Find an element in std::set by a custom comparator - c++

I created a class Route which I wanted to store in an std::set. A Route is indexed by an Id, so what I want is to be able to have an expression like
class RouteTemplate
{
Route *RouteTemplate::getRoute(const char *pId);
Route::ptr_set mRoutes;
};
Route *RouteTemplate::getRoute(const char *pId)
{
Route::ptr_set::const_iterator pos = mRoutes.find(pId);
if(pos == mRoutes.end())
return NULL;
return *pos;
}
However I get a compiler error.
conversion from 'const char *' to 'Route *const ' not possible
As far as I know I have to implement the comparator, which I did.
class Route
{
public:
static const size_t _id_len = 11;
class comparator
{
public:
bool operator() (const Route &oLeft, const Route &oRight) const
{
return oLeft < oRight;
}
};
class ptr_comparator
{
public:
bool operator() (const Route *oLeft, const Route *oRight) const
{
return (*oLeft) < (*oRight);
}
};
typedef std::set<Route, Route::comparator> set;
typedef std::set<Route *, Route::ptr_comparator> ptr_set;
public:
Route(void);
Route(const char *oId);
virtual ~Route(void) {};
inline bool operator<(const Route &oOther) const
{
return strncmp(mId, oOther.mId, _id_len) < 0;
}
inline bool operator<(const char *oId) const
{
if(!oId)
return false;
return strncmp(mId, oId, _id_len) < 0;
}
inline const char *getId(void) const { return mId; }
inline void setId(const char *oId)
{
if(oId == NULL)
mId[0] = 0;
else
{
strncpy(mId, oId, sizeof(mId));
mId[_id_len] = 0;
}
}
private:
char mId[_id_len+1];
// Additional members
};

I assume you want to leverage the templated overload of std::set::find that was added in C++14. Before that, you could only find() a key of the Key type that is used for the std::set. So, the first thing to do is using a C++14 compiler.
Second, that additional overload can only function if the resulting comparison has the same semantics as would have constructing a (temporary) key and comparing it with the std::sets comparator. If I'm not missing anything, your comparators would qualify for this. However, to avoid accidental mistakes, you have to explicitly confirm that by giving the Compare type a type member is_transparent.
If you can live with a temporary being created, you could explicitly ask for it. This should work.
Route *RouteTemplate::getRoute(const char *pId)
{
Route temporary_key {pId};
Route::ptr_set::const_iterator pos = mRoutes.find(&temporary_key);
if(pos == mRoutes.end())
return NULL;
return *pos;
}

You could also overload operator&, to allow invoking it on temporary object. This would simplify usage o find method as you could create Route object on the fly and then apply operator& at this temporary.
class Route
{
public:
...
Route* operator&() { return this; }
...
}
Then it would be valid to write getRoute() method like:
Route *RouteTemplate::getRoute(const char *pId)
{
Route::ptr_set::const_iterator pos = mRoutes.find(&Route(pId));
if (pos == mRoutes.end())
return NULL;
return *pos;
}

Related

no matching function call to error in vector.push_back

I am getting the following error while compiling my C++ program:
error: no matching function for call to 'std::vector<ChainingTable<int>::Record, std::allocator<ChainingTable<int>::Record> >::push_back(ChainingTable<int>::Record*)'
324 | vector_.push_back(new Record(key, value));
The error is coming from the line:
template <class TYPE>
bool ChainingTable<TYPE>::update(const std::string &key, const TYPE &value)
{
if (!keyExists)
{
vector_.push_back(new Record(key, value));
}
}
This is defined for the class:
class ChainingTable : public Table<TYPE>
{
struct Record
{
TYPE data_;
std::string key_;
Record(const std::string &key, const TYPE &data)
{
key_ = key;
data_ = data;
}
};
std::vector<std::vector<Record>> records_;
int capacity_; // capacity of the array
Complete code:
int sz = numRecords();
bool rc = true;
std::hash<std::string> hashFunction;
size_t hash = hashFunction(key);
size_t idx = hash % capacity_;
std::vector<Record> vector_ = records_[idx];
bool keyExists = false;
for (int i = 0; i < vector_.size(); i++)
{
if (vector_[i].key_ == key)
{
vector_[i].data_ = value;
keyExists = true;
}
}
if (!keyExists)
{
vector_.push_back(new Record(key, value));
}
What could be the reason for this?
Your vector is declared to store objects of type Record, not pointers to them (Record *) but you are trying to push result of operator new which returns Record *, just use std::vector::emplace_back instead:
vector_.emplace_back(key, value);
Note: in this line
std::vector<Record> vector_ = records_[idx];
you create a copy and later modify it, seems that you need a reference.
Note2: in your search loop you do not terminate even if you find object already, you should add break into if statement, that will make it more effective.
The problem is that your variable vector_ holds objects of type Record but when you write:
vector_.push_back(new Record(key, value));
You are trying to add a pointer to a Record object in the vector vector_ instead of adding the Record object itself.
You can solve it by writing:
vector_.emplace_back(key, value);
Alternate solution
Note that there is another possible solution which is to use:
vector_.push_back(Record(key, value));
But using emplace_back should be preferred.

I try to use MAP container to map resources, why is this not woring?

This is giving me an operator error when I compile it. No other error show up.
#include <map>
struct RESOURCE {
char Name[MAX_PATH] = { NULL };
int Level = 0;
};
struct RESOURCEFILE {
char FileName[MAX_PATH] = { NULL };
DWORD ATTRIBUTE = 0;
};
map <RESOURCE, RESOURCEFILE> ResourcesMap;
void PolulateResources(RESOURCE Resource, RESOURCEFILE File){
ResourcesMap[Resource] = File;
};
The reason this doesn't compile is because you are trying to use a map with key type RESOURCE. By default the compare function for std::map uses less-than-operator(<) for the key type to order the map. You haven't defined one here.
You can fix the issue by defining a operator< for RESOURCE:
struct RESOURCE {
char Name[MAX_PATH] = { NULL };
int Level = 0;
bool operator<(const RESOURCE& other) const
{
//write your compare function here...
//return (strcmp(Name, other.Name) < 0);
}
};
(It might be easier to use std::string for Name since it already has a operator<).
Alternatively you could define a functor or a lambda for the compare function.

Preventing assignment by subscript operator by not returning references causes runtime crash

I'm doing this:
template<typename T> class var_accessor {
public:
std::set<std::shared_ptr<T>> varset;
std::map<std::string,std::shared_ptr<T>> vars_by_name;
std::map<uint32,std::shared_ptr<T>> vars_by_id;
std::shared_ptr<T> operator[](const uint32& index) { return vars_by_id[index]; }
std::shared_ptr<T> operator[](const std::string& index) { return vars_by_name[index]; }
bool is_in_set(std::shared_ptr<T> what) { auto it = varset.find(what); if (it == varset.end()) return false; return true; }
bool is_in_set(uint32 what) { auto it = vars_by_id.find(what); if (it == vars_by_id.end()) return false; return true; }
bool is_in_set(std::string& what) { auto it = vars_by_name.find(what); if (it == vars_by_name.end()) return false; return true; }
bool place(std::shared_ptr<T> what, const uint32 whatid, const std::string& whatstring) {
if (is_in_set(what)) return false;
varset.emplace(what);
vars_by_name.emplace(whatstring,what);
vars_by_id.emplace(whatid,what);
return true;
}
};
Then...
class whatever {
std::string name;
std::function<int32()> exec;
};
And:
class foo {
public:
var_accessor<whatever> stuff;
};
This works:
std::shared_ptr<whatever> thing(new whatever);
thing->name = "Anne";
thing->exec = []() { return 1; }
foo person;
person.stuff.emplace(thing, 1, thing->name);
Getting the name crashes it:
std::cout << person.stuff[1]->name;
But if I change the operator[]'s to return references, it works fine.
I don't want to be able to accidentally add new elements without adding to all 3 structures, so that's why I made
std::shared_ptr<T> operator[]
instead of
std::shared_ptr<T>& operator[]
Is there any way to prevent assignment by subscript but keep the subscript operator working?
To be clear I want to be able to keep doing
std::cout << person.stuff[4];
But NOT be able to do
std::shared_ptr<whatever> bob(new whatever);
bob->name = "bob";
person.stuff[2] = bob;
The error is a EXC_BAD_ACCESS inside the std::string class madness
Everything I read says simply "don't return references if you want to prevent assignment" but it also prevents using it for me.
Yes I know some things should be made private but I just want to get it working first.
Using Clang/LLVM in XCode 5.1
Thanks!
You should return a const reference. See this question
A const reference means the caller is not allowed to change the value, only look at it. So assignment will be a compile-time error. But using it will work (and be efficient).

Sorting a vector of a class

I have class called "UltrasoundTemplate". These UltrasoundTemplate objects contain an int parameter, which shows when they where defined (something like a time stamp). And I have a class called "UltrasoundTarget" which contains a vector of UltrasoundTemplate's.
I add UltrasoundTemplates to the vector with push_back(ultrasoundTemplate).
Now I want to sort the vector by the order of time stamps instead of the order I added them to the vector.
I found a lot of answers in google, which all show me the same solution, but obviously I'm still doing something wrong. Here are the code snippets I think are necessary for finding a solution:
ultrasoundTemplate.h
class UltrasoundTemplate
{
public:
UltrasoundTemplate(/*...*/);
int getVolumePos() { return volume_; }
private:
int volume_;
};
ultrasoundTarget.h
//the sort algorithm
struct MyTemplateSort {
bool operator() ( UltrasoundTemplate t1, UltrasoundTemplate t2){
int it1 = t1.getVolumePos();
int it2 = t2.getVolumePos();
if (it1 < it2)
return true;
return false;
}
};
class UltrasoundTarget
{
public:
UltrasoundTarget(/*...*/);
vector<UltrasoundTemplate> getTemplates() { return USTemplateVector_; }
private:
vector<UltrasoundTemplate> USTemplateVector_;
};
FMainWindow.cpp
void FMainWindow::match_slot()
{
int i;
//here I get the name of the target I'm looking for
QTreeWidgetItem *item = targetInfoWidget_->treeWidget->currentItem();
int index = targetInfoWidget_->treeWidget->indexOfTopLevelItem(item);
QString itemToAppendName = item->text(0);
for(i = 0; i < USTargetVector.size(); i++){
if(USTargetVector.at(i).getName() == itemToAppendName) {
//here I try to sort
MyTemplateSort tmpltSrt;
std::sort(USTargetVector.at(i).getTemplates().begin(),
USTargetVector.at(i).getTemplates().end(), tmpltSrt);
break;
}
}
As an example: I define Template1 in Volume(0), Template2 in Volume(70) and Template3 in Volume(40). The order now is (Template1, Template2, Template3) but I want it to be (Template1, Template3, Template2). But this code is not doing it.
If there's Information missing, just tell me and I'll provide more code.
Thanks alot.
Your getTemplates() method returns by value, making a mess here:
std::sort(USTargetVector.at(i).getTemplates().begin(),
USTargetVector.at(i).getTemplates().end(), tmpltSrt);
You are sorting an incompatible iterator range. You can fix that particular problem by returning a reference:
vector<UltrasoundTemplate>& getTemplates() { return USTemplateVector_; }
It is common practice to add a const overload to such a method:
const vector<UltrasoundTemplate>& getTemplates() const { return USTemplateVector_; }
You can also modify your comparison functor to avoid unnecessary copies (and for general readability and const correctness):
struct MyTemplateSort {
bool operator() const ( const UltrasoundTemplate& t1, const UltrasoundTemplate& t2)
{
return t1.getVolumePos() < t2.getVolumePos();
}
};
This will require that you make getVolumePos() a const method, which it should be anyway:
class UltrasoundTemplate
{
public:
...
int getVolumePos() const { return volume_; }
...
};
Note that is is not generally good practice to provide references to the private data of a class. If possible, you should find a way to remove that from the UltraSoundTarget interface. You could, for instance, expose a pair of iterators, and/or give the class a sort method.
juanchopanza answer is correct, the problem is the way you are returning the vector from UltrasoundTarget. Just to touch another topic, maybe it would be nice to change a little the designing of your implementation. As UltrasoundTarget is a container of Ultrasound's, it makes sense to implement the sort as a method of this class, this way you have direct access to USTemplateVector_ and will save unecessary copies. Something like:
class UltrasoundTarget
{
public:
UltrasoundTarget(/*...*/);
vector<UltrasoundTemplate> getTemplates() { return USTemplateVector_; }
void sort();
private:
vector<UltrasoundTemplate> USTemplateVector_;
};
void UltrasoundTarget::sort()
{
std::sort(USTemplateVector_.begin(), USTemplateVector_.end(), tmpltSrt);
}
void FMainWindow::match_slot()
{
int i;
//here I get the name of the target I'm looking for
QTreeWidgetItem *item = targetInfoWidget_->treeWidget->currentItem();
int index = targetInfoWidget_->treeWidget->indexOfTopLevelItem(item);
QString itemToAppendName = item->text(0);
for(i = 0; i < USTargetVector.size(); i++){
if(USTargetVector.at(i).getName() == itemToAppendName)
{
//here I try to sort
MyTemplateSort tmpltSrt;
USTargetVector.at(i).sort();
break;
}
}

How can I create a switch for class members?

Say I have a class with a couple of data members, and I want a class method that returns one, and the next time it is called returns the value of the other. Something like:
class MyClass
{
public:
MyClass():switch(0){};
int get();
private:
int intA, intB;
int sw;
};
int MyClass::get()
{
if ( (++sw)%2 )
return intA;
else
return intB;
}
What would a more elegant way of doing it be? I don't like the if...else statement very much. It's fine for something like return, but if I'm actually using more complex operations, I end up duplicating a ton of code. Or having to create a second method within each method that is called after I resolve what element I'm pointing to.
What I'd prefer to do, ideally, is to use some form of pointer, so I can do
class MyClass
{
public:
MyClass():switch(&intA){};
int get();
void toggleSwitch();
private:
int intA, intB;
int * sw;
};
int MyClass::get()
{
return *sw;
}
void MyClass::toggleSwitch()
{
if ( sw == &intA )
sw = &intB;
else
sw = &intA;
}
Or something to that effect. I could call toggleSwitch(), and have my class operate on either one or the other value easily.
I still don't like it though. I prefer to avoid if's when possible, and I shouldn't need one in this case. This use of a naked pointer should be pretty safe, but I was thinking I could have something like std::unique_ptr holding each element and then std::swap them. But then the pointers would own the elements, and they'd be dynamic memory instead.
So is there a better way to do it?
Well, switch is a keyword, but I'll roll with it. How about an array of pointers?
int *fields[] = {&intA, &intB};
int MyClass::get()
{
return *fields[++switch % 2];
}
This would expand nicely if you could have additional variables later.
Or maybe:
int MyClass::get()
{
return *fields[switch = 1 - switch];
}
If you return a reference then you could use get() internally.
int &MyClass::get()
{
return *fields[switch = 1 - switch];
}
I would encapsulate the concept of a toggling value:
template<typename T>
class Toggleable {
T first;
T second;
T* current;
T* other;
public:
Toggleable(const T& first, const T& second)
: first(first),
second(second),
current(&first),
other(&second) {
}
bool toggle() {
std::swap(current, other);
}
const T& get() const {
return *current;
}
}
Then use as:
class MyClass
{
Toggleable<int> value;
public:
MyClass()
: value(42, 1729)
{
}
const int& get() {
value.toggle();
return value.get();
}
};