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

前端 未结 4 2018
抹茶落季
抹茶落季 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: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 
    #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
    

提交回复
热议问题