這裏有你想要做什麼的STL版本:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <algorithm>
int main() {
std::vector<std::string> names;
int num = 0;
std::cout << "Please enter a number: ";
std::cin >> num;
std::cout << "\n";
std::string name;
for (int i = 0; i < num; ++i) {
std::cout << "Please enter name(" << (i+1) << "): ";
std::cin >> name;
names.push_back(name);
}
//sort the vector:
std::sort(names.begin(), names.end());
std::cout << "The sorted names are: \n";
for (int i=0; i<num; ++i) {
std::cout << names[i] << "\n";
}
return 0;
}
但是,此版本是區分大小寫的排序,所以無論是否執行你的要求可能會有問題。所以,一個可能的下一步更貼近不區分大小寫的排序是使用這段代碼矢量進行排序前:
//transform the vector of strings into lowercase for case-insensitive comparison
for (std::vector<std::string>::iterator it=names.begin(); it != names.end(); ++it) {
name = *it;
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
*it = name;
}
用這種方法唯一需要注意的是,所有的字符串將被轉換成小寫,但是。
參考:
https://stackoverflow.com/a/688068/866930
How to convert std::string to lower case?
嘗試'strings'的陣列來存儲名字的價值。然後最後(循環外)調用一個排序例程。 –
這裏可以使用qsort嗎? – Supremo
請參閱我在獲取數據時不會進行排序,因爲如果您嘗試這樣做,複雜度將爲'O(n^2)'。而是獲取所有必需的字符串,然後調用自定義的qsort。請注意,您可能必須編寫並將比較器函數重載,以便比較字符串以包含不等長度的情況。我希望你明白這一點。 –