【发布时间】:2022-01-04 12:23:51
【问题描述】:
#include <iostream>
#include<vector>
#include<map>
using namespace std;
int main() {
vector<int> v1{1,2,3,4,5};
auto it1 = v1.begin();
auto it2 = v1.end();
if(it1<it2){
cout<<"TRUE"<<endl; // Output: TRUE
}
map<int,int> m;
m.insert(make_pair(1,2));
m.insert(make_pair(5,7));
auto it3 = m.begin();
auto it4 = m.end();
if(it3<it4){
cout<<"TRUE"<<endl;
}
/*
error: no match for 'operator<' (operand types are 'std::_Rb_tree_iterator<std::pair<const int, int> >' and 'std::_Rb_tree_iterator<std::pair<const int, int> >')
18 | if(it3<it4){
| ~~~^~~~
*/
}
Line (it1
【问题讨论】:
-
iterator categories 有不同的类型。 Vector 使用(旧版)随机访问迭代器,而 map 使用(旧版)双向迭代器。可以比较随机访问迭代器的排序,而双向迭代器则不能。
-
除非你只是因为好奇才问(请edit你的问题说明这一点)然后请询问你原来的潜在问题。为什么需要比较地图迭代器的排序?你认为它会解决什么问题?
-
FWIW 考虑到标签,
std::map基本上是一棵红黑树,而不是哈希图(参见std::unordered_map)。 (这就是为什么这个实现的迭代器被命名为_Rb_tree_iterator。)
标签: c++ dictionary stl hashmap iterator