c++ - 如果 {x,y} 和 {y,x} 也被认为是相同的,那么删除 vector <pair<A,A>> 中的重复项的最简单方法是什么?

标签 c++ vector std-pair

如果 2 对 {x,y} 和 {y,x} 也被视为重复,是否有内置方法可以删除对 vector 的重复项?

例如,如果我有这样的 vector :

{{1,2},{4,3},{2,1},{5,6},{1,2},{3,4},{0,1}}

我想删除重复的内容,变成:

{{1,2},{4,3},{5,6},{0,1}}

是否有任何内置函数可以处理 {x,y} 和 {y,x} 相同的情况?

如果没有,最简单的方法是什么?

我考虑过使用类似的 for 循环,但不起作用:

vector<int> isRemove;
int count=0;
for(pair<int,int> a : p){
    isRemove.push_back(0);
    for(pair<int,int> b : p){
        if((a.first==b.first && a.second==b.second) || (a.first==b.second && a.second==b.first)){
            isRemove[count]=1;
            break;
        }
    }
    count++;
}
for(int i=isRemove.size()-1;i>=0;i--){
    printf("%d\n",isRemove[i]);
    if(isRemove[i]){
        p.erase(p.begin()+i);
    }
}

还有其他更简单的方法吗?

最佳答案

std::set拥有独特的值(value)观。唯一性由 comparator 决定。您可以按如下方式实现您想要的解决方案( live example ):

#include <algorithm>
#include <iostream>
#include <set>
#include <vector>

struct custom_comparator {
    bool operator()(const std::pair<int, int>& a,
                    const std::pair<int, int>& b) const
    {
        return less_comparator(std::minmax(a.first, a.second),
                               std::minmax(b.first, b.second));
    }

    std::less<std::pair<int, int>> less_comparator;
};

int main() {
    // Input data including some duplicates
    std::vector<std::pair<int, int>> a = {
        {1, 2}, {4, 3}, {2, 1}, {5, 6}, {5, 6}, {6, 5}, {1, 2}, {3, 4}, {0, 1}
    };

    // Specify custom comparator for the set
    std::set<std::pair<int, int>, custom_comparator> unique;

    // Fill the set
    for (const auto& p : a) {
        unique.insert(p);
    }

    // Demonstrate uniqueness by outputting the elements of the set
    for (const auto& p : unique) {
        std::cout << p.first << ", " << p.second << "\n";
    }

    return 0;
}

输出:

0, 1
1, 2
4, 3
5, 6

您只需使用自定义比较器定义一个集合,以确保调用 std::less 时每对内的顺序一致,然后填充该集合。

关于c++ - 如果 {x,y} 和 {y,x} 也被认为是相同的,那么删除 vector <pair<A,A>> 中的重复项的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32841293/

相关文章:

c# - 如何使 Visual Studio 2010 将文件扩展名识别为 C#/ASPX/C/C++ 文件?

c++ - const 到非常量指针模板参数转换

css - Openlayers Feature.Vector 只使用默认样式

c++:pair.h 编译器错误 - pair 的类型不完整

c++ - 编译 Spirit 示例时出错

c++ - 首先从目录中读取较新的文件 - C++

c++ - popen 管道会减慢其他线程的速度

c++ - 对值读取错误 C++

c++ - 如何修复 C++ 中的 'Segmentation fault' 错误

c++ - 在线程中访问 vector.front() 会导致运行时错误