mulitimap查找(同樣適用于multiset)

#include <iostream>
#include <map>
using namespace std;

//1.mulitmap和map的區(qū)別就是,multimap的key可以重復,而map不可以
//2.在查找時,find函數查找的是第一個key值相等的迭代器,不影響map,但是multi怎么查找所有的key值一樣的元素的迭代器呢?
//  (1)使用count(k)函數(求出鍵k出現次數)和find(k)函數(返回第一個擁有鍵k的迭代器)
//  (2)使用lower_bound(k)函數和upper_bound(k),找到k的上下界(因為multimap中的key是有序的)--左閉右開
//  (3)使用equal_range(k)函數,返回具有相同鍵值k的迭代器區(qū)間pair:[it1,it2),相當于一個上下界

int main(int argc, char** argv)
{
    multimap<int, int> testMap;
    testMap.insert(make_pair(1, 2));
    testMap.insert(make_pair(1, 3));
    testMap.insert(make_pair(1, 4));
    testMap.insert(make_pair(2, 5));
    testMap.insert(make_pair(3, 6));

    //(1)使用第一種方法查找所以key為1的元素
    int count = testMap.count(1);
    auto it = testMap.find(1);
    for (int i = 0; i < count; i++, it++)
    {
        cout << it->second << " ";
    }
    cout << endl;

    //(2)使用第二種方法查找
    auto it1 = testMap.lower_bound(1);
    auto it2 = testMap.upper_bound(1);
    for (; it1 != it2; it1++)
    {
        cout << it1->second << " ";
    }
    cout << endl;

    //(3)使用第三種方法查找
    auto it3 = testMap.equal_range(1);
    for (auto it4 = it3.first; it4 != it3.second; it4++)
    {
        cout << it4->second << " ";
    }
    cout << endl;

    return 0;
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容