【问题标题】:STL set with custom comparator allows duplicate elements使用自定义比较器设置的 STL 允许重复元素
【发布时间】:2014-06-30 13:24:14
【问题描述】:

以下代码是产生问题的简化示例。

许多字符串 (char*) 被插入到一个集合中,其中许多是非唯一的。应该检测到重复的字符串,并返回指向原始插入的指针;但是,有时这不会发生,并且已经插入的字符串会再次插入,就好像它不存在一样。

结果集应包括:“aa”、“bb”、“cc”。 输出显示集合以:“bb”、“cc”、“aa”、“bb”结尾。 更改首先插入的字符串似乎会更改“允许”的重复项。

字符串上的数字前缀没有被使用,但被添加以确保每个字符串都有一个唯一的指针;没有它们,问题仍然存在。

使用默认的比较器和不带前缀的字符串确实可以按预期工作,但这只是比较指针;为字符串添加前缀会产生唯一的指针并插入所有字符串。

#include <iostream>
#include <set>
#include <cstring>

using std::cout;
using std::endl;
using std::set;
using std::pair;

typedef set<const char*>::const_iterator set_iter;

struct cmp_op {
    int operator() (const char* x,const char* y) const {
        int r = strcmp(x,y);
        //cout << "cmp: " << x << ((r)?((r>0)?" > ":" < "):" == ") << y << endl;
        return r;
    }
};

int main() {
    //first char ignored, just ensures unique pointers
    const char* a[] = {"1bb","2aa","3aa","4bb","5cc","6aa","7bb","8cc","9bb"};
    const size_t n = sizeof(a)/sizeof(*a);

    //using custom (strcmp) comparator
    set<const char*,cmp_op> s;

    for (int i=0; i<n; ++i) {
        cout << "insert(" << (void*)(a[i]+1) << "=" << (a[i]+1) << ")" << endl;
        pair<set_iter,bool> r = s.insert(a[i]+1);
        if (r.second) cout << "OK";
        else {cout << "dup => " << (void*)(*r.first) << "=" << (*r.first);}
        cout << endl << endl;
    }

    cout << n << " strings, " << s.size() << " unique:" << endl;
    set_iter it=s.begin();
    cout << (void*)(*it) << "=" << *it;
    while (++it!=s.end())
        cout << ", " << (void*)(*it) << "=" << *it;
    cout << endl;

    return 0;
}

我在 Windows 上使用 MinGW 和 GCC 4.8.1;使用 Ubuntu 进行测试会产生相同的结果。

【问题讨论】:

    标签: c++ stl set comparator


    【解决方案1】:

    您的比较函数没有实现严格的弱排序,因为只要 LHS 不等于 RHS,它就会返回 true。当一个“小于”另一个时,您需要更改逻辑以返回 true。这是一个例子,这似乎是一种自然的选择:

    return r < 0;
    

    请注意,为了明确意图,最好返回bool:

    bool operator() (const char* x, const char* y) const 
    {
      return strcmp(x, y) < 0;
    }
    

    【讨论】:

    • 所以比较器只是一个less_than,而不是一个完整的比较?好的,现在它可以工作了。谢谢。
    • @user3790259 它必须实现严格的弱排序,所以任何理智的“小于”或“大于”都可以。如果您不关心集合中元素的特定顺序,则选择是任意的。
    • 将其视为bool operator() 而不是int operator()
    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多