Safwan Ull Karim
Safwan Ull Karim

Reputation: 662

find a pair in set c++

if I have a set which contains pairs of int,

set<pair<int,int> > cells;

how can I find whether a pair exits in the set using 'find'. I can use 'find' for set with one value but cant do it for a pair.

I am trying like,

 cells.insert(make_pair(1,1));
 set<int,int>::iterator it;
 it=cells.find(pair<int,int>(1,1));

error: no match for 'operator=' in 'it = cells.std::set<_Key, _Compare, _Alloc>::find<std::pair<int, int>, std::less<std::pair<int, int> >, std::allocator<std::pair<int, int> > >((*(const key_type*)(& std::pair<int, int>((* &1), (* &1)))))'|

Has anyone got any ideas? Thanks!

Upvotes: 8

Views: 27267

Answers (3)

Zafi
Zafi

Reputation: 629

The problem is that your set is a set of a pair of integersstd::pair<int,int>, instead of just <int,int>. Changing that fixes your code. If you are using c++11 or later you can just use the auto keyword.

// Example program
#include <iostream>
#include <string>
#include <utility>
#include <set>

int main()
{
    std::pair<int,int> p1(1,0);
    std::pair<int,int> p2(2,1);
    std::set<std::pair<int,int>> s;
    s.insert(p1);
    s.insert(p2);
    auto it = s.find(p1);
    std::cout << it->first << "," << it->second <<std::endl;
}

Upvotes: 3

Humam Helfawi
Humam Helfawi

Reputation: 20274

It should be:

std::set<std::pair<int,int>> cells;
cells.insert(std::make_pair(1,1));
std::set<std::pair<int,int>>::iterator it; // here was the problem
it=cells.find(std::pair<int,int>(1,1));

In order to avoid these kind of mistakes you may use auto:

std::set<std::pair<int,int>> cells;
cells.insert(std::make_pair(1,1));
auto it =cells.find(std::pair<int,int>(1,1));

If you have to separate the definition and the use of it:

decltype(cells)::iterator it;
it=cells.find(std::pair<int,int>(1,1));

Live Demo

Upvotes: 1

R Sahu
R Sahu

Reputation: 206607

There seems to be a typo/misunderstanding about the type to be used for it. You need to use:

std::set<std::pair<int,int>>::iterator it;

Upvotes: 2

Related Questions