In C++, how to use find_if on a map with a functor when keys are struct with strings? - stl

I have a stl::map which key type is a custom struct. I want to know if this map already has a key with a specific string as component (noted as "id" below), whatever the value of its other components. Inspired by this answer and this one also, I try to use stl::find_if with a custom functor:
map<myStruct, vector<size_t> > myMap;
struct myStruct
{
string a, b, c, id;
};
struct checkId : unary_function<pair<myStruct, vector<size_t> >, bool>
{
private:
string _exp;
public:
checkId (myStruct x) : _exp(x.id) {}
bool operator() (const pair<myStruct, vector<size_t> > & p) const
{
return p.first.id.compare(_exp) == 0;
}
};
map<myStruct, vector<size_t> >::iterator it;
myStruct newS; // to be initialized, but not shown here
it_mP2P = find_if(myMap.begin(), myMap.end(), checkId(newS));
When I compile this, gcc returns me:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = myStruct]’:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:347: instantiated from ‘_Tp& std::map<_Key,_Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = myStruct, _Tp = std::vector<long unsigned int, std::allocator<long unsigned int> >, _Compare = std::less<myStruct>, _Alloc = std::allocator<std::pair<const myStruct, std::vector<long unsigned int, std::allocator<long unsigned int> > > >]’
myprogram.cpp:386: instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:227: error: no match for ‘operator<’ in ‘__x < __y’
Does this mean that I have to overload the operator "<" to work with my custom struct if I want to use my functor "checkId"? How can I do this? I am not a C++ expert,so thanks in advance for any piece of code.

http://codepad.org/VYNqdZeF
struct myStruct
{
std::string a, b, c, id;
bool operator<(const myStruct& rhs) const //HERES THE MAGIC
{return id < rhs.id;} //WHEEEEEEEEEEEE!
};
This is required to make std::map<myStruct, stuff> work, without passing a custom comparison functor.

It's got nothing to do with checkId. The following demonstrates the same problem:
map<myStruct, vector<size_t> > myMap;
struct myStruct
{
string a, b, c, id;
};
std::map is a sorted map (it's usually implemented as a binary search tree)... the key type (myStruct in this case) must have operator< implemented simply to construct the map.
If you don't need fast lookups, you can just use a vector< pair< myStruct, vector<size_t> > >; if you need fast lookups, you have to add some kind of structure to myStruct. For a std::map this must be a comparison operator; alternatively you can use a std::unordered_map (in C++11; this is usually implemented as a hash table) -- in this case you will need to implement a hash function.
See the documentation of std::map and std::unordered_map for more details.

This has nothing to do with your use of find_if.
For a type to be a key of a map, it needs to be comparable, either by implementing operator< or by providing a comparator as a template parameter of the map.

Mooing Duck's answer is the easiest to do, but not the most flexible
if you go and write
struct myStruct
{
std::string a, b, c, id;
bool operator<(const myStruct& rhs) const
{return id < rhs.id;}
};
then all your maps that have myStruct as a key, will have to be sorted
by id.
Suppose you have one map that needs to be compared by a, and another one by b. If you put operator<() inside your myStruct, then you will have coupled the struct with its users, tightly, which is not good programming practice.
Instead, you could set a compare function to each map:
struct myStruct
{
std::string a, b, c, id; // keep your struct unchanged, and independent of clients
};
bool Compare_by_a(const myStruct &s1, const myStruct& s2) {
return s1.a < s2.a;
}
bool Compare_by_b(const myStruct &s1, const myStruct& s2) {
return s1.b < s2.b;
}
bool Compare_by_id(const myStruct &s1, const myStruct& s2) {
return s1.id < s2.id;
}
map<myStruct, vector<size_t>, Compare_by_a > map1;
map<myStruct, vector<size_t>, Compare_by_b > map2;
map<myStruct, vector<size_t>, Compare_by_id > map3;

Related

Dart - declare function as variable

In Dart - as in many other languages - there is more than one way to declare a function. The question is, are there any differences aka "when should I use which"?
void foo(int i) {
print('i = $i');
}
void main() {
void Function(int) bar = (int j) {
print('j = $j');
};
foo(1);
bar(2);
}
Is there any difference in the declaration of foo or bar other than the fact that bar can be overwritten?
Functions can be introduced by
function declarations
method decla-rations
getter declarations
setter declarations
constructor declarations
function literals
In terms of Dart specification there is 2 differences between function literals (aka anonymous function) and other declarations
it has no name - anonymous
we can't declare a return type (which only obtained by means of type inference)
If you prefer to keep type safety, you will have to write long declaration.
Consider this example:
String foo(int i, {bool b}) => '$b $i'; // return type declared
final bar = (int i, {bool b}) => '$b $i'; // return type could not be infered
final String Function(int i, {bool b}) bar = (i, {b}) => '$b $i'; // return type infered
From my perspective
bar isn't as readable as foo declaration
Let functions literals do their anonymous job =)
PS If I missed anything - please edit my answer or reach me in comments

How to set data pointed to by argument using Critcl?

I would like to express something like this in Critcl:
void setter(int* grid, int value, int x, int y) {
grid[xy2addr(x,y)] = value;
}
I'm in particular stuck on how to deal with int* grid in Critcl. object? bytes? Custom type maybe?
Related to this question.
This case doesn't map very well onto Tcl's value model. The issue is that grid is (a pointer to) an updateable value collection. There are two ways of modelling this in Tcl in general:
As an opaque object.
As a variable containing a Tcl list (since in model terms, while Tcl values are thought of as immutable, Tcl variables are mutable).
I'll describe how to do both below, but I'm guessing that you're going to be thinking of these zOrder things as a distinct mutable type and that the additional modest one-time overhead of making the custom type will suit you far better.
Opaque (Mutable) Objects
When working with opaque objects, you pass handles to them (basically just a name) around and then you unpack them as a custom Critcl type. The trick is to create some helper functions in C to do the mapping (this can be in a critcl::ccode command) that does the mapping between names and pointers. This is slightly messy to do, but is just about building a couple of hash tables.
critcl::ccode {
static Tcl_HashTable *zOrderMap = NULL, *zOrderRevMap = NULL;
static Tcl_Obj *
MakeZOrderObj(int *zOrder) {
/* Initialize the two maps, if needed */
if (zOrderMap == NULL) {
zOrderMap = (Tcl_HashTable *) Tcl_Alloc(sizeof(Tcl_HashTable));
Tcl_InitObjHashTable(zOrderMap);
zOrderRevMap = (Tcl_HashTable *) Tcl_Alloc(sizeof(Tcl_HashTable));
Tcl_InitHashTable(zOrderRevMap, TCL_ONE_WORD_KEYS);
}
int isNew;
Tcl_HashEntry *hPtr = Tcl_FindHashEntry(zOrderRevMap, (char*) zOrder, &isNew);
if (!isNew) {
return Tcl_GetHashValue(hPtr);
}
/* make a handle! */
Tcl_Obj *handle = Tcl_ObjPrintf("zOrder%ld", (long) zOrder);
Tcl_SetHashValue(hPtr, handle);
Tcl_IncrRefCount(handle);
hPtr = Tcl_CreateHashEntry(zOrderMap, (char*) handle, &isNew);
Tcl_SetHashValue(hPtr, zOrder);
return handle;
}
static int
GetZOrderFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr, int **zOrderPtr) {
Tcl_HashTable *hPtr;
if (!zOrderMap || (hPtr = Tcl_FindHashEntry(zOrderMap, (char *) objPtr)) == NULL) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf("no such zOrder \"%s\"",
Tcl_GetString(objPtr)));
return TCL_ERROR;
}
*zOrderPtr = (int *) Tcl_GetHashValue(hPtr);
return TCL_OK;
}
}
With that helper code in place, you can then define a custom Critcl type like this:
critcl::argtype zOrder {
if (GetZOrderFromObj(interp, ##, #A) != TCL_OK) {
return TCL_ERROR;
}
} int*
critcl::resulttype zOrder {
if (rv == NULL) {
return TCL_ERROR;
}
Tcl_SetObjResult(interp, MakeZOrderObj(rv));
return TCL_OK;
} int*
That then lets you write your real code as something like this. Note that grid is defined as being of (custom) type zOrder, and that those can only be manufactured by some code that returns a zOrder as its result.
critcl::cproc setter {zOrder grid int value int x int y} void {
grid[xy2addr(x,y)] = value;
}
(The deletion function that removes the entries from the hash tables and deletes the C array is left as an exercise.)
Tcl List Variable
The other way of doing this is to make zOrder values be held in Tcl variables as lists of integers. This can be nice because it lets you look inside easily, but it can also be not so nice in other ways, as the code is not constrained to work with proper values and you expose your cprocs to more details of what's happening in Tcl.
critcl::cproc setter {Tcl_Interp* interp object varName int value int x int y} ok {
/* Unpack the list of ints from the variable */
Tcl_Obj *listObj = Tcl_ObjGetVar2(interp, varName, NULL, TCL_LEAVE_ERR_MSG);
if (listObj == NULL)
return TCL_ERROR;
Tcl_Obj **listv; int listc;
if (Tcl_ListObjGetElements(interp, listObj, &listc, &listv) != TCL_OK)
return TCL_ERROR;
int *grid = alloca(sizeof(int) * listc);
for (int i=0; i<listc; i++)
if (Tcl_GetIntFromObj(interp, listv[i], &grid[i]) != TCL_OK)
return TCL_ERROR;
/* The core of the functionality */
grid[xy2addr(x,y)] = value;
/* Repack the list of ints from the variable; this code could be optimized in this case! */
for (int i=0; i<listc; i++)
listv[i] = Tcl_NewIntObj(grid[i]);
listObj = Tcl_NewListObj(listc, listv);
Tcl_ObjSetVar2(interp, varName, NULL, listObj, 0);
return TCL_OK;
}

Reference to class method

I would like to pass to a function a reference to a class method.
For example:
#include <functional>
struct Foo
{
int f(const int& val) const
{
return val+2;
}
};
int caller(const std::function<int(const int&)>& f)
{
return f(1);
}
int main()
{
caller([](const int& val){return val+2;}); // OK
Foo foo;
caller(foo.f); // WRONG
return 0;
}
How can I fix the second call of caller() (NB: Foo:f() is not static)?
In your case, function f doesn't use any member of Foo so it can be declared static
static int f(const int& val)
and passed as:
caller(&Foo::f);
But suppose that f cannot be declared static and you want to pass "reference" to member function of particular object.
You can use lambda in that case:
Foo foo;
caller(
[&foo](const int& val){
return foo.f(val);
}
);
foo object is captured in square brackets (in this case by reference) so that you can call f member function on that particular object.
Although it is not part of your question, I should add that it is not really useful to pass int by const reference, as you will not gain any performance improvement that way. Actually, your code will run slower than if you pass int by value.

stl remove_if with class member function result

I have a object container, list; and class Foo have a member function id() return an integer identifier.
Now I want to use stl algorithm remove_if to remove some objects whose id is less than a value.
I don't want to provide a function for id compare, If it is possible for me to write one line code with STL but boost to implement it.
class Foo{
public:
unsigned id() const {return id_;}
...
private:
unsigned id_
...
};
list<Foo> foo_list;
std::remove_if(foo_list.begin(), foo_list.end(), ???);
If STL can do this with only std::bind2nd, stl::less(), std::mem_fun_ref() or other stl functions.
Yes, that is possible to achieve without lambdas, if you agree to change the interface of Foo a little bit.
class Foo
{
public:
Foo(unsigned id)
: id_(id) {}
bool is_equal(unsigned id) const
{ return id_ == id; }
private:
unsigned id_;
};
typedef list<Foo> FooList;
FooList foo_list;
foo_list.push_back(Foo(1));
foo_list.push_back(Foo(2));
unsigned to_remove = 1;
foo_list.remove_if(std::bind2nd(std::mem_fun_ref(&Foo::is_equal), to_remove));

Custom STL Containers

I have written code that allows one to traverse mapped data in the order it was entered.
The solution I coded a couple of times was:
Given a keytype, K, and and data type, D,
std::map
std::vector
When one wanted to randomly find a data entry, use map.find(K). When one wanted to traverse the map in entry order, use std::vector::iterator (begin(), end()].
This was fine, but as an exercise, I wanted to write this 'OrderedMap' as an STL compliant container. I also have (stripped down to this discussion):
template <typename K, typename D>
class OrderedMapValue
{
private:
K first_ref;
std::map<K,size_t>& m;
std::vector<D>& v;
public:
const K& first
D& second
assignment operator=(const D& data)
{
std::map<K,size_t>::const_iterator iter = m.find(first_ref);
v[iter.second] = data; // error checking of iter stripped
}
};
Further assuming
template <typename K, typename D>
class OrderedMap
{
public:
typename OrderedMapValue<K,D>& OrderedMap<K,D>::operator[](const K&);
// snip...
};
class MyClass
{
public:
MyClass(std::string s) : _my_data(s) {}
private:
std::string _my_data;
};
The following code works:
OrderedMap<std::string,MyClass*> omap;
omap["MyKey"] = new MyClass("dummy");
However, this code does not:
OrderedMap::iterator iter = omap.find("MyKey");
MyClass * obj = iter->second;
delete obj;
iter->second = new MyClass("dummy");
Assuming I have done something
a) Structurally silly or
b) Unnecessarily complex, how should this be done?
I realize that I'm likely reinventing the wheel here, but again, this effort is mainly to increase my knowledge of STL containers, their design patterns and proper use.
Thanks in advance for any insights,
I don't have a compiler right now to test this, so there could be errors, but I think you want it more like:
template <typename K, typename D>
class OrderedMap
{
private:
std::map<K,size_t> &m;
std::vector<D> &v;
public:
typename pair<K,D> TYPE;
TYPE& operator[](const K &k)
{
return v[ m[ k ]];
}
TYPE& operator[](size_t idx)
{
return v[ idx ];
}
pair<iterator,bool> insert( const TYPE& pair )
{
map<K, size_t>::const_iterator iter;
iter = m.find( pair.first );
if( iter != m.end() )
return make_pair( v[ iter.second], false );
m.insert( make_pair( pair->first, v.size() ));
v.push_back( pair->second );
return make_pair( v.last() , inserted );
}
iterator &begin()
{
return v.begin();
}
// etc
};
In OrderedMapValue::operator=, you have:
std::map<K,size_t>::const_iterator iter = m.find(first_ref);
What is first_ref? The code doesn't reference it (no pun intended) elsewhere. It looks to me like it might be a vestige from an older implementation, replaced elsewhere by the public member
const K& first.
Could this be the problem?
EDIT from the comments: The code doesn't show that first_ref is initialized anywhere; so for all I can tell, the call to m.find(first_ref) is searching for an empty string, rather than the key for the OrderedMapValue.