假设我有一个高分表,结构如下
name score
name score
....
Run Code Online (Sandbox Code Playgroud)
我需要做一些文件操作和操作文件的某些方面,我认为这样做将其存储在保存文件的顺序的容器最好的办法,进行数据处理与容器,然后输出回到档案.
我考虑使用a map< std::string, int >,但是地图不会保留文件的顺序.会vector< pair< std::string, int >>更好,还是有一些我可以使用的有序地图?如有必要,我还需要容器重复一个名字.我认为,多重映射保持一个键,但允许多个值是关键,这是不是我想要的,因为它不会维持秩序.
使用
std::vector< std::pair< std::string, int > >
Run Code Online (Sandbox Code Playgroud)
解.
或者甚至更好,做一个HighScoreEntry类,并有一个std :: vector <HighScoreEntry> - 然后你就可以在以后添加额外的数据,并在课程中嵌入得分处理代码.
要添加条目,请将条目推送到向量的末尾,然后对其运行std::sort,只需记住为HighScoreEntry编写比较运算符.
class HighScoreEntry
{
public:
std::string name;
uint32 score;
bool operator<(const HighScoreEntry& other) const
{
// code that determines ordering goes here
return score < other.score
}
};
Run Code Online (Sandbox Code Playgroud)
高分表:
std::vector< HighScoreEntry > highscores;
Run Code Online (Sandbox Code Playgroud)
排序:
std::sort( highscores.begin(), highscores.end() );
Run Code Online (Sandbox Code Playgroud)
要保留具有相同分数的高分的排序顺序,请使用时间戳,并将其添加到比较器中.