Wei Zhang
Wei Zhang

Reputation: 325

How to replace the 2D vector corresponding to the values?

I am trying to replace the elements in a 2D vector (vector<vector<int>>). I want to change the elements not only by one value, but by a list, which means, for example, change 1,3,4,5,8,9 to 1,2,3,4,5,6 one-to-one correspondence. I have made a very slow code with double loops. Is there any way to speed up the process, with new function or sort the element? Because my 2D vector is very big, 3*300000 actually. My example code is below:

int myints[] = { 1,3,4,5,8,9 };
int myints2[] = { 1,2,3,4,5,6 };
std::vector<int> vals (myints, myints+6); 
std::vector<int> vals2 (myints2, myints2+6); 
vector<vector<int>> V0(3);
V0[0]={1,4,5};
V0[1]={3,1,8};
V0[2]={1,9,4};
for (size_t j = 0; j < V0.size(); j++)
{
    for (int i = 0; i < vals.size(); i++)
    replace(V0[j].begin(), V0[j].end(), vals[i], vals2[i]);
};

The ideal output V0 should be

1 3 4
2 1 5
1 6 3

Upvotes: 3

Views: 437

Answers (1)

javidcf
javidcf

Reputation: 59691

You can use an unordered_map to replace each value directly, instead of searching through the whole vector for each replacement:

#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    unordered_map<int, int> replacements{{1, 1}, {3, 2}, {4, 3}, {5, 4}, {8, 5}, {9, 6}};
    vector<vector<int>> v0(3);
    v0[0] = {1, 4, 5};
    v0[1] = {3, 1, 8};
    v0[2] = {1, 9, 4};
    for_each(v0.begin(), v0.end(), [&](vector<int>& v)
    {
        transform(v.begin(), v.end(), v.begin(), [&](int val)
        {
            auto it = replacements.find(val);
            return it != replacements.end() ? replacements[val] : val;
        });
    });
    // Print
    for (auto& v : v0)
    {
        cout << "[ ";
        for (auto val : v)
        {
            cout << val << ", ";
        }
    cout << "]" << endl;
    }
    return 0;
}

Output:

[ 1, 3, 4, ]
[ 2, 1, 5, ]
[ 1, 6, 3, ]

In C++17, you may also choose a parallel execution policy in for_each and/or transform, since all the changes can be done in parallel.

Upvotes: 1

Related Questions