Problems with passing different data types - c++

I am working on my own graph project in C++ at the moment and I have come along a problem which I'm sure it's easy to solve but I can't seem to get it right. I am building a template graph class with a vertex class declared inside of it as such:
template <typename T>
class graph{
public:
class vertex{
public:
bool visited; //used for paths. True if vertex has been visited
//vertex constructor
vertex(const T& d = T{}, int i = 0): data(d), visited(false), id(i){
std::cout << "Just created a vertex using its constructor :)\n";}
//vertex move constructor
vertex(T&& d, int i = 0): data(std::move(d)), visited(false), id(i){}
//returns vertex ID
int returnID() const{ return id; };
//returns data in vertex
T& operator*(){ return retrieve(); }
//returns const reference to data in vertex
const T& operator*() const{ return retrieve(); }
//returns list of adjacent vertices
std::list<vertex>& getList() const{ return adjacent; }
//adds vertex to current vertex's adjacency list
void addToList(const vertex& add){
if(!isAdjacent(add))
adjacent.push_back(add);
}
//returns true if vertices are adjacent
bool isAdjacent(const vertex& add){
return (find(begin(adjacent), end(adjacent), add) == adjacent.end());
}
//overloaded equal operator for vertex class
bool operator==(const vertex& add){
if(data == *add && id == add.returnID()) return true;
return false;
}
private:
T data; //vertex stores data of any type
std::list<vertex> adjacent; //list of adjacent vertices
int id;
T& retrieve() const{ return data; }
];
];
I keep getting this error:
g++ -std=c++11 -Wno-reorder -Wall -pedantic -o executable.x main.cpp
In file included from main.cpp:2:0:
graph.h: In instantiation of ‘T& graph<T>::vertex::retrieve() const [with T = int]’:
graph.h:70:47: required from ‘const T& graph<T>::vertex::operator*() const [with T = int]’
graph.h:84:17: required from ‘bool graph<T>::vertex::operator==(const graph<T>::vertex&) [with T = int]’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.4/include/g++-v4/bits/stl_algo.h:139:46: required from ‘_InputIterator std::__find(_InputIterator, _InputIterator, const _Tp&, std::input_iterator_tag) [with _InputIterator = std::_List_iterator<graph<int>::vertex>; _Tp = graph<int>::vertex]’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.4/include/g++-v4/bits/stl_algo.h:4441:45: required from ‘_IIter std::find(_IIter, _IIter, const _Tp&) [with _IIter = std::_List_iterator<graph<int>::vertex>; _Tp = graph<int>::vertex]’
graph.h:80:54: required from ‘bool graph<T>::vertex::isAdjacent(const graph<T>::vertex&) [with T = int]’
graph.h:75:24: required from ‘void graph<T>::vertex::addToList(const graph<T>::vertex&) [with T = int]’
graph.hpp:25:4: required from ‘bool graph<T>::addEdge(graph<T>::vertex&, graph<T>::vertex&) [with T = int]’
main.cpp:12:18: required from here
graph.h:92:31: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’
T& retrieve() const{ return data; }
^
graph.h: In member function ‘T& graph<T>::vertex::retrieve() const [with T = int]’:
graph.h:92:37: warning: control reaches end of non-void function [-Wreturn-type]
T& retrieve() const{ return data; }
And to sum up the problem it seems to have an issue with my private T& retrieve() function. It keeps saying invalid initialization of type 'int&' from expression with type 'const int' referring to the data it is returning, which is private member data of type T (instantiated in main as an int). Any help would be greatly appreciated! Thanks

T data;
...
T& retrieve() const{ return data; }
The const modifier makes this method a const method. Which means that, essentially, its this is a pointer to a const class instance. Since data was not declared with a mutable modifier, data is a const value, and your compiler is complaining because it can't return a reference to a mutable value, because data is a constant value.
Either change the method to:
const T& retrieve() const{ return data; }
Or, I don't see why a reference here is needed, just:
T retrieve() const{ return data; }
P.S. You should try to make sense of these compiler errors, before giving up so quickly. It's true that C++ compilation errors are legendary for their typical obtuseness, but in this case you should be able to figure out what the compiler is telling you, after staring at those error messages, for a few minutes.

Related

Overloaded template operator calling separate class operator

I've got a template class containing a priority queue of other classes, I need to use the priority overloader to call the individual class overloaders to compare based on the individual classes preferences (in this case it's age, in another class it could be price.
I've got absolutely no doubt that I've implemented the operator overloading incorrect so would appreciate the advice.
For example
#include <iostream>
#include <queue>
#include <string>
using namespace std;
class Animal {
public:
Animal();
Animal(string t, int a);
int get_age()const;
bool operator< ( Animal& b) const;
void display()const;
private:
string type;
double age;
};
void Animal::display() const
{
cout << "Type: " << type << " Age: " << age;
}
int Animal::get_age() const
{
return age;
}
Animal::Animal(){}
Animal::Animal(string t, int a)
{
type = t;
age = a;
}
bool Animal::operator< ( Animal& b) const
{
return b.get_age();
}
template<typename T>
class Collection {
public:
Collection();
Collection(string n, string d);
void add_item(const T& c);
private:
priority_queue <T> pets;
string name; // Name of the collection
string description; // Descriptions of the collection
};
template<typename T>
Collection<T>::Collection(){}
template<typename T>
Collection<T>::Collection(string n, string d)
{
name = n;
description = d;
}
template<typename T>
bool operator<(const T& one, const T& two)
{
return one.operator<(two);
}
template<typename T>
void Collection<T>::add_item(const T& c)
{
pets.push(c);
}
int main(){
Animal p1("Dog", 10);
Animal p2("Cat", 5);
Animal p3("Turtle", 24);
Collection<Animal> P("Pets", "My Pets");
P.add_item(p1);
P.add_item(p2);
P.add_item(p3);
cout << endl;
return 0;
}
I get this error and I'm not sure what I need to do to fix it. I've got to keep the class overloader as the single variable (Animal& b).
task.cpp: In instantiation of 'bool operator<(const T&, const T&)
[with T = Animal]':
c:\mingw-4.7.1\bin../lib/gcc/mingw32/4.7.1/include/c++/bits/stl_function.h:237:22:
required from 'bool std::less<_Tp>::operator()(const _Tp&, const _Tp&)
const [with _Tp = Animal]'
c:\mingw-4.7.1\bin../lib/gcc/mingw32/4.7.1/include/c++/bits/stl_heap.h:310:4: required from 'void std::__adjust_heap(_RandomAccessIterator,
_Distance, _Distance, _Tp, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator > >; _Distance = int; _Tp = Animal; _Compare =
std::less]'
c:\mingw-4.7.1\bin../lib/gcc/mingw32/4.7.1/include/c++/bits/stl_heap.h:442:4: required from 'void std::make_heap(_RandomAccessIterator,
_RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator > >; _Compare = std::less]'
c:\mingw-4.7.1\bin../lib/gcc/mingw32/4.7.1/include/c++/bits/stl_queue.h:393:9: required from 'std::priority_queue<_Tp, _Sequence,
_Compare>::priority_queue(const _Compare&, const _Sequence&) [with _Tp = Animal; _Sequence = std::vector >; _Compare = std::less]' task.cpp:57:45: required from 'Collection::Collection(std::string, std::string) [with T = Animal;
std::string = std::basic_string]' task.cpp:79:43: required
from here task.cpp:66:30: error: no matching function for call to
'Animal::operator<(const Animal&) const' task.cpp:66:30: note:
candidate is: task.cpp:36:6: note: bool Animal::operator<(Animal&)
const task.cpp:36:6: note: no known conversion for argument 1 from
'const Animal' to 'Animal&' task.cpp: In function 'bool
operator<(const T&, const T&) [with T = Animal]':
Your comparison
bool Animal::operator< ( Animal& b) const
{
return b.get_age(); // returns true always unless age == 0
}
is no comparison and it should take a const parameter. You should have something like
bool Animal::operator< (const Animal& b) const
// ^----------------------- const !
{
return get_age() < b.get_age();
}
Btw you dont need to use a member operator< for the priority queue. Especially if you want to sort objects in different ways I would recommend to not use it, but pass a lambda to the priority_queue. See eg here for an example.
Both of your overloads of < are problematic
bool Animal::operator< ( Animal& b) const
the Animal should also be const. You also need to compare both parameters, otherwise things (such as your priority_queue) that expect < to provide an ordering will have undefined behaviour.
You don't use anything non-public from Animal, so I suggest you change it to
bool operator< (const Animal & lhs, const Animal & rhs)
{ return lhs.get_age() < rhs.get_age(); }
This has the benefit of treating both sides identically, rather than one being implicit.
template<typename T>
bool operator<(const T& one, const T& two)
{
return one.operator<(two);
}
This template matches all types and is entirely superfluous. a < b can call either a member or a free operator <. Just delete this template.

std vector no match for operator ==

I'm stuck at this error:
gcc.compile.c++
Physics/HelicityAmplitude/bin/gcc-4.8.3/debug/HelicityDecayTree.o In
file included from
/cvmfs/cluster/gcc/gcc-4.8.3/include/c++/4.8.3/algorithm:62:0,
from /cluster/compwa_externals/boost_1_55_0/include/boost/move/algorithm.hpp:23,
from /cluster/compwa_externals/boost_1_55_0/include/boost/move/move.hpp:24,
from /cluster/compwa_externals/boost_1_55_0/include/boost/unordered/detail/util.hpp:19,
from /cluster/compwa_externals/boost_1_55_0/include/boost/unordered/detail/buckets.hpp:14,
from /cluster/compwa_externals/boost_1_55_0/include/boost/unordered/detail/table.hpp:10,
from /cluster/compwa_externals/boost_1_55_0/include/boost/unordered/detail/equivalent.hpp:14,
from /cluster/compwa_externals/boost_1_55_0/include/boost/unordered/unordered_set.hpp:17,
from /cluster/compwa_externals/boost_1_55_0/include/boost/unordered_set.hpp:16,
from /cluster/compwa_externals/boost_1_55_0/include/boost/graph/adjacency_list.hpp:21,
from Physics/HelicityAmplitude/HelicityDecayTree.hpp:17,
from Physics/HelicityAmplitude/HelicityDecayTree.cpp:12:
/cvmfs/cluster/gcc/gcc-4.8.3/include/c++/4.8.3/bits/stl_algo.h: In
instantiation of ‘_RandomAccessIterator
std::__find(_RandomAccessIterator, _RandomAccessIterator, const _Tp&,
std::random_access_iterator_tag) [with _RandomAccessIterator =
__gnu_cxx::__normal_iterator >; _Tp =
HelicityFormalism::ParticleState]’:
/cvmfs/cluster/gcc/gcc-4.8.3/include/c++/4.8.3/bits/stl_algo.h:4441:45:
required from ‘_IIter std::find(_IIter, _IIter, const _Tp&) [with
_IIter = __gnu_cxx::__normal_iterato r >; _Tp =
HelicityFormalism::ParticleState]’
Physics/HelicityAmplitude/HelicityDecayTree.cpp:59:61: required from
here
/cvmfs/cluster/gcc/gcc-4.8.3/include/c++/4.8.3/bits/stl_algo.h:166:17:
error: no match for ‘operator==’ (operand types are
‘HelicityFormalism::ParticleState’ and ‘const Helicit
yFormalism::ParticleState’)
if (*__first == __val)
I see that he is asking for a const to non-const comparison of ParticleState. However I don't really understand why he is asking for this comparison. My relevant code is the following:
The header for the class:
class HelicityDecayTree {
boost::adjacency_list<> decay_tree_;
std::vector<ParticleState> particles_;
public:
void createDecay(const ParticleState &mother,
const ParticleStatePair &daughters);
}
And the source for that member function:
void HelicityDecayTree::createDecay(const ParticleState &mother,
const ParticleStatePair &daughters) {
// add particles to the list
unsigned int mother_vector_index;
unsigned int daughter1_vector_index;
unsigned int daughter2_vector_index;
if (std::find(particles_.begin(), particles_.end(), mother)
== particles_.end()) {
mother_vector_index = particles_.size();
particles_.push_back(mother);
}
else {
mother_vector_index = std::distance(particles_.begin(),
std::find(particles_.begin(), particles_.end(), mother));
}
if (std::find(particles_.begin(), particles_.end(), daughters.first)
== particles_.end()) {
daughter1_vector_index = particles_.size();
particles_.push_back(daughters.first);
}
else {
daughter1_vector_index = std::distance(particles_.begin(),
std::find(particles_.begin(), particles_.end(), daughters.first));
}
if (std::find(particles_.begin(), particles_.end(), daughters.second)
== particles_.end()) {
daughter2_vector_index = particles_.size();
particles_.push_back(daughters.second);
}
else {
daughter2_vector_index = std::distance(particles_.begin(),
std::find(particles_.begin(), particles_.end(), daughters.second));
}
// then make the correct inserts into the vector and link appropriately
boost::add_edge(mother_vector_index, daughter1_vector_index, decay_tree_);
boost::add_edge(mother_vector_index, daughter2_vector_index, decay_tree_);
}
And the ParticleState struct:
struct ParticleState {
int particle_id_;
std::string name_;
Spin J_;
Spin M_;
};
Afaiu he should be synthesizing the operator== for two const ParticleStates, but for some reason the find method is asking for a non-const version for 1 argument...
Thx in advance,
Steve
Ok I forgot that the compiler will not synthesize the operator==. So I was just missing
bool operator==(const ParticleState &rhs) const {
...
}

Using boost fibonacci_heap

Using fibonacci_heap results in a compilation error:
struct Less: public binary_function<Node*, Node*, bool>
{
bool operator()(const Node*& __x, Node*& __y) const
{ return __x->time < __y->time; }
};
boost::fibonacci_heap<Node*, Less >* m_heap;
then
Less* ls = new Less;
m_heap = new boost::fibonacci_heap<Node*, Less >(1000, (*ls));
Any attempt to run m_heap->push(n) results in
no match for call to ‘(TimeSync::Less) (TimeSync::Node* const&, TimeSync::Node*&)’
UnmanagedUtils/Trading/Simulation/TimeSync.h:50: note: candidates are: bool TimeSync::Less::operator()(const TimeSync::Node*&, TimeSync::Node*&) const
/usr/local/include/boost-1_35/boost/property_map.hpp: In function ‘Reference boost::get(const boost::put_get_helper<Reference, PropertyMap>&, const K&) [with PropertyMap = boost::identity_property_map, Reference = unsigned int, K = TimeSync::Node*]’:
Change the signature to operator()(Node * const &, Node * const &) const.

How to sort a std::set with const getters

I have a std::set container whose elements are objects of the following class:
class LaneConnector {
public:
const Lane* getLaneFrom() const {
return From;
}
const Lane* getLaneTo() const {
return To;
}
private:
Lane* From;
Lane* To;
}
and my comparator function is as follows:
struct MyLaneConectorSorter {
bool operator() (LaneConnector * c, LaneConnector * d)
{
Lane* a = const_cast<Lane*>(c->getLaneFrom());
Lane* b = const_cast<Lane*>(d->getLaneFrom());
return (a->getLaneID() < b->getLaneID());
}
} myLaneConnectorSorter;
Now when I try to sort the elements in the set with:
//dont panic, the container just came through a const_iterator of a std::map :)
const std::set<LaneConnector*> & tempLC = (*it_cnn).second;
std::sort(tempLC.begin(), tempLC.end(), myLaneConnectorSorter);
I get a frenzy of errors starting with the following lines, Appreciate if you help me solve this problem.
Thanks:
/usr/include/c++/4.6/bits/stl_algo.h: In function ‘void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::_Rb_tree_const_iterator<LaneConnector*>, _Compare = {anonymous}::MyLaneConectorSorter]’:
/home/.../dev/Basic/shared/conf/simpleconf.cpp:1104:65: instantiated from here
/usr/include/c++/4.6/bits/stl_algo.h:5368:4: error: no match for ‘operator-’ in ‘__last - __first’
/usr/include/c++/4.6/bits/stl_algo.h:5368:4: note: candidates are:
/usr/include/c++/4.6/bits/stl_iterator.h:321:5: note: template<class _Iterator> typename std::reverse_iterator::difference_type std::operator-(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)
/usr/include/c++/4.6/bits/stl_iterator.h:378:5: note: template<class _IteratorL, class _IteratorR> typename std::reverse_iterator<_IteratorL>::difference_type std::operator-(const std::reverse_iterator<_IteratorL>&, const std::reverse_iterator<_IteratorR>&)
/usr/include/c++/4.6/bits/stl_bvector.h:181:3: note: std::ptrdiff_t std::operator-(const std::_Bit_iterator_base&, const std::_Bit_iterator_base&)
/usr/include/c++/4.6/bits/stl_bvector.h:181:3: note: no known conversion for argument 1 from ‘std::_Rb_tree_const_iterator<LaneConnector*>’ to ‘const std::_Bit_iterator_base&’
First, you cannot sort an std::set. It is a sorted structure, sorting happens upon construction or insertion.
Second, you can construct an std::set with your own sorting functor, and you can avoid unnecessary const_casts by making it take const pointers:
struct MyLaneConectorSorter {
bool operator() (const LaneConnector* lhs, const LaneConnector* rhs) const
{
// you may want to put some null pointer checks in here
const Lane* a = lhs->getLaneFrom();
const Lane* b = rhs->getLaneFrom();
return a->getLaneID() < b->getLaneID();
}
};
and instantiate the set like this:
std::set<LaneConnector*, MyLaneConectorSorter> s(MyLaneConectorSorter());
or, if you want to construct it from a different set, with a different ordering,
std::set<LaneConnector*> orig = ..... ;
....
std::set<LaneConnector*, MyLaneConectorSorter> s(orig.begin(), orig.end(), MyLaneConectorSorter());

object in a set iterator

I can get a method of a class in a set iterator ?
#include <iostream>
#include <string>
#include <set>
class student{
public:
student(std::string n){
name=n;
}
void print(){
std::cout << name << std::endl;
}
bool operator < (const student & s1){ return true;}
bool operator = (const student & s1){ return true;}
private:
std::string name;
};
int main(){
std::set<student> studs;
studs.insert(student("name01"));
studs.insert(student("name02"));
std::set<student>::iterator it;
for(it = studs.begin(); it != studs.end(); it++)
(*it).print() ;
}
I get this error
students.cpp: In function ‘int main()’:
students.cpp:22: error: passing ‘const student’ as ‘this’ argument of ‘void student::print()’ discards qualifiers
/usr/include/c++/4.2.1/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = student]’:
/usr/include/c++/4.2.1/bits/stl_tree.h:982: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = student, _Val = student, _KeyOfValue = std::_Identity<student>, _Compare = std::less<student>, _Alloc = std::allocator<student>]’
/usr/include/c++/4.2.1/bits/stl_set.h:307: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename _Alloc::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(const _Key&) [with _Key = student, _Compare = std::less<student>, _Alloc = std::allocator<student>]’
students.cpp:18: instantiated from here
/usr/include/c++/4.2.1/bits/stl_function.h:227: error: passing ‘const student’ as ‘this’ argument of ‘bool student::operator<(const student&)’ discards qualifiers
with
bool operator<(const student & s1) const { return true;}
bool operator==(const student & s1) const { return true;}
now work!! O_o',
#include <iostream>
#include <string>
#include <set>
class student{
public:
student(std::string n){
name=n;
}
void print() const {
std::cout << name << std::endl;
}
bool operator<(const student & s1) const { return true;}
bool operator==(const student & s1) const { return true;}
private:
std::string name;
};
int main(){
std::set<student> studs;
studs.insert(student("name01"));
studs.insert(student("name02"));
std::set<student>::iterator it;
for(it = studs.begin(); it != studs.end(); it++)
it->print() ;
}
You need to add a const qualifer to your print member function:
void print() const
{
std::cout << name << std::endl;
}
Objects in an std::set are necessarily const, since they are used as keys. When an object (or reference) is constant, you can only call member functions of that object which are declared with the const qualifier.
You also want const qualifiers on both the == and < operator overload functions. (And don't forget to change = to == as pointed out in the comments.)
Yes, though it->print() is more intuitive.
A naive world-view is that iterators are a bit like pointers. There is more to it than that, as explained here.
The most obvious form of iterator is a
pointer: A pointer can point to
elements in an array, and can iterate
through them using the increment
operator (++). But other forms of
iterators exist. For example, each
container type (such as a vector) has
a specific iterator type designed to
iterate through its elements in an
efficient way.
You want operator==, not operator=.
Your operator< definition violates the requirements of std::set, and is inconsistent with your operator<. That is, according to your operator<, nothing is equivalent, but according to your operator==, everything is equal. Operator< should define a irreflexive, transitive, and asymmetric (for non-equivalent values) relation.
Objects in a set are necessarily const, and so to call a function on such an object that function must be declared with the const qualifier. Specifically, print() should be declared void print() const.
Similarly, operator< should be declared with the const qualifier. std::set requires that operator< can be called with const objects. Another valid option would be to make operator< a non-member function and to take both objects by value (bad) or const reference (good).
While not required in your example, operator== should also be declared with the const qualifier.
Write your print() function like this:
void print() const //<---- note this 'const'
{
std::cout << name << std::endl;
}
Now your code should work now. :-)
By the way, such functions with const keyword appearing on the right side, are called const member function, as they cannot change any member-data of the class.
See this FAQ: [18.10] What is a "const member function"?
#include <iostream>
#include <set>
using namespace std;
class Boxer{
public:
string name;
int strength;
};
struct Comp{
bool operator()(const Boxer& a, const Boxer& b){
return a.strength > b.strength;
}
};
int main(){
Boxer boxer[3];
boxer[0].name="uday", boxer[0].strength=23;
boxer[1].name="manoj", boxer[1].strength=33;
boxer[2].name="rajiv", boxer[2].strength=13;
set< Boxer, Comp> s;
s.insert(boxer[0]);
s.insert(boxer[1]);
s.insert(boxer[2]);
set< Boxer, Comp>::iterator it = s.begin();
Boxer b = *it;
cout<<b.name;
//result is Manoj
return 0;
}