g4ur4v
g4ur4v

Reputation: 3288

Using map with queue in c++

When try to run below piece of code,It compiles without any errors.

int main()
{
    queue<map<int,int> >run_time;
}

But,now when I try to push something into the queue using the below code.

int main()
{
    queue<map<int,int> >run_time;

    run_time.push(make_pair(1,2));
    run_time.push(make_pair(3,4));
}

I get error as :

no matching function for call to 'std::queue<std::map<int,int,std::less<int>,std::allocator<std::pair<const int,int>

Upvotes: 1

Views: 4534

Answers (3)

Gaganjot Singh
Gaganjot Singh

Reputation: 9

From the code given in the question it looks like you want to create a Queue for which each element of Queue is a group of two other elements. This can be easily done using class template "pair" or "tuple".

For pair[1] you write template <class T1, class T2> struct pair; while for tuple[2] template <class... Types> class tuple;

Tuple is generalization of pair where more than two members can form group. What I feel is wrong in your code is that you are initializing a map but not using it as a Map, you want to push individual elements of Map in Queue which demolish the purpose of creating a Map. Pair and Tuple create individual objects which can be treated separately from other similar objects, they act similar to as using struct to form group of different data types.

[1]. http://www.cplusplus.com/reference/utility/pair/

[2]. http://www.cplusplus.com/reference/tuple/tuple/

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227418

You have a queue of maps, not a queue of pairs. You need to push maps into it.

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258618

The problem is that make_pair doesn't create a map. You'll need to create the map beforehand, insert into it with make_pair, and insert the map itself into the queue.

map<int,int> x;
x.insert(make_pair(1,2));
run_time.push(x);

Upvotes: 4

Related Questions