Agrudge Amicus
Agrudge Amicus

Reputation: 1103

creating map with vector/list iterator as key

I am confused over the cause of this humongous error in g++ in this code:

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

There is error when list is used but not when vector is used - why? I understand how a list\vector behaves (theoretically) but still I can't find a reason for this.

ERROR:

error: no match for ‘operator<’ (operand types are ‘const std::_List_iterator’ and ‘const std::_List_iterator’) { return __x < __y; }

Upvotes: 1

Views: 42

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

The standard class std:: list has bidirectional iterators that do not have the operator < while std::vector has direct access iterators for which the operator < is defined.

This operator < is used for ordering data in std::map because by default it uses the function object std::less.

Here is a declaration of the class template std::map

template<class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map;

Upvotes: 4

Related Questions