I have a vector with some values (3, 3, 6, 4, 9, 6, 1, 4, 6, 6, 7, 3), and I want to replace each 3 with a 54 or each 6 with a 1, for example and so on.
So I need to
Use the STL algorithm for_each. It is not required to loop, and you can do it in one shot with a function object as shown below.
http://en.cppreference.com/w/cpp/algorithm/for_each
Example:
#include
#include
#include
#include
using namespace std;
void myfunction(int & i)
{
if (i==3)
i=54;
if (i==6)
i=1;
}
int main()
{
vector v;
v.push_back(3);
v.push_back(3);
v.push_back(33);
v.push_back(6);
v.push_back(6);
v.push_back(66);
v.push_back(77);
ostream_iterator printit(cout, " ");
cout << "Before replacing" << endl;
copy(v.begin(), v.end(), printit);
for_each(v.begin(), v.end(), myfunction)
;
cout << endl;
cout << "After replacing" << endl;
copy(v.begin(), v.end(), printit);
cout << endl;
}
Output:
Before replacing
3 3 33 6 6 66 77
After replacing
54 54 33 1 1 66 77