0

C++ プライム 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に見つかりませんでしたがpair、要素のイテレータを返します16, 16?!
4

1 に答える 1

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 以上の最初の要素です。

于 2019-10-07T00:47:06.097 に答える