std::unordered_set of pointers - c++

I have the following struct
struct MyClass {
int myInt;
std::map<int, int> myMap;
};
I want to use unordered_set<MyClass*, PointedObjHash, PointedObEq> but I can't find a valid way to declare PointedObEq.
I tried
struct PointedObjHash {
size_t operator() (MyClass* const& c) const {
std::size_t seed = 0;
boost::hash_combine(seed, c->myInt);
boost::hash_combine(seed, c->myMap);
return seed;
}
and I hope it is fine, but I can't find a way to declare PointedObjEq
--- EDIT ---
If declare operator== inside the class debug never breaks, but I think 'cause MyClass == MyClass* never happens...
struct MyClass {
...
...
bool operator==(MyClass* const& c) {
return this->myInt == c->myInt & this->myMap == c->myMap;
}

If declare operator== inside the class debug never breaks, but I think 'cause MyClass == MyClass* never happens...
The unordered_set needs to use operator== (or PointedObjEq) to double-check the results of the hash function. The hash provides approximate equality, the equality function is used to weed out false positives.
If you've tested adding the same value to the set twice, then you've tested the equality function. To be sure, of course, you can have it print something to the console.
Since it's impossible to define an operator== function with two pointer operands, the PointedObjEq class will be necessary. Note that it takes a MyClass const * on both sides. Also, there's no need to use a reference to a pointer.
So,
struct PointedObjEq {
bool operator () ( MyClass const * lhs, MyClass const * rhs ) const {
return lhs->myInt == rhs->myInt
&& lhs->myMap == rhs->myMap;
}
};

This should do:
struct PointedObEq {
bool operator()(MyClass const * lhs, MyClass const * rhs) const {
return lhs->myInt == rhs->myInt && lhs->myMap == rhs->myMap;
}
};
The reason why your solution does not work is because you have effectively written a mechanism to compare a MyClass with a MyClass*, when you actually need something to compare a MyClass* with a MyClass*.
P.S.: My original answer passed the pointers by const&. Thinking about it, that's a strange coding style, so I changed it to pass the pointers by value.

typedef MyClass* PtrMyClass;
struct PointedObjCompare
{ // functor for operator==
bool operator()(const PtrMyClass& lhs, const PtrMyClass& rhs) const
{
// your code goes here
}
};
std::unordered_set < MyClass*, PointedObjHash, PointedObjCompare > myset;

Related

The method find of a set of none const values cannot be called with const values. Can const_cast be used to solve that problem?

Let us say that p below has to be a pointer to const X. Then it is not possible to call find for a set of pointers to X with my special compare class. Is that a shortcoming of 'set' and 'find'? Is it safe to solve it with const_cast as I have done?
struct X{
std::string key;
X(std::string s): key(s) {}
};
struct compare {
bool operator() (const X* lhs, const X* rhs) const {
return lhs->key < rhs->key;
}
};
int main() {
std::set<X*,compare> m;
const X a("hello");
const X*p=&a;
std::set<X*,compare>::const_iterator it=m.find(const_cast<X*>(p));
}
This use of const_cast is safe, but any usage of const_cast is scary. const_cast is legal so long as you don't modify the object through the cast, which std::set::find does not do.
However, you don't need a const_cast here. If you make your comparator transparent, that opts into allowing find to search based on anything comparable to the key type. This is exactly what we want:
struct compare {
using is_transparent = void; // doesn't matter which type you use
bool operator() (const X* lhs, const X* rhs) const {
// You might want to consider using std::less<X*> to compare these.
// std::less<T*> can compare pointers which are not part of the
// same array, which is not allowed with just a simple less-than
// comparison.
return lhs->key < rhs->key;
}
};
Complete example: https://godbolt.org/z/NsZccs

std::set<myClass*> sorted

I wonder how is the most convenient way to have a sorted set, a set of pointers to objects, like
std::set<myClass*> mySet;
I want this set to be sorted by myClass::someProperty (say, an int).
Should I overload operator < in myClass? I'm not sure if it will work, because it's not a set of myClass, but a set of pointers.
How can I define a compare function?
Thank you very much.
You need to define a type (or a function) that dereferences the pointers and compares the attributes of the objects they point at, something on this general order:
class myClass {
int value;
public:
myClass(int i = 0) : value(i) {}
struct cmp {
bool operator()(myClass *const &a, myClass *const &b) const {
return a->value < b->value;
}
};
};
We they define the set something like this:
std::set<myClass*, myClass::cmp> mySet;
My advice, however, would be to store objects instead of pointers (if possible).
You can also specialize std::less for your myClass* as given below and then no need to pass comparator while creating set:
namespace std {
template<>
struct less<myClass*>
{
bool operator()(const myClass* k1, const myClass* k2) const
{
// Some code ...
}
};
}

Comparsion between structs for a set

This code works but having a struct called ptrcomp outside the weighted_pointer seems (to me) that they are different things. I tried some different ways and even googled it, but I haven't found anything that works like this.
struct node{
unsigned int oper;
void * a;
void * b;
};
struct weighted_pointer{
mutable int weight;
unique_ptr<node> pointer;
};
struct ptrcomp{
bool operator()(const weighted_pointer & lhs, const weighted_pointer & rhs) {
return tie(lhs.pointer->oper, lhs.pointer->a, lhs.pointer->b) < tie(rhs.pointer->oper, rhs.pointer->a, rhs.pointer->b);
}
};
set<weighted_pointer,ptrcomp> gate;
My objective is to make the std::set working. And possibly write it like set<weighted_pointer>.
having a struct called ptrcomp outside the weighted_pointer seems (to me) that they are different things.
That's how things really are. weighted_pointer is data, while ptrcomp is a way to compare the data. So, these two really are different things, and there is nothing wrong with your code.
If it happens that you have one canonical way of comparing your data, make it into operator <:
bool operator < (const weighted_pointer & lhs, const weighted_pointer & rhs) {
return tie(lhs.pointer->oper, lhs.pointer->a, lhs.pointer->b) < tie(rhs.pointer->oper, rhs.pointer->a, rhs.pointer->b);
}
std::set will happily use it, if you use it as std::set<weighted_pointer> (in fact, std::set has the second template parameter defaulted to std::less<T>, which is a comparator class that uses operator <).
If you change your code to
struct weighted_pointer {
mutable int weight;
unique_ptr<node> pointer;
bool operator < (const weighted_pointer & rhs) const;
};
bool weighted_pointer::operator < (const weighted_pointer & rhs) const {
return tie(pointer->oper, pointer->a, pointer->b) < tie(rhs.pointer->oper, rhs.pointer->a, rhs.pointer->b);
}
then it will work and you won't need a comparator ptrcomp for the set and can use the type set<weighted_pointer> as you wished. (You can also move the definition into the struct if you wish.)
struct weighted_pointer {
// ...
struct compare {
// ...
};
};
set<weighted_pointer,weighted_pointer::compare> gate;
// better
using weighted_pointer_set = set<weighted_pointer,weighted_pointer::compare>;
weighted_pointer_set gate;
This is how I see this usually done.
Having a std::set<weighted_pointer> means that the set uses std::less to compare the elements. This in turn calls operator< on the respective type, so if you provide an implementation of that operator it'll work.

How to create a set with my customized comparison in c++

Could someone explain me what is going on in this example here?
They declare the following:
bool fncomp (int lhs, int rhs) {return lhs<rhs;}
And then use as:
bool(*fn_pt)(int,int) = fncomp;
std::set<int,bool(*)(int,int)> sixth (fn_pt)
While the example for the sort method in algorithm library here
can do like this:
bool myfunction (int i,int j) { return (i<j); }
std::sort (myvector.begin()+4, myvector.end(), myfunction);
I also didn't understand the following:
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs<rhs;}
};
this keyword operator (not being followed by an operator as in a op. overload)... what is the meaning of it? Any operator applied there will have that behavior? And this const modifier... what is the effect caused by it?
I was trying to make a set of C-style string as follows:
typedef struct
{
char grid[7];
} wrap;
bool compare(wrap w1, wrap w2)
{
return strcmp(w1.grid, w2.grid) == -1;
}
set <wrap, compare> myset;
I thought I could create a set defining my sorting function in a similar as when I call sort from algorithm library... once it didn't compile I went to the documentation and saw this syntax that got me confused... Do I need to declare a pointer to a function as in the first example i pasted here?
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs<rhs;}
};
Defines a functor by overloading the function call operator. To use a function you can do:
int main() {
std::set <wrap, bool (*)(wrap,wrap)> myset(compare);
return 0;
}
Another alternative is to define the operator as a part of the wrap class:
struct wrap {
char grid[7];
bool operator<(const wrap& rhs) const {
return strcmp(this->grid, rhs.grid) == -1;
}
};
int main() {
wrap a;
std::set <wrap> myset;
myset.insert(a);
return 0;
}
You're almost there... here's a "fixed" version of your code (see it run here at ideone.com):
#include <iostream>
#include <set>
#include <cstring>
using namespace std;
typedef struct
{
char grid[7];
} wrap;
bool compare(wrap w1, wrap w2) // more efficient: ...(const wrap& e1, const wrap# w2)
{
return strcmp(w1.grid, w2.grid) < 0;
}
set <wrap, bool(*)(wrap, wrap)> myset(compare);
int main() {
wrap w1 { "abcdef" };
wrap w2 { "ABCDEF" };
myset.insert(w1);
myset.insert(w2);
std::cout << myset.begin()->grid[0] << '\n';
}
"explain [to] me what is going on in this example"
Well, the crucial line is...
std::set<wrap, bool(*)(wrap, wrap)> myset(compare);
...which uses the second template parameter to specify the type of function that will perform comparisons, then uses the constructor argument to specify the function. The set object will store a pointer to the function, and invoke it when it needs to compare elements.
"the example for the sort method in algorithm library..."
std::sort in algorithm is great for e.g. vectors, which aren't automatically sorted as elements are inserted but can be sorted at any time. std::set though needs to maintain sorted order constantly, as the logic for inserting new elements, finding and erasing existing ones etc. all assumes the existing elements are always sorted. Consequently, you can't apply std::sort() to an existing std::set.
"this keyword operator (not being followed by an operator as in a op. overload)... what is the meaning of it? Any operator applied there will have that behavior? And this const modifier... what is the effect caused by it?
operator()(...) can be invoked on the object using the same notation used to call a function, e.g.:
classcomp my_classcomp;
if (my_classcomp(my_int1, my_int_2))
std::cout << "<\n";
As you can see, my_classcomp is "called" as if it were a function. The const modifier means that the code above works even if my_classcomp is defined as a const classcomp, because the comparison function does not need to modify any member variables of the classcomp object (if there were any data members).
You almost answered your question:
bool compare(wrap w1, wrap w2)
{
return strcmp(w1.grid, w2.grid) == -1;
}
struct wrap_comparer
{
bool operator()(const wrap& _Left, const wrap& _Right) const
{
return strcmp(_Left.grid, _Right.grid) == -1;
}
};
// declares pointer to function
bool(*fn_pt)(wrap,wrap) = compare;
// uses constructor with function pointer argument
std::set<wrap,bool(*)(wrap,wrap)> new_set(fn_pt);
// uses the function directly
std::set<wrap,bool(*)(wrap,wrap)> new_set2(compare);
// uses comparer
std::set<wrap, wrap_comparer> new_set3;
std::sort can use either a function pointer or a function object (http://www.cplusplus.com/reference/algorithm/sort/), as well as std::set constructor.
const modifier after function signature means that function can't modify object state and so can be called on a const object.

compare function in lower bound

I have following structure
enum quality { good = 0, bad, uncertain };
struct Value {
int time;
int value;
quality qual;
};
class MyClass {
public:
MyClass() {
InsertValues();
}
void InsertValues();
int GetLocationForTime(int time);
private:
vector<Value> valueContainer;
};
void MyClass::InsertValues() {
for(int num = 0; num < 5; num++) {
Value temp;
temp.time = num;
temp.value = num+1;
temp.qual = num % 2;
valueContainer.push_back(temp);
}
}
int MyClass::GetLocationForTime(int time)
{
// How to use lower bound here.
return 0;
}
In above code I have been thrown with lot of compile errors. I think I am doing wrong here I am new to STL programming and can you please correct me where is the error? Is there better to do this?
Thanks!
The predicate needs to take two parameters and return bool.
As your function is a member function it has the wrong signature.
In addition, you may need to be able to compare Value to int, Value to Value, int to Value and int to int using your functor.
struct CompareValueAndTime
{
bool operator()( const Value& v, int time ) const
{
return v.time < time;
}
bool operator()( const Value& v1, const Value& v2 ) const
{
return v1.time < v2.time;
}
bool operator()( int time1, int time2 ) const
{
return time1 < time2;
}
bool operator()( int time, const Value& v ) const
{
return time < v.time;
}
};
That is rather cumbersome, so let's reduce it:
struct CompareValueAndTime
{
int asTime( const Value& v ) const // or static
{
return v.time;
}
int asTime( int t ) const // or static
{
return t;
}
template< typename T1, typename T2 >
bool operator()( T1 const& t1, T2 const& t2 ) const
{
return asTime(t1) < asTime(t2);
}
};
then:
std::lower_bound(valueContainer.begin(), valueContainer.end(), time,
CompareValueAndTime() );
There are a couple of other errors too, e.g. no semicolon at the end of the class declaration, plus the fact that members of a class are private by default which makes your whole class private in this case. Did you miss a public: before the constructor?
Your function GetLocationForTime doesn't return a value. You need to take the result of lower_bound and subtract begin() from it. The function should also be const.
If the intention of this call is to insert here, then consider the fact that inserting in the middle of a vector is an O(N) operation and therefore vector may be the wrong collection type here.
Note that the lower_bound algorithm only works on pre-sorted collections. If you want to be able to look up on different members without continually resorting, you will want to create indexes on these fields, possibly using boost's multi_index
One error is that the fourth argument to lower_bound (compareValue in your code) cannot be a member function. It can be a functor or a free function. Making it a free function which is a friend of MyClass seems to be the simplest in your case. Also you are missing the return keyword.
class MyClass {
MyClass() { InsertValues(); }
void InsertValues();
int GetLocationForTime(int time);
friend bool compareValue(const Value& lhs, const Value& rhs)
{
return lhs.time < rhs.time;
}
Class keyword must start from lower c - class.
struct Value has wrong type qualtiy instead of quality
I dont see using namespace std to use STL types without it.
vector<value> - wrong type value instead of Value
Etc.
You have to check it first before posting here with such simple errors i think.
And main problem here that comparison function cant be member of class. Use it as free function:
bool compareValue(const Value lhs, const int time) {
return lhs.time < time ;
}
class is the keyword and not "Class":
class MyClass {
And its body should be followed by semicolon ;.
There can be other errors, but you may have to paste them in the question for further help.
You just want to make compareValue() a normal function. The way you have implemented it right now, you need an object of type MyClass around. The way std::lower_bound() will try to call it, it will just pass in two argument, no extra object. If you really want it the function to be a member, you can make it a static member.
That said, there is a performance penalty for using functions directly. You might want to have comparator type with an inline function call operator:
struct MyClassComparator {
bool operator()(MyClass const& m0, MyClass const& m1) const {
return m0.time < m1.time;
}
};
... and use MyClassComparator() as comparator.