Vector of maps with custom comparator - c++

I am trying to create a vector of maps. Each map has a different comparator.
Here is what I have tried:-
#include<iostream>
#include<map>
#include<vector>
template <class T>
struct head {
virtual bool operator() (const T& x, const T& y) const = 0;
};
template <class T>
struct greater: head<T> {
bool operator() (const T& x, const T& y) const {return x>y;}
};
template <class T>
struct less: head<T> {
bool operator() (const T& x, const T& y) const {return x<y;}
};
int main()
{
std::vector<std::map<int, int, head<int>>> mp;
return 0;
}
But I am getting an error that my operator() is pure virtual in head.
Please tell me what is the correct way to achieve this?

You need a single comparator type that works for all your vectors. Like this:
template<typename T>
struct comp {
comp(bool gt) : do_greater(gt) {}
bool operator() (const T& x, const T& y) const
{
return do_greater ? x > y : x < y;
}
bool do_greater;
};
int main()
{
std::vector<std::map<int, int, comp<int>>> mp;
mp.emplace_back(false); // first map uses less-than
mp.emplace_back(true); // first map uses greater-than
}
That is, the choice of comparison function needs to be driven by the state initialized in each std::map constructor. That single ?: branch is probably better for performance than calling a virtual method every time, too.

Related

Defining hash function as part of a struct

I know that it's possible to define a hash function for a struct X by defining a separate hash function struct:
struct hash_X {
size_t operator()(const X &x) const {}
bool operator()(const X &a, const X &b) const {}
};
int main() {
unordered_set<X, hash_X, hash_X> s;
}
But I'm looking for something like operator<, which can be attached to struct X itself, e.g. with set:
struct X {
bool operator<(const X &other) const {}
};
int main() {
set<X> s;
}
The end goal is something like:
struct X {
size_t operator()(void) const {}
bool operator()(const X &other) const {}
};
int main() {
unordered_set<X> s;
}
Is this possible in C++?
std::unordered_set is defined within std namespace. And it uses std::hash structures to hash many different types. If you want to be able to use std::unordered_set<X> (without adding much info to the declaration), you must create another overload of the std::hash template, so as to make it hash your structure.
You should be able to get it working by doing the following:
# include <unordered_set>
struct X {
size_t operator()(void) const {}
bool operator()(const X &other) const {}
};
namespace std {
template<>
struct hash<X> {
inline size_t operator()(const X& x) const {
// size_t value = your hash computations over x
return value;
}
};
}
int main() {
std::unordered_set<X> s;
}
Andalso, you must provide either an overload to std::equal_to, or a comparison operator (operator==()) for your structure. You should add one of the following:
struct X {
...
inline bool operator==(const X& other) const {
// bool comparison = result of comparing 'this' to 'other'
return comparison;
}
};
Or:
template <>
struct equal_to<X> {
inline bool operator()(const X& a, const X& b) const {
// bool comparison = result of comparing 'a' to 'b'
return comparison;
}
};
There is no hash operator, but you could hide the hash struct inside of your X:
struct X
{
std::string name;
struct hash
{
auto operator()( const X& x ) const
{ return std::hash< std::string >()( x.name ); }
};
};
You could even make it a friend and make name private, etc.
Live example
namespace hashing {
template<class T>
std::size_t hash(T const&t)->
std::result_of_t<std::hash<T>(T const&)>
{
return std::hash<T>{}(t);
}
struch hasher {
template<class T>
std::size_t operator()(T const&t)const{
return hash(t);
}
};
}
the above is some boilerplate that sets up an adl-based hash system.
template<class T>
using un_set=std::unordered_set<T,hashing::hasher>;
template<class K, class V>
using un_map=std::unordered_map<K,V,hashing::hasher>;
now creates two container aliases where you do not have to specify the hasher.
To add a new hashable:
struct Foo {
std::string s;
friend size_t hash(Foo const&f){
return hashing::hasher{}(s);
}
};
and Foo works in un_set and un_map.
I would add support for std containers and tuples into hashing namespace (override the function hash for them), and magically those will work too.
I'd recommend to consider a more general hash class. You could define for this class all the common hash manipulation operations that you could need:
struct ghash {
// all the values and operations you need here
};
Then in any class where you want to compute a hash, you could define a conversion operator
struct X {
operator ghash () { // conversion operator
ghash rh;
// compute the hash
return rh;
}
};
You can then easily calculate the hash:
X x;
ghash hx = x; // convert x to a hash
hx = (ghash)x; // or if you prefer to make it visible
This will make it easier to extend the use of your hash structure without reinventing the common ground for any other struct X, Y,Z that may need a hash in the future.
Live demo here

implementing a generic binary function with a class and functor as template parameters

I am trying to wrap some templated functions into some binary functors like below. When I try to compile the code I have the error
error: no match for call to ‘(QtyAsc) (myobj&, myobj&)
I thought that being operator() in QtyAsc a function in a class, the template deduction mechanism would have worked but it seems that the compiler doesn't accept myobj classes as valid types for it.
Is it maybe because of the call to boost::bind? I was trying to provide a default implementation for the second templated argument (unfortunately I cannot use C++11 with default templated arguments).
class myobj {
public:
myobj(int val) : qty_(val) {}
int qty() { return qty_;}
private:
int qty_;
};
template<class T>
int get_quantity(const T& o) {
throw runtime_error("get_quantity<T> not implemented");
}
template<>
int get_quantity(const myobj& o) {
return o.qty();
}
struct QtyAsc {
template<class T, class QEx >
bool operator()(const T& o1, const T& o2, QEx extr = boost::bind(&get_quantity<T>,_1)) const {
if(extr(o1) < extr(o2))
return true;
return false;
}
};
int main() {
myobj t1(10),t2(20);
QtyAsc asc;
if(asc(t1,t2))
cout << "Yes" << endl;
}
If you can't use C++11, just provide an additional overload:
struct QtyAsc {
template<class T, class QEx >
bool operator()(const T& o1, const T& o2, QEx extr) const {
return extr(o1) < extr(o2);
}
template<class T>
bool operator()(const T& o1, const T& o2) const {
return operator()(o1, o2, &get_quantity<T>);
}
};
(I've omitted the unnecessary boost::bind.) Also, you will need to declare myobj::qty to be const:
int qty() const {
return qty_;
}
since you want to invoke it on const objects. (Live demo)

How to 'partially' specialize member methods?

I have a class
template<class T, bool isOrdered>
class Vector
{
public:
int Find(const T& t); // Return its index if found.
// Many other methods.
};
There are two versions of Find depending on the true or false of isOrdered. There is no partial specialization for member methods (class T is not specialized). My question is to how to specialize them? Thanks.
Use overload on std::integral_constant:
template<class T, bool isOrdered>
struct Vector {
int find(const T& t) {
return find_impl(t, std::integral_constant<bool,isOrdered>());
}
int find_impl (const T& t, std::true_type) {return 1;}
int find_impl (const T& t, std::false_type) {return 2;}
};

Overloading class' operator [] in C++

I have a class which I have written its [] operator, and I want that sometimes the operator will return an int and sometimes a struct.
But the compiler won't let me overload the operator, why?
It says:"...cannot be overloaded"
Code:
template <class T> struct part
{ };
template <class T> class LinkedList
{
public:
LinkedList() : size(0), head(0) {}
T& operator[](const int &loc);
part<T>& operator[](const int &loc);
};
template <class T> T& LinkedList<T>::operator[](const int &loc)
{
..a lot of thing which compiles perfectly
}
template <class T> part<T>& LinkedList<T>::operator[](const int &loc)
{
...the same thing but returns struct&.
}
You can't overload a function based on the return type. You could have your operator return a variant of int and string, and let the user check which was actually returned, but its cumbersome. If the return type can be determined at compilation time, you can implement the operator overloads by mean of having different indices types. Something like this:
struct as_string
{
as_string( std::size_t index ) : _index( index ){}
std::size_t const _index;
};
...
int operator[]( int index ) const { ... };
std::string operator[]( as_string const& index ) const { ... };
And then the caller would invoke object[0] to get an int result, or object[as_string(0)] to get a string result.
The type of a function's output is not a part of the function's signature. Thus you can't use both int operator[](int index) and Foo operator[](int index).

Overload comparison operators for a templated class

I'm having troubles in overloading comparison operators in order to compare two pair struct in such way:
typedef pair<string, unsigned int> INDEX;
bool operator>(INDEX &v1, INDEX &v2)
{
if(v1.second == v2.second) //if integer parts are equal
{
//string that comes earlier in the dictionary should be larger
return v1.first < v2.first;
}
return v1.second > v2.second;
}
The actual comparison takes place at this->element(hole/2) < this->element(hole) inside fixUp(CBTNODE hole), a member function of BinaryHeap class, which is a derived class of CompleteBinaryTree. The T will be instantiated as type INDEX, which is typedefed as pair<string, unsigned int>.
In other words, the comparison between two pairs: ("a.txt", 42) > ("b.txt", 42) should return true.
I tried to overload operator> outside the class declaration in two different ways but neither of them worked:
bool operator>(INDEX &v1, INDEX &v2);
bool operator>(BinaryHeap<T> &v1, BinaryHeap<T> &v2);
Any help will be much appreciated!
Z.Zen
Here is the declarations:
typedef int CBTNODE;
template <typename T>
class CompleteBinaryTree {
public:
//Initializes an empty binary tree
CompleteBinaryTree(int initialSize = 10);
//Destructor
~CompleteBinaryTree();
//Returns the element of the CBT pointed to by node. Behavior is undefined
//if node does not exist.
T element(CBTNODE node);
protected:
T *data;
int numElts, maxElts;
};
typedef pair<string, unsigned int> INDEX;
template <typename T>
class BinaryHeap : public CompleteBinaryTree<T>
{
public:
//Maintain heap property with bottom up heapify method.
void fixUp(CBTNODE hole);
};
bool operator>(INDEX &v1, INDEX &v2);
Implementation:
template <typename T>
T CompleteBinaryTree<T>::element(CBTNODE node) {
assert(node >= 0);
assert(node < numElts);
return data[node];
}
template <typename T>
void BinaryHeap<T>::fixUp(CBTNODE hole)
{
T tmp = this->element(hole);
while( hole > 0 && this->element(hole/2) < tmp )
{
//do stuff
}
}
bool operator>(INDEX &v1, INDEX &v2)
{
if(v1.second == v2.second) //if two have same relevance
{
return v1.first < v2.first;
}
return v1.second > v2.second;
}
A temporary, such as the result of element func, cannot be bound to a reference to non-const, such as the formal arguments of your operator>.
Declare it thusly:
bool operator>( INDEX const& v1, INDEX const& v2 )
However, the implementation that you present doesn't seem to be correct for operator>.
And while I'm at it, what you want is really operator< instead, because that's the one required by standard algorithms. Perhaps combined with an operator== (because it's inefficient to synthesize it from operator<). With those two any relationship can be checked for relatively efficiently.
Btw., if you stop using ALL UPPERCASE names for anything else then macros (see the FAQ), then you can avoid inadvertent name collision with macros.
Cheers & hth.,
Don't typedef INDEX, be explicit:
template<class F, class S>
struct Index {
std::pair<F, S> Value;
Index(const std::pair<F, S>& pValue)
: Value(pValue) {}
};
template<class F, class S>
bool operator<(const Index<F, S>& pLeft, const Index<F, S>& pRight) {
// your implementation...
}