C++ map::begin()、end()

在C++中,std::map是一个关联容器,它提供了一种键-值对的存储方式,并按照键的排序顺序进行自动排序。map类提供了一系列的成员函数,其中包括begin()和end()函数,用于获取指向map容器中第一个元素和最后一个元素之后位置的迭代器。

下面是关于begin()和end()函数的详细解释:

map::begin()函数

iterator begin();
const_iterator begin() const;

这个函数返回一个指向map容器中第一个元素的迭代器。如果map为空,返回的迭代器等于end()函数返回的迭代器,表示指向map容器的末尾。

例如:

std::map<int, std::string> myMap;
// 添加一些元素到myMap中
std::map<int, std::string>::iterator it = myMap.begin();

在这个例子中,it是一个指向myMap中第一个元素的迭代器。

map::end()函数

iterator end();
const_iterator end() const;

这个函数返回一个指向map容器中最后一个元素之后位置的迭代器,也就是尾后迭代器。尾后迭代器不指向具体的元素,而是表示map容器的末尾。

例如:

std::map<int, std::string> myMap;
// 添加一些元素到myMap中
std::map<int, std::string>::iterator it = myMap.end();

在这个例子中,it是一个指向myMap中最后一个元素之后位置的迭代器,表示尾后迭代器

example

#include <iostream>
#include <map>

int main() {
    
    
    std::map<int, std::string> myMap = {
    
    {
    
    1, "apple"}, {
    
    2, "banana"}, {
    
    3, "orange"}};

    // 使用auto关键字推导迭代器类型
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
    
    
        std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/neuzhangno/article/details/132452416
今日推荐