C++ STL中的unordered_map end()函数
unordered_map::end() 是C++ STL中的一个内置函数,它返回一个迭代器,该迭代器指向unordered_map容器中 最后一个 元素的位置。在unordered_map对象中,并没有保证哪个特定的元素被认为是其第一个元素,但是由于迭代范围从其begin到其end并在范围内失效,因此容器中的所有元素都包含在内。
语法:
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是96,他的桶编号是4
Marks of Aman是37,他的桶编号是3
Marks of Rohit是64,他的桶编号是3