C++ std::set and std::multiset

C++ std::set and std::multiset

本文关键字:std multiset and set C++      更新时间:2023-10-16

在c++中,默认std::setstd::multiset都有std::less<T>作为比较器。谁能解释一下为什么std::multiset允许重复而std::set不允许?

两者都从现有内容的等效upper_bound开始,为新条目找到正确的插入点。

std::set然后检查是否找到一个键等于新键的现有项,如果是,返回失败信号。

std::multiset只是在该点插入新项(如果它在上面的步骤中没有返回,std::set也会这样做)。

继续Jerry的回答,注意std::setstd::multiset假定元素通过operator<的严格弱排序是可比较的。特别是,元素不必在operator== 下具有可比性。std::set只允许不等价的元素,而std::multiset允许额外的等价的元素。这与相等/不相等略有不同。两个元素AB!(A < B) && !(B < A)时是相等的,std::set::insert检查的是后一个条件,如果为真,则不插入该元素。

示例Live on Ideone

#include <iostream>
#include <set>
struct Foo
{
    int _x, _y, _z;
    Foo(int x, int y, int z): _x(x), _y(y), _z(z) {}
    bool operator<(const Foo& rhs) const // weak majorization
    {
        return (_x < rhs._x) && (_x + _y < rhs._x + rhs._y) &&
               (_x + _y + _z < rhs._x + rhs._y + rhs._z) ; 
    }
};
int main()
{
    std::set<Foo> setFoo;
    // try to insert 2 equivalent elements
    setFoo.insert(Foo{1, 2, 3}); 
    if(setFoo.insert(Foo{1, 2, 0}).second == false) // failed to insert
        std::cout << "Equivalent element already in the set!" << std::endl;
}