gpt4 book ai didi

c++ - 在 C++ 98 中的对 vector 中按键查找对

转载 作者:行者123 更新时间:2023-11-27 22:53:40 24 4
gpt4 key购买 nike

我正在使用以下版本,将无法使用 C++11g++ (SUSE Linux) 4.3.4 [gcc-4_3-branch 修订版 152973]。

我有一个 vector 对。

  std::vector<std::pair<int, std::string> > vec;
vec.push_back(std::make_pair(5, std::string("tata")));
vec.push_back(std::make_pair(6, std::string("tat2")));
vec.push_back(std::make_pair(7, std::string("tat3")));
vec.push_back(std::make_pair(8, std::string("tat4")));

现在我可以使用迭代器使用键对来搜索 vector 中的所有元素,例如

    std::vector<std::pair<int, std::string> >:: iterator it ;
for (it = vec.begin(); it != vec.end(); ++it)
{
if (it->first == item)
{
cout << "Found " << item << "\n";
return 0;
}
}

我希望有任何可能的方法在 C++98 中使用 std::find 操作,因为我搜索了相关的帖子,其中大部分都解决了 C++ 11 中支持的问题。

最佳答案

C++11 只是让代码更简洁。在 C++11 中,我们可以这样写:

std::find_if(vec.begin(), vec.end(), [&](std::pair<int, std::string> const & ref) {
return ref.first == item;
});

现在,在 C++98 中,lambda 将变得更加冗长:

class SearchFunction {
public:
SearchFunction(int item): item_(item) {}
bool operator()(std::pair<int, std::string> const & ref) {
return ref.first == item_;
}
private:
int item_;
};

std::find_if(vec.begin(), vec.end(), SearchFunction(item));

SearchFunction 这样的类通常被称为 Functors .

关于c++ - 在 C++ 98 中的对 vector 中按键查找对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com