0

I want a program that creates an undetermined amount of lists. The size of each list is fixed, but I can't determine at compile time how many lists am I going to need.

I understand I cannot create a vector of arrays. I also understand I can use a vector of vectors, but I wonder if this is the best efficient way to do it considering the fact I need to reserve a fixed amount of memory each time I need a new array.

4
  • 2
    Fixed-length and static are not the same thing. Commented Mar 2, 2015 at 9:55
  • Ahm... But fixed length allows you to create static arrays, and non-fixed does not, Does it? Commented Mar 2, 2015 at 10:00
  • You should wrap your list data type in a class of its own, and use std::array as its underlying storage. If you can't use C++11, you are probably better off using vectors rather than legacy C arrays. Any performance loss will probably be utterly insignificant. Commented Mar 2, 2015 at 10:04
  • 1
    All static arrays are fixed-length, but not all fixed-length arrays are static. Your arrays are not static. Commented Mar 2, 2015 at 10:06

2 Answers 2

5

Erm, you can use a vector of arrays, for example,

std::vector<std::array<T, N>> some_vec;
Sign up to request clarification or add additional context in comments.

6 Comments

That solved my question. Will vector <array<array<int,2>, 64>> create a vector of a 2x64 elements?
@D1X yes, it is declaring a vector of arrays of size 64 where each array entry is an array of two ints, if that's what you are after..
And one more question: Let's suppose I have declared vector<array<array<short,2>,64>> sol and I want to copy the stack stack<array<short,2> lifo to the first element in vector sol. Is this correct? sol[0]=lifo;
It should be std::vector<std::array<T, N> > some_vec; (note the space between the two >), otherwise the compiler will complain about invalid use of the >> operator.
@luator, std::array implies c++11, which means that you no longer need spaces between the angle brackets! You should upgrade your compiler (or standard!)
|
2

@Nim is right, but I cannot upvote yet :p Also his solution is C++11.

Another alternative which is to be preferred over std::vector<std::vector<T> > is to have one vector with the dimensions X * Y. Then you can access your elements with v[y * Y + x];

This works with all versions of C++ and should be just as efficient as the std::vector<std::array<T, N> > solution.

1 Comment

if boost is already used, then yes. but I would not require boost just for that ;-) but yeah, boost is cool :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.