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

doubt with stl vector

P: 6
if I have :

vector<int> one(4);
vector<int> two(4);

and say we assigned 0s to all the elements of one and 1s to all the element of two. and than we do :

one = two;

in this case the contents of two are copied to contents of one.

But instead if we do like this :

vector<int> one;
vector<int> two;

one.reserve(4);
two.reserve(4);

and than do the same assignments than the contents of two are not copied to the vector one...


why does this happen ?

thanks in advance.
Feb 24 '07 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 1,510
no obvious reason why assignment should not work
do you initialise one and two in the case
Expand|Select|Wrap|Line Numbers
  1. vector<int> one;
  2. vector<int> two;
  3.  
  4. one.reserve(4);
  5. two.reserve(4);
  6.  
if so what with what values and what are the values of the elements of one after the assignment
Expand|Select|Wrap|Line Numbers
  1. one = two;
Feb 24 '07 #2

P: 6
Yeah I mentioned that in the post that I initialize the elements of one and two with different integer values.

say something like

one[0] = one[1] = one[2] = one[3] = 0;
two[0] = two[1] = two[2] = two[3] = 1;

and after we do:

one = two

the values of one[] are still the same old values i.e. "0"
Feb 24 '07 #3

Expert 100+
P: 1,510
when I run the following program
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. int main()
  5. {
  6.   vector<int> one(4);
  7.   vector<int> two(4);
  8.   one.reserve(4);
  9.   two.reserve(4);
  10.   one[0] = one[1] = one[2] = one[3] = 0;
  11.   two[0] = two[1] = two[2] = two[3] = 1;
  12.    cout << "\n one " ;
  13.    for (int i=0; i< one.size() ; i++) cout << one[i] << " ";
  14.    cout << "\n two " ;
  15.    for (int i=0; i< two.size() ; i++) cout << two[i]  << " ";
  16.    cout << endl<< endl;
  17.  
  18.    one = two;               // ** assign two to one
  19.    cout << "\n one " ;
  20.    for (int i=0; i< one.size() ; i++) cout << one[i] << " ";
  21.    cout << "\n two " ;
  22.    for (int i=0; i< two.size() ; i++) cout << two[i]  << " ";
  23.    cout << endl<< endl;
  24.    system("pause");
  25. }
  26.  
it gives
one 0 0 0 0
two 1 1 1 1

one 1 1 1 1
two 1 1 1 1
Press any key to continue . . .

tried it with gcc and Borlan CBuilder 5 - which compiler are you using?
post your code and we can try it?
Feb 25 '07 #4

Post your reply

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