#include <iostream> #include <map> using namespace std; int main() { std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}}; auto itBegin = myMap.begin(); // 迭代器指向开头位置 std::cout << itBegin->first << ": " << itBegin->second << std::endl; --itBegin; if (itBegin == myMap.end()) { std::cout << "111" << std::endl; } else { std::cout << itBegin->first << ": " << itBegin->second << std::endl; } --itBegin; if (itBegin == myMap.end()) { std::cout << "222" << std::endl; } else { std::cout << itBegin->first << ": " << itBegin->second << std::endl; } --itBegin; if (itBegin == myMap.end()) { std::cout << "333" << std::endl; } else { std::cout << itBegin->first << ": " << itBegin->second << std::endl; } --itBegin; if (itBegin == myMap.end()) { std::cout << "444" << std::endl; } else { std::cout << itBegin->first << ": " << itBegin->second << std::endl; } --itBegin; if (itBegin == myMap.end()) { std::cout << "555" << std::endl; } else { std::cout << itBegin->first << ": " << itBegin->second << std::endl; } return 0; }
输出结果:
1: one 111 3: three 2: two 1: one 555
要点:
map容器的迭代器是一个cycle,.begin()进行自减操作后,与.end()相同
.end()获取的是最后一个键-值对的下一个位置,里面没有实际内容,因此.end() 返回的迭代器不能用于解引用,否则会导致未定义行为
尝试了在vector上做同样的操作,但是得到的结果不正确