【问题标题】:Is there a good way to search by both key and value?有没有按键和值搜索的好方法?
【发布时间】:2010-10-03 03:41:51
【问题描述】:

我目前在 C++ 中使用map<int, int>。我可以毫无问题地检查键的存在,但是是否有一种有效的方法来检索特定值也具有的键?我的目的是获取具有给定值的所有元素,然后更新它们的值。

【问题讨论】:

  • 很有可能有更好的数据结构来解决您的问题。你能描述一下你一般在做什么吗?
  • 实际上,我在这里玩弄这个问题:stackoverflow.com/questions/3848239/trying-to-group-values 我想出了一个解决方案,并正在看看我是否可以在 C++ 中实现它。我还没有验证我自己的解决方案版本,但我想知道如果效率是一个问题,这个问题实际上是如何解决的。

标签: c++ stl


【解决方案1】:

您可能对Boost.Bimap 感兴趣。

【讨论】:

  • 谢谢。现在会调查并回来。
  • 这绝对是非常有用的+1
【解决方案2】:

现在使用 c++11 及更高版本很容易。

试试下面的示例。

//DECLARE A MAP
std::map<int, int> testmap;

//SAMPLE DATA
testmap.insert(std::make_pair(1, 10));
testmap.insert(std::make_pair(2, 20));
testmap.insert(std::make_pair(3, 30));
testmap.insert(std::make_pair(4, 20));

//ELEMENTS WITH VALUE TO BE FOUND
int value = 20;

//RESULTS
std::map<int,int> keysMatching;

//ONE STEP TO FIND ALL MATCHING MAP ELEMENTS
std::copy_if(testmap.begin(), testmap.end(), std::inserter(keysMatching, keysMatching.end()), [value](const auto& v) {return v.second == value; });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2019-10-09
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多