我对这段代码中 g++
中这个巨大错误的原因感到困惑:
#include<iostream>
#include<map>
#include<utility>
#include<vector>
#include<list>
using namespace std;
int main()
{
list<int> p={1,2,3,4};
map<list<int>::iterator, int> q;
q[p.begin()]=9991;
cout<<q[p.begin()]<<endl;
return 0;
}
使用 list
时有错误,但使用 vector
时却没有 - 为什么?我了解 list
\vector
的行为方式(理论上),但我仍然找不到原因。
错误:
error: no match for ‘operator<’ (operand types are ‘const std::_List_iterator’ and ‘const std::_List_iterator’) { return __x < __y; }
最佳答案
标准类std:: list
有没有 operator <
的双向迭代器同时 std::vector
有直接访问迭代器,其 operator <
已定义。
这operator <
用于 std::map
中的订购数据因为默认情况下它使用函数对象 std::less
.
这是类模板 std::map 的声明
template<class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map;
关于c++ - 创建以 vector/列表迭代器为键的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58420375/