I'm sorry if this has already been asked somewhere, but I haven't been able to find an answer to what I'm looking for.
I have a vector of std::string pointers, that I want to sort in alphabetical order, and I haven't been able to figure out how to do this. I am using std::sort.
I wrote up a quick program to test out what I was trying to do (since in the actual implementation, my code is being run in a child process, so it's kind of hard to debug):
#include <string>
#include <algorithm>
#include <vector>
#include <string.h>
bool cmpStrPtrs(std::string *a, std::string *b) {
std::string a1 = *a;
std::string a2 = *b;
if(a1 == a2) return 0;
return a1 > a2 ? 1 : -1;
}
int main(int argc, char *argv[]) {
std::vector<std::string *> vec;
std::string *str1 = new std::string("AAAAA");
std::string *str2 = new std::string("aaaaa");
std::string *str3 = new std::string("xxxxx");
std::string *str4 = new std::string("bfuen");
std::string *str5 = new std::string("xylophone");
vec.push_back(str1);
vec.push_back(str2);
vec.push_back(str3);
vec.push_back(str4);
vec.push_back(str5);
std::sort(vec.begin(), vec.end(), cmpStrPtrs);
for(std::string *str : vec) {
printf("%s\n", str->c_str());
}
return 0;
}
When I run this, I get this output:
$ ./strsort
xylophone
bfuen
xxxxx
aaaaa
AAAAA
This doesn't seem to be in any sort of alphabetical order at all, so I can assume that I'm either using sort() wrong or there's something wrong with my comparator function. I also tried it without a comparator function and I think that's just ordering them based on their memory locations from least to greatest, which doesn't actually change anything. I also tried using
bool cmpStrPtrs(std::string *a, std::string *b) {
return a->compare(*b);
}
but it gave me the same result.
If it's relevant, I'm compiling with g++ using the c++17 standard.
newis non-idiomatic C++. Your comparison function is wrong too (let's start with "you're returning anintfrom a function that was supposed to returnbool") Also see en.cppreference.com/w/cpp/concept/Compareboolvector<string*>and not justvector<string>? I don't see what value the extra indirection adds.