c++ - 任意结构上的 set_union - 我哪里出错了?

标签 c++ algorithm struct

这是我之前 post 的延续这告诉我该怎么做很好,但实现它并没有奏效:S。我想要的只是 C++ 算法类中的 set_union(和其他集合操作)来处理我的结构。这是我目前所拥有的。

我的结构:

struct player {
    int lbl;
    int lbl1;

    bool operator<(const player &t) const {
        return (lbl < t.lbl && lbl1 < t.lbl);
    }
};

它在我的结构上定义了 < 运算符,即如果一个玩家的两个标签(整数)都小于另一个玩家的标签,则该玩家比另一个玩家“小”。

然后执行 set_union 我这样做:

    player p1;
    p1.lbl = 1;
    p1.lbl1 = 3;

    player p2;
    p2.lbl = 3;
    p2.lbl1 = 5;

    player p3;
    p3.lbl = 2;
    p3.lbl1 = 8;

    player p4;
    p4.lbl = 1;
    p4.lbl1 = 7;

    vector<player> v1;
    vector<player> v2;
    v1.push_back(p2);
    v1.push_back(p1);
    v2.push_back(p3);
    v2.push_back(p4);

    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());

    vector<player> v;
    set_union(v1.begin(), v1.end(), v2.begin(), v2.end(),
              back_inserter(v));

    for(int i = 0; i < v.size(); i++) {
        cout << v.at(i).lbl << ", " << v.at(i).lbl1 << endl;
    }

打印:

1, 3
3, 5

什么时候应该打印

1, 3
3, 5
2, 8
1, 7

因为它是集合并集。我可能在某处的结构定义中出错了?相同的 set_union 适用于字符串和整数的 vector ,所以它可能是我的播放器结构?

谢谢。

附加代码

我的实际结构代码如下(Nawaz 建议进行更正)。我最初发布了一个简化版本,但我可能需要发布所有版本:

struct player {
    int i;
    int lbl;
    int lbl1;
    argument argu;
    string player_name;

    player(string player_name);

    bool operator<(const player &t) const {
        if ( lbl != t.lbl )
            return lbl < t.lbl;
        return lbl1 < t.lbl1;
    }

};

最佳答案

你应该实现 Strict weak ordering , 因为 关联容器 例如 std::set, std::multiset, std::map, std::multimap 要求元素的顺序必须是Strict Weak Ordering .在您的情况下,set_union 根据 std::set 规则对数据进行操作,这需要严格的弱排序,但您的比较函数不需要'实现它。这就是问题所在!

还要注意什么the documentation of std::set_union在 cplusplus 上说,

Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument goes before the second argument in the specific strict weak ordering it defines, and false otherwise.

所以,你的比较函数应该是这样的:

struct player {
    int lbl;
    int lbl1;

    bool operator<(const player &t) const 
    {
        if ( lbl != t.lbl )
               return lbl < t.lbl;
        return lbl1 < t.lbl1;
    }
};

这将给出正确的输出。请参阅此在线演示:

http://www.ideone.com/d4Kob

关于c++ - 任意结构上的 set_union - 我哪里出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6298333/

相关文章:

algorithm - 当目标状态的确切权重未知时,A* 中的启发式算法

javascript - 3Sum leetcode算法

algorithm - 我的二进制搜索算法 (a) 正确且 (b) 有效吗?

c - 使用另一个 char 数组从 struct 设置一个 char 数组

c++ - 尝试对结构数组使用选择排序

c++ - AttributeError :/usr/lib/libgdal. so.1: undefined symbol :OGR_F_GetFieldAsInteger64 在 Docker 中安装时

c++ - 为什么 std::exception 在 VC++ 中有额外的构造函数?

c++ - 如何在具有相同第一个索引的二维矩阵中添加值 (c++)

c++ - 使用STL从字符串中删除重复字符

c - 尝试编译 .h 文件时出现错误。缺少分号