當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ unordered_map end( )用法及代碼示例


unordered_map::end()是C++ STL中的內置函數,該函數返回一個迭代器,該迭代器指向unordered_map容器中容器中最後一個元素之後的位置。在unordered_map對象中,不能保證將哪個特定元素視為其第一個元素。但是容器中的所有元素都被覆蓋了,因為範圍從其開始到結束直到無效。

用法:

iterator unordered_map_name.end(n)

參數:該函數接受一個參數n,它是一個指定桶號的可選參數。如果設置了該值,則迭代器將檢索指向存儲桶的past-the-end元素的指向,否則,指向容器的past-the-end元素。


返回值:該函數將迭代器返回到容器末尾的元素。

以下示例程序旨在說明上述函數:

示例1:

// CPP program to demonstrate the 
// unordered_map::end() function 
// returning all the elements of the multimap 
#include <iostream> 
#include <string> 
#include <unordered_map> 
using namespace std; 
  
int main() 
{ 
    unordered_map<string, int> marks; 
  
    // Declaring the elements of the multimap 
    marks = { { "Rohit", 64 }, { "Aman", 37 }, { "Ayush", 96 } }; 
  
    // Printing all the elements of the multimap 
    cout << "marks bucket contains : " << endl; 
    for (int i = 0; i < marks.bucket_count(); ++i) { 
  
        cout << "bucket #" << i << " contains:"; 
  
        for (auto iter = marks.begin(i); iter != marks.end(i); ++iter) { 
            cout << "(" << iter->first << ", " << iter->second << "), "; 
        } 
  
        cout << endl; 
    } 
    return 0; 
}
輸出:
marks bucket contains : 
bucket #0 contains:
bucket #1 contains:
bucket #2 contains:
bucket #3 contains:(Aman, 37), (Rohit, 64), 
bucket #4 contains:(Ayush, 96),

程序2

// CPP program to demonstrate the 
// unordered_map::end() function 
// returning the elements along 
// with their bucket number 
#include <iostream> 
#include <string> 
#include <unordered_map> 
  
using namespace std; 
  
int main() 
{ 
    unordered_map<string, int> marks; 
  
    // Declaring the elements of the multimap 
    marks = { { "Rohit", 64 }, { "Aman", 37 }, { "Ayush", 96 } }; 
  
    // Printing all the elements of the multimap 
    for (auto iter = marks.begin(); iter != marks.end(); ++iter) { 
  
        cout << "Marks of " << iter->first << " is "
             << iter->second << " and his bucket number is "
             << marks.bucket(iter->first) << endl; 
    } 
  
    return 0; 
}
輸出:
Marks of Ayush is 96 and his bucket number is 4
Marks of Aman is 37 and his bucket number is 3
Marks of Rohit is 64 and his bucket number is 3


相關用法


注:本文由純淨天空篩選整理自Shubrodeep Banerjee大神的英文原創作品 unordered_map end() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。