gpt4 book ai didi

c++ - 字符串指针的排序 vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:07 26 4
gpt4 key购买 nike

如果有人问过这个问题,我很抱歉,但我找不到我正在寻找的答案。

我有一个 std::string 指针 vector ,我想按字母顺序排序,但我一直无法弄清楚如何做到这一点。我正在使用 std::sort。

我写了一个quick program测试我正在尝试做什么(因为在实际实现中,我的代码正在子进程中运行,所以很难调试):

#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;
}

当我运行它时,我得到了这个输出:

$ ./strsort
xylophone
bfuen
xxxxx
aaaaa
AAAAA

这似乎根本不是按字母顺序排列的,所以我可以假设我使用的 sort() 有误,或者我的比较函数有问题。我也在没有比较器功能的情况下尝试过它,我认为这只是根据它们的内存位置从最小到最大对它们进行排序,这实际上并没有改变任何东西。我也试过使用

bool cmpStrPtrs(std::string *a, std::string *b) {
return a->compare(*b);
}

但它给了我相同的结果。

如果相关,我将使用 c++17 标准使用 g++ 进行编译。

最佳答案

std::string::compare返回 int , 不是 bool .根据cppreference.com返回值为

negative value if *this appears before the character sequence specified by the arguments, in lexicographical order

zero if both character sequences compare equivalent

positive value if *this appears after the character sequence specified by the arguments, in lexicographical order strong text

返回值转换为bool计算结果为 true对于所有非零值。这意味着您的函数返回 true对于每对不相同的字符串。

C++标准实际上定义了operator<对于字符串,因此您可以将函数更改为

bool cmpStrPtrs(std::string *a, std::string *b) {
return *a < *b;
}

但这仍然会在您的代码中留下一个大问题。你绝对不需要这个指针。事实上,您现在正在泄漏内存,因为您忽略了 delete他们。适合这项工作的工具是 std::vector<std::string> .这有一个额外的好处,即没有额外的间接级别,std::sort可以隐式调用 operator<没有辅助函数,导致以下解决方案。

std::vector<std::string> vec;
vec.emplace_back("AAAAA");
vec.emplace_back("aaaaa");
vec.emplace_back("xxxxx");
vec.emplace_back("bfuen");
vec.emplace_back("xylophone");

std::sort(vec.begin(), vec.end());

关于c++ - 字符串指针的排序 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49142024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com