矢量的通用矢量在C + + [英] Generic vector of vectors in C++
问题描述
在C ++中有一个好的方法来实现(或伪造)一个向量的通用向量的类型?
Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?
忽略一个向量的向量一个好主意(除非有一些等价的东西总是更好)。假设它确实对问题建模,并且矩阵没有准确地建模问题。假设模板函数把这些东西作为参数确实需要操作结构(例如调用push_back),所以他们不能只是一个支持 [] []
。
Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. Assume also that templated functions taking these things as parameters do need to manipulate the structure (e.g. calling push_back), so they can't just take a generic type supporting [][]
.
我想要做的是:
template<typename T>
typedef vector< vector<T> > vecvec;
vecvec<int> intSequences;
vecvec<string> stringSequences;
但是这是不可能的,因为typedef不能模板。
but of course that's not possible, since typedef can't be templated.
#define vecvec(T) vector< vector<T> >
是关闭的,并且会保存在vecvec上操作的每个模板函数上重复的类型,
is close, and would save duplicating the type across every templated function which operates on vecvecs, but would not be popular with most C++ programmers.
推荐答案
您希望拥有template-typedefs。这是不是但目前的C ++支持。一种解决方法是执行
You want to have template-typedefs. That is not yet supported in the current C++. A workaround is to do
template<typename T>
struct vecvec {
typedef std::vector< std::vector<T> > type;
};
int main() {
vecvec<int>::type intSequences;
vecvec<std::string>::type stringSequences;
}
在下一个C ++(称为c ++ 0x,c ++ 1x due到2010),这将是可能的:
In the next C++ (called c++0x, c++1x due to 2010), this would be possible:
template<typename T>
using vecvec = std::vector< std::vector<T> >;
这篇关于矢量的通用矢量在C + +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!