0

我正在使用astd::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 %d\n",temp2, 3);

    it = find(signal_list.begin(), signal_list.end(), temp2);

    printf("i found %s at position %d ",temp2, it - signal_list.begin());

}
4

2 回答 2

8

您正在比较指针地址,而不是字符串。您应该使用 a std::vector<std::string>orstd::find_if()并将其传递给可以比较 char 指针的谓词。

以下是你如何做第二个:

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));
于 2012-01-25T00:10:45.137 回答
3

那是因为 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*not char*。因此,将它们存放在这样的地方是非常危险的vector<char*>。任何修改它们的尝试都可能使您的应用程序崩溃。至少使用vector<char const*>. 如果您正在查看警告,编译器将警告您有关从char const*to的弃用转换char*

于 2012-01-25T00:21:27.023 回答