[英]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.