从以下示例代码开始:
class cmp
{
public:
bool operator()(int a, int b) { return a<=b; }
};
int main()
{
set<int, cmp> s;
s.insert(2);
s.insert(2);
s.insert(4);
s.insert(5);
s.insert(6);
copy(s.begin(), s.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
multiset<int> ms;
ms.insert(2);
ms.insert(2);
ms.insert(4);
ms.insert(5);
ms.insert(6);
copy(ms.begin(), ms.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
return 0;
}
集合 - 包含唯一值。
多集 - 可以包含重复值。
但在我的集合实现中,我更改了谓词以接受重复值。如果我们仅通过更改谓词就可以做到这一点,拥有两个不同容器的目的是什么?
我相信功能也是一样的,实现也是一样的(平衡树)。如果我遗漏了什么,有人可以详细说明吗?
最佳答案
Compare
关系必须是strict-weak ordering(在这两种情况下)§23.2.4/2:
Each associative container is parameterized on
Key
and an ordering relationCompare
that induces a strict weak ordering (25.4) on elements ofKey
. [...]
和§25.4/4:
The term strict refers to the requirement of an irreflexive relation (
!comp(x, x)
for allx
), [...]
您的定制Compare
( cmp
) 不满足此要求,因此您的 std::set<int, cmp>
的行为未定义。
关于c++ - set 和 multiset 只是一个谓词不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41180181/