如何在C++中替换向量中的特定值?

bob*_*lob 3 c++ swap replace vector

我有一个带有一些值的向量(3,3,6,4,9,6,1,4,6,6,7,3),我想用54替换每个3或用1替换每个6,例如,等等.

所以我需要首先通过向量,得到[i]值,搜索并用54替换每个3,但仍然保持相关positions.std::setvector::swap一个好方法?我甚至不知道如何开始这个:(我不能使用push_back,因为这不会保持正确的值顺序,因为这很重要.

请保持简单; 我只是一个初学者:)

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)

看到它在行动.


Alo*_*ave 6

您可以使用replacereplace_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)