这是您尝试执行的 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
如何将 std::string 转换为小写?