How to replace specific values in a vector in C++?

前端 未结 4 1968
抹茶落季
抹茶落季 2021-01-06 18:50

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

相关标签:
4条回答
  • 2021-01-06 19:07

    The tool for the job is std::replace:

    std::vector<int> vec { 3, 3, 6, /* ... */ };
    std::replace(vec.begin(), vec.end(), 3, 54); // replaces in-place
    

    See it in action.

    0 讨论(0)
  • 2021-01-06 19:11

    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 <iostream>
    #include <algorithm>
    #include <vector>
    #include <iterator>
    using namespace std;
    
    void myfunction(int & i)
    {
        if (i==3)
            i=54;
        if (i==6)
            i=1;
    }
    
    
    int main()
    {
        vector<int> 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<int> 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
    
    0 讨论(0)
  • 2021-01-06 19:23

    You could loop through each element of the list.

    std::vector<int> vec{3, 3, 6, 4, 9, 6, 1, 4, 6, 6, 7, 3};
    for(int n=0;n<vec.size();n++)
        if(vec[n]==3)
            vec[n]=54;
    
    0 讨论(0)
  • 2021-01-06 19:24

    You can use the replace or replace_if algorithm.

    Online Sample:

    #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;
    }
    
    0 讨论(0)
提交回复
热议问题