简体   繁体   中英

Inserting elements to vector in c++

I need to insert for every element of vector it's opposite.

#include <iostream>
#include <vector>
int main() {
  std::vector < int > vek {1,2,3};
  std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl;
  for (int i = 0; i < 3; i++) {
    std::cout << i << " " << vek[i] << std::endl;
    vek.insert(vek.begin() + i + 1, -vek[i]);
  }
  std::cout << std::endl;
  for (int i: vek) std::cout << i << " ";
  return 0;
}

OUTPUT:

1 2 3
0 1  // it should be 0 1 (because vek[0]=1)
1 -1 // it should be 1 2 (because vek[1]=2)
2 1  // it should be 2 3 (because vek[2]=3)

1 -1 1 -1 2 3 // it should be 1 -1 2 -2 3 -3

Could you explain me why function insert doesn't insert the correct value of vector? What is happening here?

Note: Auxiliary vectors (and other data types) are not allowed

During the for loop, you are modifying the vector:

After the first iteration which inserts -1 , the vector becomes [1, -1, 2, 3] . Therefore, vec[1] becomes -1 rather than 2 . The index of 2 becomes 2 . And after inserting -2 into the vector, the index of the original value 3 becomes 4 .

In the for loop condition, you need to add index i by 2, instead of 1:

#include <iostream>
#include <vector>
int main() {
  std::vector < int > vek {1,2,3};
  std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl;
  for (int i = 0; i < 3 * 2; i+=2) {
    std::cout << i << " " << vek[i] << std::endl;
    vek.insert(vek.begin() + i + 1, -vek[i]);
  }
  std::cout << std::endl;
  for (int i: vek) std::cout << i << " ";
  return 0;
}

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