仅使用迭代器从两个向量中删除重复项

Erasing duplicates from two vectors using only iterators

如何仅使用迭代器从两个字符串向量中删除重复项(从两个向量中删除它们)?

我想这行不通,因为如果值已经被删除,它们将无法进行比较,但我想不出任何其他解决方案,前提是我有一个功能可以同时擦除两个元素。

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

我可以建议以下方法。在下面的演示程序中,为了简单起见,我使用了 std::vector<int> 类型的向量。

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

程序输出为

4
5