std::find在使用strdup时不起作用

std::find does not work when using strdup

本文关键字:strdup 不起作用 find std      更新时间:2023-10-16

我使用std::vector来存储一些字符串,后来我尝试std::find它们,但通过strdup,如示例代码所示,它不起作用,std::find返回最后一个,这意味着它没有找到字符串,但我可以看到它在那里,因为我通过std::vector::at函数访问它,它显示正确。问题出在哪里?

#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <stdint.h>
#include <string.h>
int main()
{
    std::vector<char*> signal_list;
    std::vector<char*>::iterator it;
    char *temp;
    char *temp2;
    signal_list.push_back("DDF_LTEsyn__CALLER");
    signal_list.push_back("DDF_LTEsyn__FFT_ctrl");
    signal_list.push_back("DDF_LTEsyn__IFFT_ctrl");
    signal_list.push_back("DDF_LTEsyn__ae_ctrl");
    signal_list.push_back("DDF_LTEsyn__cwp_ctrl");
    signal_list.push_back("DDF_LTEsyn__decision_ctrl");
    signal_list.push_back("DDF_LTEsyn__ovelap_ctrl");
    signal_list.push_back("DDF_LTEsyn__pilots_ctrl");
    signal_list.push_back("DDF_LTEsyn__pre_ctrl");
    signal_list.push_back("DDF_LTEsyn__rep_ctrl");
    temp2 = strdup(signal_list.at(3));
    printf("There is %s at position %dn",temp2, 3);
    it = find(signal_list.begin(), signal_list.end(), temp2);
    printf("i found %s at position %d ",temp2, it - signal_list.begin());
}

您比较的是指针地址,而不是字符串。您应该使用std::vector<std::string>std::find_if(),并向其传递一个可以比较字符指针的谓词。

以下是你可以做的第二个:

bool compare(const char *str1, const char *str2)
{
    return strcmp(str1, str2) == 0;
}
it = std::find_if(signal_list.begin(), signal_list.end(), std::bind2nd(std::ptr_fun(compare), tmp2));

这是因为find正在比较指针。

默认操作是比较指针值(而不是字符串值)。

两个选项:
A:更改

temp2 = strdup(signal_list.at(3));
// Change this to:
temp2 = signal_list.at(3);

现在它将在两个指针上找到匹配。

B:切换到使用std::string而不是char*

std::vector<char*>   signal_list;
char*                temp2;
// Change to:
std::vector<std::string>  signal_list;
std::string               temp2;

现在,它将使用字符串比较,并按照您的期望进行操作。

注意:字符串文字的类型为char const*,而不是char*。因此,将它们存储在这样的CCD_ 10中是非常危险的。任何修改它们的尝试都可能导致应用程序崩溃。至少使用vector<char const*>。如果您正在查看警告,编译器会警告您从char const*char*的转换不推荐使用。