简体   繁体   中英

vector list initializer and assignment

For the two snippet of code, i don't understand the second one

1st: it prints 0 1 2 as expected

  vector<int> ivec;
  ivec={0,1,2};
  for(auto i: ivec){
    cout<<ivec[i]<<endl;
  }

2nd: it prints 0 0 0 5. How is this random value generated?

  vector<int> ivec;
  ivec={0,1,2};
  ivec={4,5,9,1};
  for(auto i: ivec){
    cout<<ivec[i]<<endl;
  }

This is undefined behavior because ivec has size 4 yet you are indexing elements such as 4 , 5 , and 9 which are out of bounds.

for(auto i : ivec){
  cout << ivec[i] << endl;
}

Instead you should be printing the elements themselves

for(auto i : ivec){
  cout << i << endl;
}

To be clear, in your range-based for loop i is the actual element not the index of the element. If you wanted to use indices you would not use a range-based for loop

for(std::size_t i = 0; i < ivec.size(); ++i){
  cout << ivec[i] << endl;
}

this loop here:

for(auto i : ivec)

is not the same as

for(int i =0; ...)

when you do

for(auto i: ivec){ // with ivec value to {4,5,9,1};
   cout<<ivec[i]<<endl;
} 

then you do:

 cout << ivec[4] << endl; // Undefined Behav...
 cout << ivec[5] << endl; // Undefined Behav...
 cout << ivec[9] << endl; // Undefined Behav...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM