[英]C++ std::sort function gets not finished?
我目前正在为游戏设置高分部分,由于std :: sort函数的行为异常,我遇到了一个非常奇怪的问题。
我在C ++中的RAD Studio 10.2(Embarcadero IDE)中完成所有操作。
所以他是我的代码:
std::string Line;
int count = 0;
int i = 0;
ifstream File("Highscore.txt");
if(File.is_open())
{
while(getline(File, Line))
{
count += 1;
}
File.close();
}
ifstream ReadFile("Highscore.txt");
if(ReadFile.is_open())
{
string *scores = NULL;
scores = new string[count];
while(getline(ReadFile, Line))
{
scores[i] = Line;
i += 1;
}
ReadFile.close();
std::sort(scores, (scores+count));
UnicodeString Uscores1 = scores[0].c_str();
UnicodeString Uscores2 = scores[1].c_str();
UnicodeString Uscores3 = scores[2].c_str();
UnicodeString Uscores4 = scores[3].c_str();
UnicodeString Uscores5 = scores[4].c_str();
LScore1->Caption = Uscores1;
LScore2->Caption = Uscores2;
LScore3->Caption = Uscores3;
LScore4->Caption = Uscores4;
LScore5->Caption = Uscores5;
}
我没有从编译器/链接器得到任何错误,并且一切正常。 字符串数组正确填充,依此类推。
但是它没有排序。
为了向您显示问题,我制作了一个屏幕截图-在左侧,您可以看到带有分数的txt文件; 在右侧,您可以在排序算法后看到输出:
我现在的问题是为什么会这样?
谢谢你的帮助
欢迎使用C ++。 由于您要按等级列出数字,因此将它们读为int
而不是string
。 忘了new
操作员。 多年以来,您将不需要它。 使用标准容器,例如std::vector
,可以透明地处理内存分配和取消分配。
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
int main() {
using namespace std;
vector<int> scores;
{
ifstream inp("Highscore.txt");
int next;
while (inp >> next) {
scores.push_back(next);
}
}
sort(scores.begin(), scores.end());
for (auto s : scores) {
cout << s << '\n';
}
return 0;
}
怎么样:
int i = 0;
int * scoresInteger = NULL;
scoresInteger = new int[count];
for(i = 0; i < count; i++)
{
scoresInteger[i] = std::stoi(scores[i]);
}
std::sort(scoresInteger, scoresInteger + count);
如果需要,可以使用targetStrings[i] = std::to_string(scoresInteger[i])
将整数转换回字符串。
string * targetScores = NULL;
targetScores = new std::string[count];
for(i = 0; i < count; i++)
{
targetScores[i] = std::to_string(scoresInteger[i]);
}
delete [] scoresInteger;
scoresInteger = NULL;
不要忘记稍后delete [] targetScores
。
我现在的问题是为什么会这样?
因为您的得分被比较为string
而不是int
。 因为“ 3”大于“ 25”
std::cout << std::boolalpha << (std::string("3") > std::string("25")) << std::endl; // true
幸运的是,您可以将自定义比较器(或lambda)传递给std::sort
,使其表现出所需的效果:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
const int count = 5;
std::string scores[count] = { "35","25","3","4","5" };
// TWEAKED SORT
std::sort(scores, scores + count, [](std::string const &s1, std::string const &s2)
{
return std::stoi(s2) < std::stoi(s1);
});
// TEST
for (auto const &s : scores)
{
std::cout << s << std::endl;
}
}
上面示例中的比较string
s被转换为int
,然后进行比较,从而得出所需的排序顺序 。
35
25
5
4
3
请注意,我不同意您的其余代码,我认为您应该重新考虑实现,因为将std::vector<std::string>
用于您的任务会更加容易,安全和高效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.