Given following vectors:
std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};
In the end I want foo
to contain values { 10, 2, 30, 4, 50, 6, 70 }
meaning replacing all odd values.
I've tried the algorithm std::replace_if, but how to access the bars corresponding value?
// replace_copy_if example
#include <iostream> // std::cout
#include <algorithm> // std::replace_copy_if
#include <vector> // std::vector
bool IsOdd (int i) { return ((i%2)==1); }
int main () {
std::vector<int> foo{1,2,3,4,5,6,7};
std::vector<int> bar{10,20,30,40,50,60,70};
std::replace_if (foo.begin(), foo.end(), IsOdd, 0);
std::cout << "foo contains:";
for (auto i: foo){ std::cout << ' ' << i; }
std::cout << '\n';
return 0;
}
// output : foo contains: 0 2 0 4 0 6 0
// desired output : foo contains: 10 2 30 4 50 6 70
To replace an element in Java Vector, set() method of java. util. Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.
To change the value of a vector item, we refer to their index number or position in the given vector inside brackets [] . We then assign it to a new value.
vector:: assign() is an STL in C++ which assigns new values to the vector elements by replacing old ones. It can also modify the size of the vector if necessary.
You can use the std::transform
overload that takes two input iterator ranges:
std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(),
[](auto const& a, auto const& b) {
if (a % 2)
return b;
return a;
}
);
Adding to the answers here you can make a function of your own:
Demo: https://godbolt.org/z/yf3jYx
void IsOdd (const std::vector<int>& a, std::vector<int>& b) {
for(size_t i = 0; i < a.size() && i < b.size(); i++){
if(b[i] % 2 == 1)
b[i] = a[i];
}
}
and call it in main:
IsOdd(bar, foo);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With