【发布时间】:2015-01-17 22:56:46
【问题描述】:
所以我有一个包含int 对的红黑树,当我调用.find(x) 函数时,它将搜索x(第一个和第二个),但我想让它忽略第二个值,并且只查找第一个值。我该怎么做?
【问题讨论】:
-
你已经有效地描述了
std::map<int,int>
所以我有一个包含int 对的红黑树,当我调用.find(x) 函数时,它将搜索x(第一个和第二个),但我想让它忽略第二个值,并且只查找第一个值。我该怎么做?
【问题讨论】:
std::map<int,int>
一般来说,这是不可能的。但是对于您有限的一对ints,您可以使用upper_bound() 和std::numeric_limits<int>::min() 伪造它:
#include <iostream>
#include <iomanip>
#include <limits>
#include <set>
int main()
{
using key_type = std::pair<int, int>;
std::set<key_type> s { {1, -1}, {1, 3}, {2, 10}, {3, 42} };
auto it = s.upper_bound (key_type (2, std::numeric_limits<int>::min ()));
std::cout << "(" << it->first << "; " << it->second << ")\n";
}
【讨论】:
auto fn = [](const pair<int, int>&a, const pair <int, int>&b) {
return a.first < b.first;
};
set<pair<int, int>, decltype(fn)> my_set(fn);
my_set 现在是一个仅使用 pair.first 作为键的集合
例子:
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main()
{
auto fn = [](const pair<int, int>&a, const pair <int, int>&b) {
return a.first < b.first;
};
set<pair<int, int>, decltype(fn)> my_set(fn);
my_set.insert({1, 123});
my_set.insert({4, 456});
my_set.insert({7, 789});
auto iter = my_set.find({4, 0});
if (iter != my_set.end()) {
cout << "first: " << iter->first << ", second: " << iter->second << "\n";
} else {
cout << "not found\n";
}
return 0;
}
打印
first: 4, second: 456
将my_set 更改为set<pair<int, int>> my_set;,它将打印not found
当然,只键入first 可以说是map<int, int>,那么为什么不这样做呢?
【讨论】: