Reputation: 1481
Hi all I am a newbie to c++. After compiling this program, I get an error msg saying .
assign3_3.cpp:120:9: error: could not convert 'sPair' from 'std::set<pairT, clas
scomp>' to 'std::set<pairT>'
here is my code.
#include <set>
#include <string>
#include <iostream>
using namespace std;
struct pairT
{
string first, second;
};
struct classcomp
{
bool operator() (const pairT &lhs, const pairT &rhs) const
{
if (lhs.first == rhs.first && lhs.second == rhs.second)
{
return 0;
}
else if (lhs.first < rhs.first)
{
return -1;
}
else if (lhs.first == rhs.first && lhs.second < rhs.second)
{
return -1;
}
else
{
return 1;
}
}
};
set<pairT> CartesianProduct(set<string> & one, set<string> & two);
int main()
{
string A = "ABC";
string B = "XY";
set<string> sA, sB;
sA.insert(&A[0]);
sA.insert(&A[1]);
sA.insert(&A[2]);
sA.insert(&B[0]);
sA.insert(&B[1]);
set<pairT> pT = CartesianProduct(sA, sB);
//for (set<pairT>::iterator it = pT.begin(); it != pT.end(); it++)
// cout << pT.find(it).first << pT.find(it).second << endl;
return 0;
}
set<pairT> CartesianProduct(set<string> &one, set<string> &two)
{
set<string>::iterator itA, itB;
pairT pT;
set<pairT, classcomp> sPair;
for (itA = one.begin(); itA != one.end(); itA++)
{
//cout << *itA << endl;
for(itB = two.begin(); itB != two.end(); itB++)
{
pT.first = *itA;
pT.second = *itB;
sPair.insert(pT);
}
}
return sPair;
}
First, I am not understanding about the making a comparison function for pairT. If this is the case here, please explain. I am having a trouble using set container please help thanks and merry christmas !
Upvotes: 1
Views: 263
Reputation: 18652
In addition to what Kerrek SB said, your comparison function isn't correct.
The comparator required by std::set<std::pair>
needs to follow the following logic:
if (lhs.first < rhs.first)
return true;
else if (lhs.first == rhs.first && lhs.second < rhs.second)
return true;
else
return false;
This can be expressed more compactly as:
return lhs.first < rhs.first ||
!(rhs.first < lhs.first) && lhs.second < rhs.second;
Fortunately, this is how std::pair::operator<
is defined in the standard library. When you create a std::set<std::pair>
this operator will be used by default so you don't have to provide your own.
Upvotes: 0
Reputation: 477454
The comparator is part of the type. You must say set<pairT, classcomp>
everywhere. Best to use a typedef.
Upvotes: 3