i'm trying to create a function that takes in a vector by reference and if it sees a vector entry 2, it would take delete the entry and replace it with 4 copies of 5.
so if the vector is 222 (then it is size n = 3), i want 555555555555 as the new vector
however, it only works properly for the first few, when the index is < n.
so right now, it would change vector a to be 555522 any ideas how to make the vector resize?
void replace2 (vector <int>* a, int n){
for (int i = 0; i < n; ++i){
if ((*a)[i] == 2){
(*a).erase((*a).begin() + i);
for(int j = 0; j < 4; ++j){
(*a).insert((*a).begin() + i, 5);
}
}
}
}
The problem with using
for ( int i = 0; i < n; ++i ) { ... }
has already been pointed out in one of the comments:
After the first iteration of the loop,
(*a)[i]
no longer equals 2. Remaining iterations do nothing.
Your function will be simplified if you iterate from the end of the vector and go back.
Also, pass a reference to the vector instead of a pointer.
Here's a complete program:
#include <vector>
#include <iostream>
void replace2(std::vector <int>& a, int n){
for (int i = n-1; i >= 0; --i){
if (a[i] == 2){
a.erase(a.begin() + i);
for(int j = 0; j < 4; ++j){
a.insert(a.begin() + i, 5);
}
}
}
}
int main()
{
std::vector<int> a{2, 2, 2};
replace2(a, 3);
for(auto item : a )
{
std::cout << item;
}
std::cout << std::endl;
}
See it working at https://ideone.com/0Lip5j .
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.