【问题标题】:std::set<pair<int,int> > -- find only using pair<>::first as the keystd::set<pair<int,int> > -- 仅使用 pair<>::first 作为键查找
【发布时间】:2015-01-17 22:56:46
【问题描述】:

所以我有一个包含int 对的红黑树,当我调用.find(x) 函数时,它将搜索x(第一个和第二个),但我想让它忽略第二个值,并且只查找第一个值。我该怎么做?

【问题讨论】:

  • 你已经有效地描述了std::map&lt;int,int&gt;

标签: c++ find set


【解决方案1】:

一般来说,这是不可能的。但是对于您有限的一对ints,您可以使用upper_bound()std::numeric_limits&lt;int&gt;::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";
}

Live on Coliru

【讨论】:

  • 别担心,我刚刚找到了一个好方法。
  • @VladPotra - 你没有分享那种好方法 - 多么粗鲁:)
  • 不可能?
【解决方案2】:
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&lt;pair&lt;int, int&gt;&gt; my_set;,它将打印not found

当然,只键入first 可以说是map&lt;int, int&gt;,那么为什么不这样做呢?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多