How can I replace specific values ​​in a vector in C ++?

I have a vector with some values ​​(3, 3, 6, 4, 9, 6, 1, 4, 6, 6, 7, 3) and I want to replace every 3 with 54 or every 6 1, for example, etc. .d.

So I need to go through the vector first, get the value of [i], find and replace every 3 with 54, but still keep the corresponding positions.std::set

vector::swap

good way? I'm not even sure how to start this :( I can't use push_back

it as it won't preserve the correct order of the values ​​as it's important.

Please keep it simple; I'm just a beginner :)

+3


source to share


4 answers


Tool for the job std::replace

:

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

      



Look at the action .

+12


source


You can use replace or replace_if .

Online example:



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

      

+6


source


You can scroll through each item in 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;

      

+1


source


Use STL algorithm for_each

. This is not required for the loop and you can do it in one shot using the 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


source







All Articles