Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11661

Difference between two vectors and new vector containing elements of the same indexes of remaining vector

$
0
0

Let us consider three vectors

std::vector<std::size_t> v1{1, 2, 3, 4, 5}std::vector<std::size_t> v2{6, 7, 8, 9, 10}std::vector<std::size_t> const v3{7, 10}  

where v2 always has the same size of v1. I want to have a vector v4, that is, the difference between v2 and v3, that is, v4 = {6, 8, 9}. Besides, I want to have a vector v5 that contains the elements of the remaining indexes of v2 in v4, that is, v5 = {1, 3, 4}. In this example, the remaining elements of v2 in v4 are v2[0], v2[2], and v2[3], this way, v5 = {v1[0], v1[2], v[3]}.

By now, I have the working code

std::vector<std::size_t> v1 = {1, 2, 3, 4, 5};    std::vector<std::size_t> v2 = {6, 7, 8, 9, 10};    std::vector<std::size_t> const v3 = {10, 7};    std::vector<int> v4;    std::vector<int> v5;    for (std::size_t i = 0; i < v2.size(); ++i)    {        if (std::find(v3.begin(), v3.end(), v2[i]) == v3.end())        {            v4.push_back(v2[i]);            v5.push_back(v1[i]);        }    }

Although the code is working, I am wordering if there is any algorithm in std that is faster and do the same job.

P.S.: neither v1, v2, and v3 has repeated elements. v3 is defined as const because it can be modified (obviously, a copy of it can be made, but more memory will be required; v3 as well as v1 and v2 can have more than 1e6 elements). v2, and so v1, is always bigger than v3. The solution can be based on c++20.

I know that there is std::set_difference from algorithm, but it just define v4. For building v5, I will need to find the indexes of the removed elements of v4 and them remove these elements from v1.


Viewing all articles
Browse latest Browse all 11661

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>