在我的程式中,我有一個通過用戶輸入填充的空字串向量。該程式旨在從用戶輸入中獲取數字,然后按從小到大的順序對這些數字進行排序(資料型別是字串,以便更容易檢查不需要的輸入,例如空格、字母、標點符號等)。實際上,程式根據起始數字而不是大小對數字進行排序。如何更改程式以按我想要的方式排序?
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
#include <string>
#include <sstream>
using namespace std;
int main()
{
vector<string> vect;
string input;
int intInput;
int entries = 0;
int i = 0;
int x = 0;
while (x < 1)
{
i ;
cout << "Please input an integer. When finished providing numbers to organize,
input any character that isn't an integer:\n";
vect.resize(i 1);
getline(cin, input);
cout << endl;
stringstream ss(input);
if (ss >> intInput)
{
if (ss.eof())
{
vect.push_back(input);
entries ;
}
else
{
cout << "Error: Invalid input.\n\n";
}
}
else if (entries < 1)
{
cout << "Error: Invalid input.\n\n";
i = -1;
continue;
}
else if (entries >= 1)
{
break;
}
}
cout << "All done? Organizing numbers!\n";
sort(vect.begin(), vect.end());
for (int j = 0; j < vect.size(); j )
{
cout << vect[j] << endl;
}
return 0;
}
我嘗試了各種方法將字串資料轉換為int資料,比如lexical cast & stoi(),但是都沒有成功,所以我想知道是否有另一種方法,比如在不改變資料的情況下對資料進行排序型別。
uj5u.com熱心網友回復:
您可以指定一個比較函式,該函式回傳第一個引數是否“小于”該std::sort函式的第二個引數。
在測驗時,我發現一些空字串,使std::stoithrowstd::invalid_argument被推入向量中(它看起來像 by vect.resize(i 1);)。因此,我添加了一些代碼來檢測錯誤并將無效字串評估為小于任何有效整數。
sort(vect.begin(), vect.end(), [](const string& a, const string& b) {
bool aError = false, bError = false;
int aInt = 0, bInt = 0;
try {
aInt = stoi(a);
} catch (invalid_argument&) {
aError = true;
}
try {
bInt = stoi(b);
} catch (invalid_argument&) {
bError = true;
}
if (aError && !bError) return true;
if (bError) return false;
return aInt < bInt;
});
#include <stdexcept>
應添加使用std::invalid_argument。
參考:
- std::sort - cppreference.com
- std::stoi、std::stol、std::stoll - cppreference.com
- std::invalid_argument - cppreference.com
uj5u.com熱心網友回復:
vect 開頭有兩個不能轉換為字串的字符。這是您的相同代碼,只是添加了 2。
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
#include <string>
#include <sstream>
using namespace std;
int main()
{
vector<string> vect;
string input;
int intInput;
int entries = 0;
int i = 0;
int x = 0;
while (x < 1)
{
i ;
cout << "Please input an integer. When finished providing numbers to organize, input any character that isn't an integer:\n";
vect.resize(i 1);
getline(cin, input);
cout << endl;
stringstream ss(input);
if (ss >> intInput)
{
if (ss.eof())
{
vect.push_back(input);
entries ;
}
else
{
cout << "Error: Invalid input.\n\n";
}
}
else if (entries < 1)
{
cout << "Error: Invalid input.\n\n";
i = -1;
continue;
}
else if (entries >= 1)
{
break;
}
}
cout << "All done? Organizing numbers!\n";
sort(vect.begin() 2, vect.end()); //added 2 here
for (int j = 2; j < vect.size(); j ) //iterating from 2
{
cout << vect[j] << endl;
}
return 0;
}
它適用于我的 linux,希望它也適用于你的
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454234.html
上一篇:C std::any函式將std::any的C字符陣列轉換為字串
下一篇:在串列中列印單個字母
