考虑以下数据结构和代码。
struct Sentence {
std::string words;
int frequency;
Sentence(std::string words, int frequency) : words(words), frequency(frequency) {}
};
struct SentencePCompare {
bool operator() (const Sentence* lhs, const Sentence* rhs) const {
if (lhs->frequency != rhs->frequency) {
return lhs->frequency > rhs->frequency;
}
return lhs->words.compare(rhs->words) < 0;
}
};
std::set<Sentence*, SentencePCompare> sentencesByFrequency;
int main(){
Sentence* foo = new Sentence("foo", 1);
Sentence* bar = new Sentence("bar", 2);
sentencesByFrequency.insert(foo);
sentencesByFrequency.insert(bar);
for (Sentence* sp : sentencesByFrequency) {
std::cout << sp->words << std::endl;
}
foo->frequency = 5;
for (Sentence* sp : sentencesByFrequency) {
std::cout << sp->words << std::endl;
}
}
以上代码的输出结果如下。bar
foo
bar
foo
正如我们所预期的那样,当集合中指向指针的对象被更新时,即使谓词根据它们所指向的对象对指针进行排序,集合也不会自动重新评估谓词。
有没有一种方法可以强制 std::set
重新评估谓词,以便顺序再次正确?
std::set
并不是适合你使用情况的容器类型?因为键(keys)应该是常量,所以没有必要进行重新排序。 - Some programmer dudevector
表示可能是有意义的,然后在每次使用之前立即对其进行排序。 - Alex Celeste