Reputation: 14660
using namespace std;
vector<vector<T> > vec_collection(3);
vec_collection[0]=vector<T>(12);
vec_collection[1]=vector<T>(3);
vec_collection[2]=vector<T>(14);
Suppose I have an empty collection of 3 vectors and after initialization, I want the first, second, and third vector to be of specific size 12, 3, and 14 say. Is the above code snippet the right way to declare their sizes?
Upvotes: 1
Views: 2919
Reputation: 393467
Yes. Allthough it doesn't make the vectors fixed-size (vectors can be resized explicitely, or implicitely - e.g. using push_back
or insert
).
Finally, vectors can simply be assigned over.
If you need strongtype, fixed-size, jagged nested vectors (urrfff that's a mouth-full):
#include <tuple>
#include <array>
using std::array;
using std::tuple;
typedef tuple<
array<T, 12>,
array<T, 3>,
array<T, 14>
> vec_collection;
That would be a bit more awkward to work with, but if speed and container size guarantees were of the essence, go for it.
Note that in pre-TR1 world (say, c++98 with a c++03 library), this would be pretty close to equivalent (but even less comfortable to work with):
struct vec_collection
{
T a[12];
T b[3];
T c[14];
};
Upvotes: 3
Reputation: 126867
Your code in line of principle creates separated temporary vector
instances that replace the existing zero-size ones, which in theory means that for every of those lines you have a constructor call (create the temporary), a copy-constructor call (copy it over the existing vector
) and a destructor call (destroy the temporary).
Although I think that some optimizations could make it actually better than it sounds, it's way easier and almost surely more efficient to simply do:
using namespace std;
vector< vector<T> > vec_collection(3);
vec_collection[0].resize(12);
vec_collection[1].resize(3);
vec_collection[2].resize(14);
On the other hand, if you need such vector
s to be always of that fixed size, you should replace them with fixed-size data structures (e.g. a struct
containing three C-style arrays or std::array
), as in @sehe's answer.
Upvotes: 7
Reputation: 17622
vector< vector<T>* > vec_collection(3); // i changed it to a vector of vector<T>*
vec_collection[0]=new vector<MyType>(12);
//etc
You probably want to replace with in the code. E.g.
vector<int>(12);
Moreover, if your vector are fixed size, you can just use arrays.
Upvotes: -1
Reputation: 75150
If you have C++11, you can do it with an initialiser list, which is more efficient:
vector<vector<T>> vec_collection(3) { vector<T>(12), vector<T>(3), vector<T>(14) };
Otherwise, you can do it the way you're doing which is fine, or just call resize
on the elements like in Matteo's answer.
Upvotes: 2