为什么 [std::unique] 不能应用于 [std::multiset]?
Why can't [std::unique] apply to [std::multiset]?
#include <set>
#include <algorithm>
using namespace std;
int main()
{
multiset<int> coll{ 1, 1, 2 };
unique(coll.begin(), coll.end()); // error
}
为什么 std::unique
不能应用于 std::multiset
?
因为std::unique改变(通过移动)移动赋值传入的范围[first, last)中的元素。这意味着它要求解引用迭代器的类型必须满足 MoveAssignable 的要求。
Type requirements
- ForwardIt must meet the requirements of ForwardIterator.
- The type of dereferenced ForwardIt must meet the requirements of MoveAssignable.
但std::multiset的迭代器为const迭代器(C++11起),不符合要求。不能通过它们移动赋值的元素。
std::multiset
是内部排序的容器,std::unique
是改变容器中元素的位置。 std::unique
在它的实现中使用了 container::iterator_type
,由于 std::multiset
的结构是严格的,它只有 const_iterator_type
。因此 std::unique
不能应用于 std::multiset
类型。
在引入 c++11 之前,可以更改 std::multimap
的内部结构,因此可以在此类容器上应用 std::unique
。
std::unique
不会从范围中删除重复值。相反,它将它们移动到范围的末尾(通过交换输入序列中的两个元素)。在 std::multiset
和其他关联容器中,元素的顺序由排序谓词定义,用户不能更改。此限制是通过使 std::multiset
的非常量迭代器与其 const_iterator
有点相似来实现的(即,您不能通过其非常量迭代器修改 std::multiset
的元素)。
#include <set>
#include <algorithm>
using namespace std;
int main()
{
multiset<int> coll{ 1, 1, 2 };
unique(coll.begin(), coll.end()); // error
}
为什么 std::unique
不能应用于 std::multiset
?
因为std::unique改变(通过移动)移动赋值传入的范围[first, last)中的元素。这意味着它要求解引用迭代器的类型必须满足 MoveAssignable 的要求。
Type requirements
- ForwardIt must meet the requirements of ForwardIterator.
- The type of dereferenced ForwardIt must meet the requirements of MoveAssignable.
但std::multiset的迭代器为const迭代器(C++11起),不符合要求。不能通过它们移动赋值的元素。
std::multiset
是内部排序的容器,std::unique
是改变容器中元素的位置。 std::unique
在它的实现中使用了 container::iterator_type
,由于 std::multiset
的结构是严格的,它只有 const_iterator_type
。因此 std::unique
不能应用于 std::multiset
类型。
在引入 c++11 之前,可以更改 std::multimap
的内部结构,因此可以在此类容器上应用 std::unique
。
std::unique
不会从范围中删除重复值。相反,它将它们移动到范围的末尾(通过交换输入序列中的两个元素)。在 std::multiset
和其他关联容器中,元素的顺序由排序谓词定义,用户不能更改。此限制是通过使 std::multiset
的非常量迭代器与其 const_iterator
有点相似来实现的(即,您不能通过其非常量迭代器修改 std::multiset
的元素)。