Modifying set elements - c++

With the below code, I am trying to update the values in a set but its not compiling when i try to compile .
It's giving me the error at the bottom, can you please help ?
What wrong I am doing here?
#include < iostream >
#include < set >
using namespace std;
class A
{
public:
int a,b;
bool operator()(A a1,A a2)
{
return true;
}
A(int a ,int b)
{
this.a=a;
this.b=b;
}
};
void print_set(const std::set<A>&st) const
{
std::set<A>::iterator it;
std::cout<<"\nvalues in set";
for(it=st.begin();it!=st.end();it++)
{
std::cout<<"\na="<<it->a<<"b="<<it->b;
}
}
int main ()
{
std::set<A> s;
for ( int i=0;i<5;i++)
{
s.insert(A(i,i+1));
}
print_set(s);
std::set<A>::iterator it;
for(it=s.begin();it!=s.end();it++)
{
A tmp=*it;
s.erase(it);
tmp.a=10;
tmp.b=20;
s.insert(tmp);
std::cout<<"\ninserting tmp "<<tmp.a<<" "<<tmp.b;
}
print_set(s);
return 0;
}
I am getting an error like this :
/usr/include/c++/4.6/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = A]’:
/usr/include/c++/4.6/bits/stl_tree.h:1277:4: instantiated from ‘std::pair<std::_Rb_tree_iterator<_Val>, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = A, _Val = A, _KeyOfValue = std::_Identity<A>, _Compare = std::less<A>, _Alloc = std::allocator<A>]’

A few issues in your code, see below comments:
A(int a ,int b)
{
//this.a=a;
//this.b=b;
this->a = a; // this pointer should be accessed by this->
this->b = b;
}
// to store element in std::set, it must follow strict weak ordering rule.
// by default, operator< need to be defined
bool operator<(const A& lhs, const A& rhs)
{
return lhs.a < rhs.a;
}
// print_set is not a member function, can't have trailing const after function name
void print_set(const std::set<A>&st) // const

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.

Error is generated with the sort method while sorting the values inside a vector

When we are compiling the below code using g++ in debian machine, then following errors are generated...can anyone pls help me why the error are? I tried by commenting sort line then error dissappears however our task requires sorting to be done then what can be the possible solution
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Here is a simple struct
struct MyStruct
{
int Num;
// Define the operator <
bool operator <(const MyStruct& Rhs)
{
return (Num < Rhs.Num);
}
};
int main()
{
vector<MyStruct> MyVector;
// Let the size be 5.
MyVector.resize(5);
// Push 5 instances of MyStruct with Num ranging
// from 5 to 1
MyStruct TestStruct;
int i = 0;
for (i = 0; i < 5; ++i)
{
TestStruct.Num = 5 - i;
MyVector[i] = TestStruct;
}
// Now sort the vector
sort(MyVector.begin(), MyVector.end());
// Try to display Num for each element. It is sorted
for (i = 0; i < 5; ++i)
{
cout << MyVector[i].Num << '\n';
}
return 0;
}
Output:
In file included from /usr/include/c++/4.7/algorithm:63:0,
from testvect.cpp:3: /usr/include/c++/4.7/bits/stl_algo.h: In instantiation of
‘_RandomAccessIterator
std::__unguarded_partition(_RandomAccessIterator,
_RandomAccessIterator, const _Tp&) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator >; _Tp = MyStruct]’: /usr/include/c++/4.7/bits/stl_algo.h:2309:70: required
from ‘_RandomAccessIterator
std::__unguarded_partition_pivot(_RandomAccessIterator,
_RandomAccessIterator) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator >]’ /usr/include/c++/4.7/bits/stl_algo.h:2340:54: required from ‘void
std::__introsort_loop(_RandomAccessIterator, _RandomAccessIterator,
_Size) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator >; _Size = int]’ /usr/include/c++/4.7/bits/stl_algo.h:5476:4: required from ‘void std::sort(_RAIter, _RAIter) [with _RAIter =
__gnu_cxx::__normal_iterator >]’ testvect.cpp:33:41: required from here
/usr/include/c++/4.7/bits/stl_algo.h:2271:4: error: passing ‘const
MyStruct’ as ‘this’ argument of ‘bool MyStruct::operator<(const
MyStruct&)’ discards qualifiers [-fpermissive]
You use quite dated compiler where stl used const& parameters, in more modern versions those are passed by rvalue references and does not require const operator<, so to fix it:
Change:
bool operator <(const MyStruct& Rhs)
to
bool operator <(const MyStruct& Rhs) const
^^^^^
Alternately, use a later version of the compiler which supports more modern versions of C++ and then enable the more modern versions with '-std=c++11' or '-std=c++14'.
Corrected Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Here is a simple struct
struct MyStruct
{
int Num;
// Define the operator <
bool operator <(const MyStruct& Rhs)const
{
return (Num < Rhs.Num);
}
};
int main()
{
vector<MyStruct> MyVector;
// Let the size be 5.
MyVector.resize(5);
// Push 5 instances of MyStruct with Num ranging
// from 5 to 1
MyStruct TestStruct;
int i = 0;
for (i = 0; i < 5; ++i)
{
TestStruct.Num = 5 - i;
MyVector[i] = TestStruct;
}
// Now sort the vector
sort(MyVector.begin(), MyVector.end());
// Try to display Num for each element. It is sorted
for (i = 0; i < 5; ++i)
{
cout << MyVector[i].Num << '\n';
}
return 0;

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 {
...
}

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;
}

Errors when using map() in C++

I wrote a piece of code and used map and vector but it shows me something I can't get. I'll be thankful if someone help me in this way and correct my code or give me some hints.
The code is:
// For each node in N, calculate the reachability, i.e., the
// number of nodes in N2 which are not yet covered by at
// least one node in the MPR set, and which are reachable
// through this 1-hop neighbor
std::map<int, std::vector<const NeighborTuple *> > reachability;
std::set<int> rs;
for (NeighborSet::iterator it = N.begin(); it != N.end(); it++)
{
NeighborTuple const &nb_tuple = *it;
int r = 0;
for (TwoHopNeighborSet::iterator it2 = N2.begin (); it2 != N2.end (); it2++)
{
TwoHopNeighborTuple const &nb2hop_tuple = *it2;
if (nb_tuple.neighborMainAddr == nb2hop_tuple.neighborMainAddr)
r++;
}
rs.insert (r);
reachability[r].push_back (&nb_tuple);
}
/*******************************************************************************/
//for keepping exposition of a node
std::map<Vector, std::vector<const NeighborTuple *> > position;
std::set<Vector> pos;
for (NeighborSet::iterator it = N.begin(); it != N.end(); it++)
{
NeighborTuple nb_tuple = *it;
Vector exposition;
pos.insert (exposition);
position[exposition].push_back (&nb_tuple);
}
and the errors are for this line: position[exposition].push_back (&nb_tuple);
and the errors are:
/usr/include/c++/4.1.2/bits/stl_function.h: In member function ‘bool std::less<_
Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = ns3::Vector3D]’:
/usr/include/c++/4.1.2/bits/stl_map.h:347: instantiated from ‘_Tp& std::map<_K
ey, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = ns3::Vector3D, _Tp = std::vector<const ns3::olsr::NeighborTuple*, std::allocator<const ns3::olsr::NeighborTuple*> >, _Compare = std::less<ns3::Vector3D>, _Alloc = std::allocator<std::pair<const ns3::Vector3D, std::vector<const ns3::olsr::NeighborTuple*, std::allocator<const ns3::olsr::NeighborTuple*> > > >]’
../src/routing/olsr/olsr-routing-protocol.cc:853: instantiated from here
/usr/include/c++/4.1.2/bits/stl_function.h:227: error: no match for ‘operator<’ in ‘__x < __y’
debug/ns3/ipv6-address.h:432: note: candidates are: bool ns3::operator<(const ns3::Ipv6Address&, const ns3::Ipv6Address&)
debug/ns3/nstime.h:475: note: bool ns3::operator<(const ns3::Time&, const ns3::Time&)
debug/ns3/ipv4-address.h:305: note: bool ns3::operator<(const ns3::Ipv4Address&, const ns3::Ipv4Address&)
debug/ns3/address.h:231: note: bool ns3::operator<(const ns3::Address&, const ns3::Address&)
debug/ns3/type-id.h:376: note: bool ns3::operator<(ns3::TypeId, ns3::TypeId)
Thanks in advance.
Bahar
std::map is a sorted container of pairs. As such, keys in the map must have operator <() defined. Make sure Vector has the less-than operator defined.
For example:
class Vector {
int len, ang;
friend bool operator<(const Vector&, const Vector&);
};
bool operator<(const Vector& v1, const Vector& v2)
{
return true_if_v1_is_less_than_v2(); // you define what "less than" means
}
Of course, there other ways to do this. You may make operator< a member function. Or you may have the two member data public and the operator a non-member, non-friend function. Or you may define operator< in an anonymous namespace, to enhance information hiding. Or you may use a comparator other than operator<.
You declared the position object as followed : std::map<Vector, std::vector<const NeighborTuple *> > position;
And you are trying to push NeighborTuple * inside...
Try using const NeighborTuple *
I notice that you seem to have a pushback line that compiles and a line that does not.
The difference might be that you have a const in the first case
NeighborTuple const &nb_tuple = *it;