簡體   English   中英

如何按降序對字符串向量進行排序?

[英]How do I sort a vector of strings in descending order?

我有以下代碼,其中有一個字符串向量。 每個字符串都是一個 integer。我想按降序對其進行排序。 常規排序 function 並沒有解決我的問題。 有人可以指出如何做到這一點嗎? 我想要 output 作為 345366,38239,029323。 我也想要 029323 中的前導零。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;


int main() {
    vector<string> v = {"345366", "029323", "38239"};
    vector<int> temp(v.size());
    for (int idx = 0; idx < v.size(); idx++)
        temp[idx] = stoi(v[idx]);
    sort(temp.begin(), temp.end()));
    cout<<temp[0]<<" "<<temp[1]<<" "<<temp[2];

    return 0;
}

您可以像這樣使用比較器 function:

vector<string> v = {"345366", "029323", "38239"};
std::sort(v.begin(), v.end(), [](const std::string &s1, const std::string &s2) -> bool {
    return std::stoi(s1) > std::stoi(s2); 
});
for(auto i : v)
    cout << i << endl;

檢查此 std::stoi() 參考

編輯:從評論來看,似乎std::stoi()std::atoi()好得多。 要轉換 C++ 字符串,請使用std::stoi() 對於 C 字符串,如果字符串不可轉換為 int, std::atoi()將靜默失敗而不會產生任何錯誤,而std::stoi()將產生異常,因此也是一個更安全的選擇。

cout << std::atoi("abc") << endl; // runs smoothly
cout << std::stoi("abc") << endl; // creates an 'uncaught exception of type std::invalid_argument: stoi'

但是,在這種情況下結果將是相同的(將提取前綴 integer 部分並退出,如果是std::stoi() ,如果字符串不以整數開頭,它將創建一個異常):

cout << std::atoi("999abc12") << endl; // prints 999
cout << std::stoi("999abc12") << endl; // prints 999
cout << std::stoi("abcdef12") << endl; // generates exception

另請參閱此答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM