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

2019-02-18 19:48发布

问题:

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 go through the vector first, get the [i] value, search and replace each 3 with a 54, but still keep relevant positions.std::set is vector::swap a good way? I am not even sure how to begin this :( I can't use push_back as that would not keep the correct order of values as that is important.

Please keep it simple; I am just a beginner :)

回答1:

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.



回答2:

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;
}


回答3:

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;


回答4:

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