我将编写一个代码来比较数组中的一些对象并按名称对它们进行排序。
首先如何在 C++ 中比较字符串?在java中很容易 oneString.compareTo(another);
如果您在 C++ 中拥有合并排序,请分享。谢谢你!
在 C++ 中比较字符串与在 Java 中非常相似——调用方法compare
而不是compareTo
. 所以使用oneString.compare(another);
.
您可以将std::string
成员函数operator<()
用作std::sort
(使用 C++11 lambda 表达式)的比较函数。这可能会或可能不会使用归并排序作为实现,但它具有相同的O(N log N)
复杂性。
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> v = { "foo", "bar" };
std::sort(v.begin(), v.end());
std::for_each(v.begin(), v.end(), [](std::string const& elem) {
std::cout << elem << "\n";
});
return 0;
}