c++ - 如何删除结构向量的重复项

Gab*_*ana 2 c++ vector

我有矢量运动

 vector<posToMove> movements;
Run Code Online (Sandbox Code Playgroud)

posToMove 是一个结构:

struct posToMove
{
    int fromX;
    int fromY;
    int toX;
    int toY;
};
Run Code Online (Sandbox Code Playgroud)

我想删除运动中的重复项,我该怎么做?

sil*_*fox 6

最简单的方法是使用:

movements.erase(std::unique(movements.begin(), movements.end()), movements.end());
Run Code Online (Sandbox Code Playgroud)

std::unique只删除连续重复的元素,因此您需要std::vector通过重载<==运算符对第一个元素进行排序:

struct posToMove
{
    int fromX;
    int fromY;
    int toX;
    int toY;

    bool operator < (const posToMove& other) const
    {
        //declare how 2 variable of type posToMove should be compared with <
        return std::make_tuple(fromX, fromY, toX, toY) < std::make_tuple(other.fromX, other.fromY, other.toX, other.toY);
    }

    bool operator == (const posToMove& other) const
    {
        //declare how 2 variable of type posToMove should be compared with ==
        return std::make_tuple(fromX, fromY, toX, toY) == std::make_tuple(other.fromX, other.fromY, other.toX, other.toY);
    }
};
Run Code Online (Sandbox Code Playgroud)

我用 声明<==操作符make_tuple(),但你也可以用你选择的比较来替换它。

代码 :

#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
struct posToMove
{
    int fromX;
    int fromY;
    int toX;
    int toY;

    bool operator < (const posToMove& other) const
    {
        //declare how 2 variable of type posToMove should be compared with <
        return std::make_tuple(fromX, fromY, toX, toY) < std::make_tuple(other.fromX, other.fromY, other.toX, other.toY);
    }

    bool operator == (const posToMove& other) const
    {
        //declare how 2 variable of type posToMove should be compared with ==
        return std::make_tuple(fromX, fromY, toX, toY) == std::make_tuple(other.fromX, other.fromY, other.toX, other.toY);
    }
};

std::vector<posToMove>movements;

int main()
{
    movements.push_back({0,1,0,0});
    movements.push_back({1,2,5,7});
    movements.push_back({3,9,9,6});
    movements.push_back({0,1,0,0});
    movements.push_back({4,1,8,0});
    movements.push_back({1,2,5,7});

    std::sort(movements.begin(), movements.end());

    std::cout << "After sort : \n";
    for (auto x : movements)
    {
        std::cout << x.fromX << " " << x.fromY << " " << x.toX << " " << x.toY << "\n";
    }
    std::cout << "\n";

    movements.erase(std::unique(movements.begin(), movements.end()), movements.end());

    std::cout << "After removing : \n";
    for (auto x : movements)
    {
        std::cout << x.fromX << " " << x.fromY << " " << x.toX << " " << x.toY << "\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

After sort :
0 1 0 0
0 1 0 0
1 2 5 7
1 2 5 7
3 9 9 6
4 1 8 0

After removing :
0 1 0 0
1 2 5 7
3 9 9 6
4 1 8 0
Run Code Online (Sandbox Code Playgroud)

相关:删除结构 c++ 向量中的重复项

文件: