题解 | #输入整型数组和排序标识
输入整型数组和排序标识,对其元素按照升序或降序进行排序
https://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
#include <iostream> #include <vector> #include <algorithm> #include <sstream> using namespace std; int main() { string strInputNum, strInputArr, strInputSortPara; getline(cin, strInputNum); getline(cin, strInputArr); getline(cin, strInputSortPara); int nInputNum = stoi(strInputNum); vector<int> vecTokens; char chSigned = ' '; istringstream stringstream(strInputArr); string strTokens; while (getline(stringstream, strTokens, chSigned)) { vecTokens.push_back(stoi(strTokens)); } int nInputSortPara = stoi(strInputSortPara); sort(vecTokens.begin(), vecTokens.end()); if (nInputSortPara == 1) { reverse(vecTokens.begin(), vecTokens.end()); } string strOutput = ""; for (size_t i = 0; i < vecTokens.size(); i++) { if (i != vecTokens.size() - 1) { strOutput = strOutput + to_string(vecTokens[i]) + " "; } else { strOutput = strOutput + to_string(vecTokens[i]); } } cout<<strOutput<<endl; }