如何在向量结构中搜索项目?

时间:2020-09-20 21:50:13

标签: c++ vector

我正在尝试创建一个函数,该函数将在使用矢量的结构中找到一个项目,但我不断收到错误消息:

“ operator ==”不匹配(操作数类型为“ video_games”和“ const std :: basic_string”)

void DataStoreVectors::findItem(vector<video_games> &Video_Games) {

    video_games videoGames;
    
    cout << "Type a Video Game to Find: ";
    cin >> videoGames.game_name;

    vector<video_games>::iterator it;
    it = find(Video_Games.begin(), Video_Games.end(), videoGames.game_name);
    if(it != Video_Games.end())
        cout << "Found: " << videoGames.game_name << endl;
    else
        cout << "Not Found." << endl;

}

我在做什么错,这个错误是什么意思?

3 个答案:

答案 0 :(得分:0)

查找 的参数中用 videoGames 替换 videoGames.game_name 。它将编译。如果您的结构video_games具有操作符==,则该方法将起作用。如果game_name属性相等,则该操作符将返回true。

答案 1 :(得分:0)

扩大我的评论:

std::find需要知道何时找到匹配项。如果您提供的是某个对象,它将尝试使用==将该对象与集合中的每个项目进行比较。

视频游戏不是字符串,比较它们没有任何意义。因此,如某些评论所建议的,重载operator ==并不是一个好的设计。

考虑以下替代方法:

auto it = std::find(
    Video_Games.begin(), Video_Games.end(),
    [&](const auto & game) { return game.game_name == videoGames.game_name; }
);
if(it != Video_Games.end())
    std::cout << "Found: " <<it->game_name <<std::endl;
else
    std::cout << "Not Found." <<std::endl;

我们通过为该搜索提供std::find(而不是让其使用true的函数)来告诉==该特定搜索应考虑匹配的内容。

答案 2 :(得分:0)

您无需将视频游戏的名称存储在video_games对象中,只需将其存储在字符串video_game_name中即可。

然后,从c ++ 20开始,您可以像这样实现它:

auto it = std::ranges::find(Video_Games, video_game_name, 
                            &video_games::game_name);