【发布时间】:2014-10-21 00:17:39
【问题描述】:
#include <algorithm>
#include <iostream>
#include <list>
#include <vector>
class Int
{
public:
Int(int i = 0) : m_i(i) { }
public:
bool operator<(const Int& a) const { return this->m_i < a.m_i; }
Int& operator=(const Int &a)
{
this->m_i = a.m_i;
++m_assignments;
return *this;
}
static int get_assignments() { return m_assignments; }
private:
int m_i;
static int m_assignments;
};
int Int::m_assignments = 0;
int main()
{
std::list<Int> l({ Int(3), Int(1) });
l.sort();
std::cout << (Int::get_assignments() > 0 ? 1 : 0);
std::vector<Int> v({ Int(2), Int() });
std::sort(v.begin(), v.end());
std::cout << (Int::get_assignments() > 0 ? 2 : 0) << std::endl;
return 0;
}
上面的代码打印出02,这意味着std::list::sort()不对列表的元素执行任何赋值操作(operator=()),而std::sort()确实对@987654326的元素执行至少1个赋值操作@。
差异源于什么?容器类?排序实现? Int 类的实现?
【问题讨论】:
-
list::sort不允许使迭代器/对元素的引用无效,因此它不能复制/移动它们。作为一个双向链表,它通过修改指向前一个/下一个元素的指针来执行排序。
标签: c++ c++11 stl assignment-operator