std::find在使用strdup时不起作用
std::find does not work when using strdup
我使用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*
的转换不推荐使用。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- std::find在使用strdup时不起作用