如果集合中元素的值發生更改,則排序可能不再正確。正如這個小程序所示:如何告訴std ::設置爲'刷新'其排序?
#include <algorithm>
#include <iostream>
#include <set>
#include <string>
struct Comp
{
bool operator()(const std::string * lhs, const std::string * rhs)
{
return *lhs < *rhs;
}
};
int main()
{
typedef std::set<std::string*, Comp> MySet;
MySet mySet;
std::string * a = new std::string("a");
mySet.insert(a);
std::string * c = new std::string("c");
mySet.insert(c);
std::string * b = new std::string("b");
mySet.insert(b);
for (MySet::iterator it = mySet.begin(); it != mySet.end(); ++it)
{
std::cout << *(*it) << std::endl;
}
// Ouput has correct order:
// a
// b
// c
*b = "z";
std::cout << std::endl;
std::string * d = new std::string("d");
mySet.insert(d);
for (MySet::iterator it = mySet.begin(); it != mySet.end(); ++it)
{
std::cout << *(*it) << std::endl;
}
// Output no longer ordered correctly:
// a
// d
// z
// c
return 0;
}
如何告訴設置'刷新'其內部排序?
值不應該改變。 'value_type`應該是`std :: set`(儘管我相信VS不遵守這個規則?) –
2012-02-01 14:34:28
值類型是用戶通過的,並且添加了一個頂級const。如果用戶傳遞`std :: string *`,值類型將是`std :: string * const`。沒有規定禁止用戶傳遞不強制值的排序位置的不變性的事物;有一條規則說,以這種方式修改值會產生未定義的行爲。 – 2013-10-18 16:12:20