Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic vector of vectors in C++

Tags:

c++

stl

Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?

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 [][].

What I want to do is:

template<typename T> typedef vector< vector<T> > vecvec;  vecvec<int> intSequences; vecvec<string> stringSequences; 

but of course that's not possible, since typedef can't be templated.

#define vecvec(T) vector< vector<T> > 

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.

like image 885
Steve Jessop Avatar asked Nov 16 '08 15:11

Steve Jessop


People also ask

Can I have a vector of vectors?

Yes! Yes, you can make a vector of vectors in C++. The normal vector is a one-dimensional list data structure. A vector of vectors is a two-dimensional list data structure, from two normal vectors.

What are vectors in C?

Vectors are a modern programming concept, which, unfortunately, aren't built into the standard C library. Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

Can we use vector in C?

You can't. By definition, C knows nothing of any of the required components of a std::vector , including, but not limited to: C does not have namespaces, so it can't understand the std namespace. C does not have templates, so it can't understand the std::vector<T> type.


1 Answers

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; } 

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> >; 
like image 196
Johannes Schaub - litb Avatar answered Sep 22 '22 19:09

Johannes Schaub - litb