gpt4 book ai didi

c++ - 使用自定义比较器设置的 STL 允许重复元素

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:41 26 4
gpt4 key购买 nike

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

许多字符串 (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 进行测试会产生相同的结果。

最佳答案

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

return r < 0;

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

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

关于c++ - 使用自定义比较器设置的 STL 允许重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24491172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com