Search code examples
c++multimapdeque

print deque containing multimap


I would need to print a dequeu containing a multimap, but it's not working, what am I doing wrong?

int main()
{
    deque<multimap<string,int> > q_map;
    multimap<string,int> m;

    m.insert(pair<string, int>("a", 1));
    m.insert(pair<string, int>("c", 2));
    m.insert(pair<string, int>("b", 3));
    m.insert(pair<string, int>("b", 4));
    m.insert(pair<string, int>("a", 5));
    m.insert(pair<string, int>("b", 6));
    cout << "Map size: " << m.size() << endl;

    q_map.push_back(m);
    for (std::deque<int>::iterator it = q_map.begin(); it!=q_map.end(); ++it)
        std::cout << ' ' << *it;
}

I am always getting a compiler error:

error: conversion from ‘std::_Deque_iterator<std::multimap<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> > >, std::multimap<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> > >&, std::multimap<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> > >*>’ to non-scalar type ‘std::_Deque_iterator<int, int&, int*>’ requested
q_map.cpp:23: error: no match for ‘operator!=’ in ‘it != std::deque<_Tp, _Alloc>::end() [with _Tp = std::multimap<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> > >, _Alloc = std::allocator<std::multimap<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> > > >]()’

Solution

  • You have this type:

    deque<multimap<string,int> > q_map;
    

    But you're trying to iterate over it with this type:

    for (std::deque<int>::iterator it = q_map.begin(); ...
    

    That's what you're doing wrong.

    If you can't use the C++11 range-based for loop, or the C++11 auto feature, then instead of repeating the type multimap<string,int> everywhere, you can use a typedef for it:

    typedef multimap<string,int> mmap;
    

    Now you can refer to std::deque<mmap> everywhere you use it, so the for loop would use a std::deque<mmap>::iterator