文字列のベクトルがある次のコードがあります。各文字列は整数です。これを降順で並べ替えたいと思います。通常のソート機能では問題は解決しませんでした。誰かがこれを行う方法を指摘できますか?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;
}
次のようなコンパレータ機能を使用できます。
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文字列のstd::atoi()
場合、文字列がintに変換できない場合、エラーを生成せずにサイレントに失敗しますがstd::stoi()
、例外を生成するため、より安全な選択でもあります。
cout << std::atoi("abc") << endl; // runs smoothly
cout << std::stoi("abc") << endl; // creates an 'uncaught exception of type std::invalid_argument: stoi'
ただし、この場合、結果は同じになります(接頭辞の整数部分を抽出して終了std::stoi()
します。の場合、文字列が整数で始まらないと、例外が作成されます)。
cout << std::atoi("999abc12") << endl; // prints 999
cout << std::stoi("999abc12") << endl; // prints 999
cout << std::stoi("abcdef12") << endl; // generates exception
この回答も参照してください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加