Jon*_*Jon 12
这项工作的工具是std::replace:
std::vector<int> vec { 3, 3, 6, /* ... */ };
std::replace(vec.begin(), vec.end(), 3, 54); // replaces in-place
Run Code Online (Sandbox Code Playgroud)
您可以使用replace或replace_if算法.
#include<vector>
#include<algorithm>
#include<iostream>
#include<iterator>
using namespace std;
class ReplaceFunc
{
int mNumComp;
public:
ReplaceFunc(int i):mNumComp(i){}
bool operator()(int i)
{
if(i==mNumComp)
return true;
else
return false;
}
};
int main()
{
int arr[] = {3, 3, 6, 4, 9, 6, 1, 4, 6, 6, 7, 3};
std::vector<int> vec(arr,arr + sizeof(arr)/sizeof(arr[0]));
cout << "Before\n";
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, "\n"));
std::replace_if(vec.begin(), vec.end(), ReplaceFunc(3), 54);
cout << "After\n";
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, "\n"));
return 0;
}
Run Code Online (Sandbox Code Playgroud)