Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

push_back in vector of vectors

Status
Not open for further replies.

ARCITS

Programmer
Apr 4, 2002
99
GB
I have a vector of vectors (2D vector)

vector< vector< vector<int> > > AdjMat;

How do I use push_back with this? or is it a case of resizing and then inserting the data?

I tried AdjMat[1][1]=1 but I get and error

Any help appreciated
 
Well simplified, if you have a vector<int> then you would push_back(int) so if you have a vector< vector<int> > you have to push_back(vector<int>) and so on. So if you run a loop that sets a several vector<int> to the values needed then run another loop push_back-ing those vectors into a vector< vector<int> > and so on.
 
Note that vector< vector< vector<int> > > is actually a 3D vector.

AdjMat[1][1][1]=1

should work, or declare your vector as a 2d vector:
Code:
vector< vector<int> > AdjMat;
AdjMat[1][1]=1;
 
Thanks CodingNovice - I sort of understand the concept of your explanation but what would the syntax be in my example?

vector < vector<int> > AdjMat;

Thanks!
 
Code:
vector<int> r1;
vector < vector<int> > AdjMat;

AdjMat.push_back(r1);
AdjMat[0].push_back(1234);


Ion Filipski
1c.bmp
 
If you know the size of your matrix at the beginning, it would be better to just start the vectors off at a certain size, or if you need to change the size later just use resize. The push_back method is good if you want to add just one entry at a time.
Code:
// 10 x 20 matrix:
vector< vector<int> > AdjMat1(10, vector<int>(20));

// 10 empty vectors:
vector< vector<int> > AdjMat2(10);

// Resize 10 x 20 matrix to 30 x 30, setting new entries to 5:
int len = AdjMat1.size();
for (int i = 0; i < len; i++)
{
    AdjMat1[i].resize(30, 5);
}
AdjMat1.resize(30, vector<int>(30, 5));

// or resize 10 x 20 matrix to 30 x 30 full of the number 5:
{
    vector< vector<int> > tmpMat(30, vector<int>(30, 5));
    AdjMat1.swap(tmpMat);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top