c++ - set 和 multiset 只是一个谓词不同吗?

标签 c++ stl

从以下示例代码开始:

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 relation Compare that induces a strict weak ordering (25.4) on elements of Key. [...]

和§25.4/4:

The term strict refers to the requirement of an irreflexive relation (!comp(x, x) for all x), [...]

您的定制Compare ( cmp ) 不满足此要求,因此您的 std::set<int, cmp> 的行为未定义。

关于c++ - set 和 multiset 只是一个谓词不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41180181/

相关文章:

c# - MarshalAs(UnmanagedType.ByValArray, SizeConst 大小限制

c++ - 停留在一个基本的 OpenGL 程序上

c++ - 如何准确地按照要求格式化我的输出?

c++ - 替代关键字表示

c++ - 带有 GNU STL 的 GCC 4.8 为 std::string 构造函数生成错误代码?

c++ - 使用迭代器范围将单个元素附加到容器

c++ - 这段代码中如何使用 map<string, set<string>>?

c++ - std::to_chars() 最小浮点缓冲区大小

c++ - set_union() 返回的迭代器

c++ - 此示例中使用的运算符 "<"在哪里?