c++ - 在 vector 对中查找元素并输出C++

标签 c++ vector

我有一对 vector :

typedef pair<string,int> is;
vector<is> v;
我将一些值推到 vector 上。
v.push_back(make_pair("One",1));
v.push_back(make_pair("Two",2));
v.push_back(make_pair("Three",3));
v.push_back(make_pair("Four",4));
我需要让用户输入一个名称并搜索 vector ,找到该名称并将其输出成对的对应int。如果用户键入“One”,我希望输入键入1。
我尝试了以下方法。
struct comp_pair_int
{
    bool operator()(const pair<string, int>& a, const string& b)
    {
        return (a.first < b);
    }
    bool operator()(const string& a, const pair<string, int>& b)
    {
        return (a < b.first);
    }
};
sort(v.begin(),v.end(),comparison);
if (binary_search(v.begin(), v.end(),
    "One", comp_pair_int()))
    cout << "Element found\n";
else
    cout << "Element not found";
该代码返回是否找到该元素,但这不是我想要的全部,我还需要在找到的元素对中输出第二个元素。我怎样才能做到这一点?

最佳答案

std::binary_search 仅会为您提供bool结果,因此它没有提供足够的信息来获取您要查找的对的值。
惯用的方法是使用 std::lower_bound ,它会向您要查找的对返回一个迭代器,如下所示:

if (auto i = std::lower_bound(v.begin(), v.end(),
                              "One", comp_pair_int());
    i != v.end() && i->first == "One")   // lower bound actually found correct pair
       cout << "Element found with value " << i->second;
else
       cout << "Element not found";
请注意,与binary_search一样,范围需要按用于搜索的相同谓词进行排序。

关于c++ - 在 vector 对中查找元素并输出C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62958060/

相关文章:

c++ - C/C++ - 模拟长时间运行的操作

c++ - Pythran “undefined reference to ` ATL_caxpby'”错误

c++ - 命名空间标准重载小于

c++ - CUDA 凸包程序在大输入时崩溃

c++ - 从对象 vector 调用虚拟函数的模板版本

c++ - 在 C++ 中从 T 转换为 const T 的函数

c++ - 获取 gsl_vector_view 的大小

C++:传递从 vector 获取的数组指针时的EXC_BAD_ACCESS

C++ - 纯虚函数的参数

math - 关于假设函数中向量转置的查询(斯坦福机器学习视频讲座 2)