用于关联容器的 C++ 入门 5ed equal_range

Posted

技术标签:

【中文标题】用于关联容器的 C++ 入门 5ed equal_range【英文标题】:C++ primer 5ed equal_range for associative containers 【发布时间】:2019-10-07 00:19:00 【问题描述】:

在 C++ prime 5 Ed 第 11 章。关联容器。 “表 11.7. 在关联容器中查找元素的操作”:

据说:“c.equal_range(k)返回一对迭代器,表示键为k的元素。如果k不存在,则两个成员都是c.end()。”

set<int> si 5, 7, 23, 16, 81, 24, 10;
auto it = si.equal_range(13);
cout << *it.first << " " << *it.second << endl; // 16 16
但正如您在上面看到的那样,13 没有找到,但它返回元素的迭代器 pair16, 16?!

【问题讨论】:

另见***.com/a/12159150/596781。请注意,equal_range 如果未找到键,则不会返回结束迭代器,而是返回一个 lower_bound/upper_bound 对(如果未找到元素,则相等)。 @KerrekSB:equal_rangefirst 返回为16 而请求的值是13 是否合乎逻辑。我认为这是不正确的结果;它应该返回 off-end 而不是返回不正确的结果。 是的,因为结果是一个范围,如果没有找到,则范围是empty。 (询问范围的正确问题不是它从哪里开始,而是其中有什么。)此外,范围具有告诉您元素 如果存在 在哪里的价值,这允许您,比如说,便宜地插入它。 【参考方案1】:

运行这个程序,它按预期工作:它返回结束迭代器。

int main (int argc, char** argv) 
    std::set<int> si 5, 7, 23, 16, 81, 24, 10;
    auto it = si.equal_range(99);

    if(it.first == std::end(si)) 
        std::cout << "Element not found." << std::endl;
    
    else 
        std::cout << *it.first << ", " << *it.second << std::endl;
    

    return 0;

但是,如果我要检查 13,我会回复 16, 16

根据cppreference.com

Returns a range containing all elements with the given key in the container. The range is defined by two iterators, one pointing to the first element that is not less than key and another pointing to the first element greater than key. Alternatively, the first iterator may be obtained with lower_bound(), and the second with upper_bound().

16 恰好是您的示例中不小于且大于 13 的第一个元素。

【讨论】:

是的,并且在您所指的书的第 440 页上也提到过,还请注意,如果您在 16-16 感到困惑,set 中的元素将被排序(使用严格的弱排序) CppReference 的链接好像坏了。还是谢谢你。 @ItachiUchiwa 很奇怪,不知怎的,我在 URL 的末尾加了一个逗号。现在应该可以工作了!

以上是关于用于关联容器的 C++ 入门 5ed equal_range的主要内容,如果未能解决你的问题,请参考以下文章

C++从入门到入土第二十篇:关联式容器-map和set

C++从入门到入土第二十篇:关联式容器-map和set

STL_关联容器 VS C++ hashmap

C++ STL常用标准库容器入门(vector,map,set,string,list...)

C++ STL常用标准库容器入门(vector,map,set,string,list...)

c++关联容器