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

In C++, std::map is an associative container that provides a way to store key-value pairs and automatically sorts them according to the sort order of the keys. The map class provides a series of member functions, including begin() and end() functions, which are used to obtain iterators pointing to the position after the first element and the last element in the map container.

The following is a detailed explanation of the begin() and end() functions:

map::begin() function

iterator begin();
const_iterator begin() const;

This function returns an iterator pointing to the first element in the map container. If the map is empty, the returned iterator is equal to the iterator returned by the end() function, indicating that it points to the end of the map container.

For example:

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

In this example, it is an iterator pointing to the first element in myMap.

map::end() function

iterator end();
const_iterator end() const;

This function returns an iterator pointing to the position after the last element in the map container, which is the tail iterator. The tail iterator does not point to a specific element, but represents the end of the map container.

For example:

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

In this example, it is an iterator pointing to the position after the last element in myMap, indicating the tail iterator

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;
}

Guess you like

Origin blog.csdn.net/neuzhangno/article/details/132452416