C++ std::set and std::multiset
C++ std::set and std::multiset
在c++中,默认std::set
和std::multiset
都有std::less<T>
作为比较器。谁能解释一下为什么std::multiset
允许重复而std::set
不允许?
两者都从现有内容的等效upper_bound
开始,为新条目找到正确的插入点。
std::set
然后检查是否找到一个键等于新键的现有项,如果是,返回失败信号。
std::multiset
只是在该点插入新项(如果它在上面的步骤中没有返回,std::set
也会这样做)。
继续Jerry的回答,注意std::set
和std::multiset
假定元素通过operator<
的严格弱排序是可比较的。特别是,元素不必在operator==
下具有可比性。std::set
只允许不等价的元素,而std::multiset
允许额外的等价的元素。这与相等/不相等略有不同。两个元素A
和B
在!(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;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- C++:将 std::set_union() 输出存储在 std::multiset 中
- 如何为包含最多N个元素的std::multiset调用最大数量分配
- 为什么 [std::unique] 不能应用于 [std::multiset]?
- 试图理解libstdc++对std::multiset的实现
- std::multiset::iterator = NULL 不再有效
- std::multiset<A>的模板参数 A、B 分别是什么意思,它是如何工作的?
- 在STD :: MultiSet中维护插入顺序
- 哪个元素将从 std::multimap::find 返回,同样,std::multiset::find
- std::multiset并查找中间元素
- std::multiset vs. std::<int>map<int, std::size_t> 用于保留多个可重复的整数值
- 在std::multiset中,如果找到一个元素,有一个函数或算法可以只擦除一个样本(单播或重复)
- 从std::multiset的第i个元素删除到末尾
- 用C++11将compare函数传递给std::multiset
- 输出“std::multiset”的唯一元素及其频率,使用C++中的std::算法(无循环)
- 对std::multiset内的相等范围进行排序
- 在“std::multiset”的唯一元素上迭代
- 如何使用std::multiset与多个比较器函数
- C++ std::set and std::multiset