我有一对 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/