Home > Software design >  Erasing duplicates from two vectors using only iterators
Erasing duplicates from two vectors using only iterators

Time:12-18

How can I delete duplicates from two vectors of strings ( delete them from both vectors) using only iterators? I suppose it doesn't work because if values are already deleted they can't be compared,but I can not think of any other solution, only if I had one function to erase both elements at the same time.

    void obrisiIsteRijeci(std::vector<std::string>&v1, std::vector<std::string>& v2){

 
  
  for(auto it=v1.begin();it!=v1.end();it  ){
  auto it1=it;
 
     for(auto it2=v2.begin();it2!=v2.end();it2  ){
     
      if((*(it2)==*(it1)) && (*(it1)==*(it2))){
       
       v1.erase(it1);
       v2.erase(it2);
      }

     }
     
  }
  } 

CodePudding user response:

I can suggest the following approach. In the demonstration program below I am using vectors of the type std::vector<int> for simplicity.

#include <iostream>
#include <vector>
#include <iterator>
$include <algorithm>

int main()
{
    std::vector<int> v1 = { 1, 2, 1, 2, 3, 4 }, v2 = { 1, 2, 3, 5 };

    for (auto first = std::begin( v1 ); first != std::end( v1 ); )
    {
        auto it = std::find( std::begin( v2 ), std::end( v2 ), *first );

        if (it != std::end( v2 ))
        {
            v2.erase( std::remove( it, std::end( v2 ), *first ), std::end( v2 ) );

            auto value = *first;
            auto offset = std::distance( std::begin( v1 ), first );

            v1.erase( std::remove( first, std::end( v1 ), value ), std::end( v1 ) );
            first = std::next( std::begin( v1 ), offset );
        }
        else
        {
              first;
        }
    }

    for (const auto &item : v1)
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    for (const auto &item : v2)
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';
}

The program output is

4
5
  • Related