我创建了一个小的高分系统,它可以保存到文件,然后根据要求读取/加载。
但是,我正在加载一个字符串 vector ,因此创建了一个字符串生成器来添加它们并按顺序显示。
但是,我意识到这是一种糟糕的做法,我不确定如何获得我想要的结果,即拥有一个可以按分数(降序)顺序排序的数据结构以及对应名称。
理论上我想做的是 <vector<int, string> theScore
.如果有人能指出正确的方向,我将不胜感激。
这是我所拥有的:
vector<string> HighScore::loadScore()
{
ifstream loadFile("scorefile.txt");
string name;
int score;
vector<string> theScore;
string builder;
if (loadFile.is_open())
{
while (!loadFile.eof())
{
loadFile >> name >> score;
builder = to_string(score) + "\t";
builder = builder + name;
//Add all entries to vector List
theScore.push_back(builder);
}
//Sort all entries in score to descending order (Reverse)
std::sort(theScore.rbegin(), theScore.rbegin() +theScore.size());
}
return theScore;
}
最佳答案
我不太清楚你想做什么,但我希望
你想定义一个包含必要的类
信息,以及 operator>>
和 operator<<
为了它。所以
你最终会得到类似的东西:
std::vector<Entry> data;
Entry entry;
while ( loadFile >> entry ) {
data.push_back( entry );
}
如果Entry
是这样的:
struct Entry
{
int score;
std::string name;
};
然后是你的operator>>
可能看起来像:
std::istream&
operator>>( std::istream& source, Entry& dest )
{
Entry results;
source >> results.score >> results.name;
if ( source ) {
dest = results;
}
return source;
}
(或者您可能想要读取一行并解析它,以便 名称中允许有空格。)
要排序,您可以定义简单的比较运算符:
struct ByScore
{
bool operator()( Entry const& lhs, Entry const& rhs ) const
{
return lhs.score < rhs.score;
}
};
并将一个实例传递给std::sort
:
std::sort( data.begin(), data.end(), ByScore() );
(我可能会补充说:while ( !loadFile.eof() )
不正确,因为
正在使用 >>
的结果没有首先验证他们
已经成功了。)
关于c++ - 如何返回一个int和一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15920599/