Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Generally speaking, C++ doesn't sort strings like that, since they're non-PODs. In fact, in this case, qsort swaps the internals of std::string, which cannot be done directly (UB).
Sorting non-POD types is done with std::sort.
Anyway, std::sort is a template function; it is better to inline than qsort, and therefore it is better to use it in C++ code.
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
int str_compare(std::string const & l, std::string const & r)
{
if (l == r)
return 0;
return l < r ? -1 : 1;
}
int str_compare(void const * l, void const * r) { return str_compare(*static_cast<std::string const *>(l), *static_cast<std::string const *>(r)); }
int main()
{
std::string strs[3] = { "foo", "bar", "baz" };
std::qsort(strs, 3, sizeof(std::string), str_compare); // В общем, работает, но UB
// std::sort(&strs[0], &strs[0] + 3); // вот так - лучше
for (auto & s : strs)
std::cout << s << std::endl;
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question