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!
Creating Sets of Pairs Variable 'x' is of type 'pairs'. To access the elements of the pair, use variable name followed by dot operator followed by the keyword 'first' or 'second', these are public members of class pair.
Set of pairs in C++No duplicate pair is allowed in a set of pairs. Elements of such a set, i.e pairs are sorted according to the key that is the first element of each pair present in the set. We can search for a particular pair, add pair, remove pair and can get the count of pair present.
Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The pair container is a simple container defined in <utility> header consisting of two data elements or objects.
set::size() in C++ STL size() function is used to return the size of the set container or the number of elements in the set container. Return Value: It returns the number of elements in the set container.
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;
}
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With