【问题标题】:sorted vector of pair (std::vector<pair<int, int>>) Search by first element of pair and update the second element value [closed]对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值 [关闭]
【发布时间】:2020-10-16 08:51:04
【问题描述】:

我有一个成对的向量 (std::vector>),按对中的第一个排序。我想通过搜索对的第一个值来更新对的第二个值。

vector<pair<int,int>> v = { {1, 5}, {4, 26}, {5, 3}, {7, 13}, {12, 43}, {17, 31} };

我想将该对的第二个值更新为 27,它的第一个值为 12。

// Expected v
v = { {1, 5}, {4, 26}, {5, 3}, {7, 13}, {12, 27}, {17, 31} }

请记住,向量已经按 pair 的第一个元素排序。

【问题讨论】:

  • 请发布您尝试过的内容。
  • 使用 boost::flat_map。
  • 进行二分查找,然后更新找到的元素,
  • ... 并且编译时不要混合 c++ 版本。它可能会让人感到困惑。选择一个...
  • 看起来不错的计划。去吧,当你有问题时告诉我们?

标签: c++ algorithm c++14 c++17


【解决方案1】:

您可以使用std::lower_bound 对已排序的向量执行二进制搜索。结果是大于或等于参数的第一个元素的迭代器。您必须手动比较结果以获得完全匹配。

auto it = std::lower_bound(v.begin(), v.end(), std::make_pair(12, 0));
if (it != v.end() && it->first == 12) {
  it->second = 27;
}

【讨论】:

    【解决方案2】:

    使用 std::map

    std::map<int, int> mymap;
    mymap = { {1, 5}, {4, 26}, {5, 3}, {7, 13}, {12, 27}, {17, 31} };
    int newValue = 5;
    mymap.at(12) = newValue; //update the value 27 here
    std::cout << mymap.at(12) << std::endl; 
    

    请注意,如果地图中缺少请求的元素,at 函数将抛出 out of range exception。 此外,与您的矢量一样,此地图已排序。

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2019-11-06
      相关资源
      最近更新 更多