By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,332 Members | 1,427 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,332 IT Pros & Developers. It's quick & easy.

how to insert elements in a 2d vector?

P: 4
I encounter problems in inserting elements in a 2d vector. For example I want to insert 99 in v[2][5], how would I do it? What I have is this code:
Expand|Select|Wrap|Line Numbers
  1.  
  2.   #include <iostream>
  3. #include <iomanip>
  4. #include <vector>
  5.  
  6. int main()
  7. {
  8.   std::vector< std::vector<int> > v;
  9.  
  10.   for ( int i = 0; i < 10; i++ ) {
  11.     v.push_back ( std::vector<int>() );
  12.  
  13.     for ( int j = 0; j < 10; j++ )
  14.       v[i].push_back ( i + j );
  15.   }
  16.  
  17.   std::vector< std::vector<int> >::iterator row_it = v.begin();
  18.   std::vector< std::vector<int> >::iterator row_end = v.end();
  19.  
  20.   for ( ; row_it != row_end; ++row_it ) {
  21.     std::vector<int>::iterator col_it = row_it->begin();
  22.     std::vector<int>::iterator col_end = row_it->end();
  23.  
  24.     for ( ; col_it != col_end; ++col_it )
  25.       std::cout<< std::setw ( 3 ) << *col_it;
  26.     std::cout<<'\n';
  27.   }
  28.  
  29. //line 27
  30.  
  31. }
  32.  
  33.  
  34.  
I tried inserting the line v.at(2).insert(col_it-5, 99); at line 27, but what I get is a segmentation fault message (I'm doing this in Linux). I also tried v[2].insert(col_it-5, 99) and the same thing happened. What I need is to insert not to overwrite the contents of v[2][5].
Can somebody tell me what I'm doing wrong. Any other suggestions on inserting elements on a 2d vector will be greatly appreciated.
Feb 18 '07 #1
Share this Question
Share on Google+
1 Reply


Ganon11
Expert 2.5K+
P: 3,652
Are you sure you should be writing col_it - 5? Also, where in the program are you trying to insert this? You may be attempting to do this at a point when col_it is not pointing to an element in the 3rd row (index 2) of the vector.
Feb 18 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.