为什么strcmp在find_if中调用时返回0 ?c++



我有一个元素向量。这些元素都是包含路径的结构体,我想找到一个具有特定路径的元素。

我尝试使用std::find_if,如下面的UseFindIf所示方法,但是调用strcmp无论const char ptrs是否总是返回0。是否相同

然后,我尝试使用for循环遍历容器的迭代器,如UseForLoop所示方法,并按预期工作。

有谁知道为什么strcmp中调用find_if时的行为如下所示

?在下面的代码中调用UseFindIf发现打印和调用UseForLoop打印NotFound

int(结构体的成员是不相关的)

#include <iostream>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
struct MyStruct
{
string path;
int aNumber = 9;
};
void UseFindIf(const vector<MyStruct>& container,  const char* _path)
{
auto itFoundTexture = std::find_if( container.begin(), container.begin(), [&]( const MyStruct& _td ) 
{
return strcmp( _td.path.c_str(), _path ) == 0;
});

cout << (itFoundTexture == container.end() ? "Not Found" : "Found") << endl;
}
void UseForLoop(const vector<MyStruct>& container,  const char* _path)
{
auto itFoundTexture = container.begin();
for (; itFoundTexture != container.end(); ++itFoundTexture)
{
if (strcmp( itFoundTexture->path.c_str(), _path ) == 0) break;
}

cout << (itFoundTexture == container.end() ? "Not Found" : "Found") << endl;
}

int main()
{
vector<MyStruct> container;
MyStruct data;
data.path = "../assets/test.jpg";
data.aNumber = 888;
container.push_back(data);

UseFindIf(container, "../assets/othertest.jpg");
UseForLoop(container, "../assets/othertest.jpg");
return 0;
}

我也试着写lambda,所以它比较字符串而不是char指针,但结果相同。

void UseFindIf(vector<MyStruct>& container,  const char* _path)
{
string strTest(_path);
auto itFoundTexture = std::find_if( container.begin(), container.begin(), [&]( const MyStruct& _td ) 
{
return _td.path == strTest;
});

cout << (itFoundTexture == container.end() ? "Not Found" : "Found") << endl;
}

我也可以说这个问题与lambda无关,我在find_if之外运行了相同的lambda它的行为与预期一致。

如果它有帮助,我使用c++ 20在我的项目在VS。我也尝试使用https://www.onlinegdb.com/online_c++_compiler和相同的结果。

提前感谢!

您在UseFindIf()中有一个错别字。你指定的迭代器范围是[begin..begin)而不是[begin..end),所以你的lambda永远不会看到vector的任何元素,而itFoundTexture将始终被设置为begin迭代器,这就是为什么你总是看到Found而不管实际的搜索结果(当向量不是空的时候)。

你需要改变这个:

std::find_if( container.begin(), container.begin(), ...);
^

改为:

std::find_if( container.begin(), container.end(), ...);
^

最新更新