【发布时间】:2014-04-08 15:06:08
【问题描述】:
Std::sort 在类属性可变时起作用。例如,以下代码有效,并且向量按预期按升序排序。
class PersonMutable
{
public:
PersonMutable(int age, std::string name):
Age(age),Name(name)
{
}
int Age;
std::string Name;
};
void TestSort()
{
std::vector<PersonMutable> people;
people.push_back(PersonMutable(24,"Kerry"));
people.push_back(PersonMutable(30,"Brian"));
people.push_back(PersonMutable(3,"James"));
people.push_back(PersonMutable(28,"Paul"));
std::sort(people.begin(),people.end(),
[](const PersonMutable& a, PersonMutable & b) -> bool
{
return a.Age < b.Age;
});
}
但是当同一个类不可变时,它与 std::sort 不兼容。
class PersonImmutable
{
public:
PersonImmutable(int age, std::string name):
Age(age),Name(name)
{
}
PersonImmutable& operator=(const PersonImmutable& a)
{
PersonImmutable b(a.Age,a.Name);
return b;
}
const int Age;
const std::string Name;
};
void TestSort()
{
std::vector<PersonImmutable> people;
people.push_back(PersonImmutable(24,"Kerry"));
people.push_back(PersonImmutable(30,"Brian"));
people.push_back(PersonImmutable(3,"James"));
people.push_back(PersonImmutable(28,"Paul"));
std::sort(people.begin(),people.end(),
[](const PersonImmutable& a, PersonImmutable & b) -> bool
{
return a.Age < b.Age;
});
}
谁能告诉我为什么?
非常感谢。
【问题讨论】:
-
你能解释一下你如何期望
std::sort在不改变序列的情况下交换元素吗? -
另外,请注意您的
operator=通过引用返回堆栈上的值,这将导致未定义的行为... -
@Agnew 从概念上讲,对序列中的元素进行排序不应该改变items,而是改变sequence 本身。 (例如:如果我手动按花色对扑克牌进行排序,我不会修改单张牌的属性;只修改它们在牌组中的位置。)问题中指出的混淆源于
std::sort实际上的 C++ 机制运行。 -
@Lilshieste:如果您对指针进行排序,卡片类比会更好 - 有效地跟踪哪些卡片在哪里而不接触卡片,但是当您考虑到矢量内容是内存位置并且它可能很多时使用赋值覆盖元素比使用破坏/复制构造(更好的是 - 交换)更有效,实际行为变得直观而可取。
-
具有
const成员的课程比他们的价值更麻烦,IMO。改为封装。