how to create a 2D vector no entry

Feb 16, 2010 at 8:16pm
I would like to read a text file and fill it into a 2D vector but the size is unknown.

If i know the size of row and column i can create the vector like

 
vector<vector<int>> adjMat(500, vector<int>(500));


How do you define it when the size is only known after reading everything from the input file.

Any help would be appreciated!!
Feb 16, 2010 at 8:22pm
how about vector<vector<int>> adjMat; ?
Feb 16, 2010 at 8:26pm
1
2
3
4
5
6
7
8
9
10
11
12
// create an empty container
deque<deque<int> > container;
//              ^ this space will keep the compiler from interpreting >> as a single token

// use a temporary to create a row
deque<int> temp;
temp.push_back( 1 );
temp.push_back( 2 );
temp.push_back( 3 );

// store the row
container.push_back( temp );


Note that a vector will resize (since its reserve size cannot be specified ahead of time) resulting in a number of costly resizes (depending on the number of elements). A deque is probably more suitable.
Last edited on Feb 16, 2010 at 8:28pm
Feb 16, 2010 at 8:34pm
I don't necessarily agree that a deque is better without knowing more of the requirements. You can resize the vector's after reading the info from the file if there is some kind of parameter at the start of the file that tells you how many elements are needed or if there is another way of setting the vector size prior to the point which you begin filling it.

The real question is how will you be filling the container? Do you need the data to be contiguous within each vector? How will you use the container once it is filled? A deque could definitely be a better choice but it depends on a number of factors.
Feb 16, 2010 at 8:48pm
Agreed, container choice should be based on the requirements. I suppose it should be said that if neither contiguous storage nor random access is a requirement then a list might be even better.
Feb 18, 2010 at 6:56am
Thats the beauty of a vector over an array.....you don`t need to predefine the vector size before you load or initialize it. You could envisage a 'line' vector in which each vector element held a string terminated by '\n'.
Feb 18, 2010 at 7:50am
i am not getting , so what should we use .. only vector or list .
Topic archived. No new replies allowed.