当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。