セット内の要素の値が変更された場合、順序が正しくない可能性があります。この小さなプログラムに示すように、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はそれに従わないと思いますが) –
値の型はユーザーが渡したもので、トップレベルのconstが追加されています。ユーザが 'std :: string *'を渡すと、値の型は 'std :: string * const'になります。ユーザーが値のソート位置の不変性を強制しないものを渡すことを禁じるルールはありません。このような方法で値を変更すると、未定義の動作が発生するというルールがあります。 –