I would like to know if there is an efficient way to remove objects from a container based on values of member fields of the objects. For example, I can do the following using stl::unique with a list of strings:
#include<iostream>
#include<list>
#include<string>
#include<algorithm>
using namespace std;
bool stringCompare(const string & l, const string & r)
{
return (l==r);
}
int main()
{
list<string> myStrings;
myStrings.push_back("1001");
myStrings.push_back("1001");
myStrings.push_back("81");
myStrings.push_back("1001");
myStrings.push_back("81");
myStrings.sort();
myStrings.erase(unique(myStrings.begin(), myStrings.end(), stringCompare), myStrings.end());
list<string>::iterator it;
for(it = myStrings.begin(); it != myStrings.end(); ++it)
{
cout << *it << endl;
}
return 0;
}
prints 1001, 81...
Is there a way I can do something similar with the following code, or do I need to perform the comparisons "manually" using operators and iterating through the containers. I couldn't think of a more elegant solution and would like to know if this is possible without writing a lot of code. Any help will be much appreciated!
class Packet
{
public:
Packet(string fTime, string rID) : filingTime(fTime), recordID(rID)
string getFilingTime() {return filingTime;}
string getRecordId() {return recordID;}
private:
string filingTime;
string recordID;
};
int main()
{
vector<Packet*> pkts;
pkts.push_back(new Packet("10:20", "1004"));
pkts.push_back(new Packet("10:20", "1004")); // not unique (duplicate of the line above)
pkts.push_back(new Packet("10:20", "251"));
pkts.push_back(new Packet("10:20", "1006"));
// remove packet from vector if time and ID are the same
return 0;
}
Thanks
Two options to be able to use std::unique:
Define an operator== method for Packet and change the vector<Packet*> to vector<Packet>.
bool Packet::operator==(const Packet& rhs) const
{
if (getFilingTime() != rhs.getFilingTime())
return false;
if (getSpid() != rhs.getSpid())
return false;
return true;
}
//etc.
int main()
{
vector<Packet> pkts;
pkts.push_back(Packet("10:20", "1004"));
pkts.push_back(Packet("10:20", "1004")); // not unique (duplicate of the line above)
pkts.push_back(Packet("10:20", "251"));
pkts.push_back(Packet("10:20", "1006"));
// remove packet from vector if time and ID are the same
pkts.erase(unique(pkts.begin(), pkts.end()), pkts.end());
return 0;
}
Keep the vector as vector<Packet*> and define a method to compare the elements.
bool comparePacketPtrs(Packet* lhs, Packet* rhs)
{
if (lhs->getFilingTime() != rhs->getFilingTime())
return false;
if (lhs->getSpid() != rhs->getSpid())
return false;
return true;
}
//etc.
int main()
{
vector<Packet*> pkts;
pkts.push_back(new Packet("10:20", "1004"));
pkts.push_back(new Packet("10:20", "1004")); // not unique (duplicate of the line above)
pkts.push_back(new Packet("10:20", "251"));
pkts.push_back(new Packet("10:20", "1006"));
// remove packet from vector if time and ID are the same
pkts.erase(unique(pkts.begin(), pkts.end(), comparePacketPtrs), pkts.end());
return 0;
}
As an alternative to unique, you could simply insert the elements into a set (or unordered_set in C++11).
Whichever way you decide to go, you'll need to define comparison operators for Packet. For unique, you'll need operator==; for set you'll need operator<. For completeness, you should define both, and their counterparts:
class Packet {
…
bool operator==(const Packet& p) const {
return fillingTime == p.fillingTime && recordID == p.recordID;
}
bool operator<(const Packet& p) const {
return fillingTime < p.fillingTime ||
(fillingTime == p.fillingTime && recordID < p.recordID);
}
bool operator!=(const Packet& p) const { return !(*this == p); }
bool operator> (const Packet& p) const { return p < *this; }
bool operator>=(const Packet& p) const { return !(*this < p); }
bool operator<=(const Packet& p) const { return !(p < *this); }
…
};
If you use C++11's unordered_set, you'll need to go one step further and define a hash function.
EDIT: I just noticed you're storing pointers to Packet. Why? Just store Packet directly.
Related
I'm testing std::set with a custom comparator. But I see the same object getting inserted twice.
Following is the object class:
class Info
{
public:
Info(string n, string oN, int dom):
name(n),
objName(oN),
domain(dom)
{}
void setName(std::string n) { name = n;}
void setObjName(std::string n) { objName = n;}
void setDomain(int dom) { domain = dom; }
std::string getName() const { return name;}
std::string getObjName() const { return objName;}
int getDomain() const { return domain;}
private:
std::string name;
std::string objName;
int domain;
};
Following is my custom comparator:
struct InfoCmp {
bool operator() (const Info &lhs, const Info &rhs) const {
if((lhs.getName() < rhs.getName()) || (lhs.getObjName() < rhs.getObjName()) || (lhs.getDomain() < rhs.getDomain()) ){
return true;
}
return false;
}
};
Following is the usage:
Info rst1("rst1", "rstObj1", 1);
Info rst2("rst2", "rstObj2", 2);
Info rst3("rst1", "rstObj3", 3);
std::set<Info,InfoCmp> resetSet;
resetSet.insert(rst1);
resetSet.insert(rst2);
resetSet.insert(rst3);
resetSet.insert(rst1);
resetSet.insert(rst2);
resetSet.insert(rst3);
I see rst2 inserted twice, but it shouldn't be as per my comparator.
I see that you've come up with your own solution, after recognizing from the comments that your original did not impose a strict object ordering as required by set. Here's a different version that only requires operator< and not operator==, making it consistent with the classes and algorithms of the standard library. It also simplifies things if you're e.g. doing a case insensitive comparison.
struct InfoCmp {
bool operator() (const Info &lhs, const Info &rhs) const {
if(lhs.getName() < rhs.getName())
return true;
if(rhs.getName() < lhs.getName())
return false;
if(lhs.getObjName() < rhs.getObjName())
return true;
if(rhs.getObjName() < lhs.getObjName())
return false;
return lhs.getDomain() < rhs.getDomain();
}
};
struct InfoCmp2 {
bool operator() (const Info &lhs, const Info &rhs) const {
return std::make_tuple(lhs.getName(), lhs.getObjName(), lhs.getDomain()) < std::make_tuple(rhs.getName(), rhs.getObjName(), rhs.getDomain());
}
};
This operator can written with make_tuple as well, and working fine.
as suggested by Cory Kramer, adding strict ordering in comparator fixed the problem.
struct InfoCmp {
bool operator() (const Info &lhs, const Info &rhs) const {
if((lhs.getName() < rhs.getName())
|| ( (lhs.getName() == rhs.getName()) && (lhs.getObjName() < rhs.getObjName()) )
|| ( (lhs.getName() == rhs.getName()) && (lhs.getObjName() == rhs.getObjName()) && (lhs.getDomain() < rhs.getDomain()) )){
return true;
}
return false;
}
};
I need to know how to overload the operator = != and < so I could work with set<set<object> >
I have my class:
class pr{
private:
set<set<e> > pr_;
public:
pr();
~pr();
void set_pr(set<e> a);
pr& operator=(const pr& a) const;
bool operator!=(const pr& a) const;
bool operator<(const pr& a) const;
};
So if I have a set like this: {{1,2,3},{4,5}} where the numbers are objects.
I would like to do operations with the sets in other class like this:
void otherclass::myfunction(){
pr prt; //I create the objects
pr prt_old;
set<e> C1; //I create the subset and fill
set<e> C2;
//C1 and C2 filled here
prt.set_pr(C1); //Insert the set<e> into set<set<e>>
prt.set_pr(C2); //It will fail because i dont know how to compare set<e> < <set<e>
while(prt != prt_old){
prt_old = prt ;
prt = create(prt_old);
}
//...
I tried to overload doing this:
pr& pr::operator=(const pr& a) const{
this->clear();
for(set<set<e> >::iterator it =a.begin();it!=a.end();it++){
for(set<e>::iterator j = it->begin(); j != it->end();j++){
this->set_pr(*j);
}
}
return *this;
}
bool pr::operator!=(const pr& a) const{
if(this->size() != a.size()){
return 1;
}
//Now i don't know how to continue for check if for example
// i had {{1,2},{3,4}} and {{1},{2}}
//this two set have same size but they are differnt
//How could i just iterate through the two sets at same time
// and check if subset have too same size or if the objects inside the subset are equal
//Also i need the operator < to insert a set<e> into a set<set<e> > but how??
//Note: class 'e' has already defined the "operator<" for when I insert objects in the set<e>
//And i order them by a function that return an integrer
To test if one set is contained in the other, you iterate over each member of the first set, and test if it exists in the second set.
bool operator<(const pr& a) const {
for (auto _set : _data) {
if (a._data.find(_set) == a._data.end())
return false;
}
return true;
}
To test if two sets are identical, you test their size is equal, and that one is contained in the other
bool operator==(const pr& a) const {
return _data.size() == a._data.size() && *this < a;
}
But notice that there is no need to define an operator==, because the default one defined by std::set is fine.
Here is a full functioning program:
#include <iostream>
#include <set>
using namespace std;
template <class e>
class pr {
private:
set<set<e> > _data;
public:
void insert(set<e> a) { _data.insert(a); }
bool operator==(const pr& a) const {
return _data.size() == a._data.size() && *this < a;
}
bool operator!=(const pr& a) const { return !(*this == a); }
bool operator<(const pr& a) const {
for (auto _set : _data) {
if (a._data.find(_set) == a._data.end())
return false;
}
return true;
}
};
int main()
{
pr<int> a,b,c;
a.insert(set<int>({ 1 }));
b.insert(set<int>({ 1 }));
b.insert(set<int>({ 1, 2 }));
c.insert(set<int>({ 1, 2 }));
c.insert(set<int>({ 1 }));
std::cout << ((a<b) ? "a<b\n" : "NOT a<b\n");
std::cout << ((b<a) ? "b<a\n" : "NOT b<a\n");
std::cout << ((a==c) ? "a==c\n" : "NOT a==c\n");
std::cout << ((b==c) ? "b==c\n" : "NOT b==c\n");
std::cout << ((a==b) ? "a==b\n" : "NOT a==b\n");
return 0;
}
I need to make a disjoint set of the type dataum.
I have all the data in the vector as follows
vector<dataum> S;
S.push_back( dataum(0,0) );
S.push_back( dataum(0,1) );
S.push_back( dataum(0,2) );
.
.
Then I create the disjoint_set
std::vector<int> rank (100);
std::vector<dataum> parent (100);
boost::disjoint_sets<int*,dataum*> ds(&rank[0], &parent[0]);
for( int i=0 ; i<S.size() ; i++ )
{
ds.make_set( S[i] );
}
This seem to not work. What am I missing?
I want to create a disjoint set with custom datatype. In this case dataum. Initially each of my dataums should be in different sets.
The documentation states that
Rank must be a model of ReadWritePropertyMap with an integer value type and a key type equal to the set's element type.
Parent must be a model of ReadWritePropertyMap and the key and value type the same as the set's element type.
At your previous question I posted the following sample code in a comment:
After looking at the (new for me) disjoint_set_* classes, I don't think that they afford iterating members of sets. They act like unidirectional mapping from element to set representative. In case it helps you: http://paste.ubuntu.com/8881626 – sehe 9 hours ago
Here it is, reworked for an imagined dataum type:
struct dataum {
int x,y;
bool operator< (const dataum& o) const { return tie(x,y) < tie(o.x,o.y); }
bool operator==(const dataum& o) const { return tie(x,y) == tie(o.x,o.y); }
bool operator!=(const dataum& o) const { return tie(x,y) != tie(o.x,o.y); }
};
Here's how I can see a disjoint_set declaration for it:
std::map<dataum,int> rank;
std::map<dataum,dataum> parent;
boost::disjoint_sets<
associative_property_map<std::map<dataum,int>>,
associative_property_map<std::map<dataum,dataum>> > ds(
make_assoc_property_map(rank),
make_assoc_property_map(parent));
The mechanics of this are to be found in the documentation for Boost PropertyMap, which is a very powerful generic data structure abstraction layer, mostly used with Boost Graph Library. It's wildly powerful, but I can't say it's user friendly.
Here's the full demo Live On Coliru¹
#include <boost/pending/disjoint_sets.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <iostream>
#include <map>
#include <cassert>
using namespace boost;
struct dataum {
int x,y;
bool operator< (const dataum& o) const { return tie(x,y) < tie(o.x,o.y); }
bool operator==(const dataum& o) const { return tie(x,y) == tie(o.x,o.y); }
bool operator!=(const dataum& o) const { return tie(x,y) != tie(o.x,o.y); }
};
int main() {
std::vector<dataum> S { {0,0}, {0,1}, {0,2} };
std::map<dataum,int> rank;
std::map<dataum,dataum> parent;
boost::disjoint_sets<
associative_property_map<std::map<dataum,int>>,
associative_property_map<std::map<dataum,dataum>> > ds(
make_assoc_property_map(rank),
make_assoc_property_map(parent));
for(auto i=0ul; i<S.size(); i++)
ds.make_set(S[i]);
assert((ds.count_sets(S.begin(), S.end()) == 3));
assert((ds.find_set(dataum{0,2}) == dataum{0,2}));
assert((ds.find_set(dataum{0,1}) == dataum{0,1}));
ds.union_set(dataum{0,2},dataum{0,1});
assert((ds.count_sets(S.begin(), S.end()) == 2));
assert((ds.find_set(dataum{0,2}) == dataum{0,1}));
assert((ds.find_set(dataum{0,1}) == dataum{0,1}));
std::cout << "done";
}
¹ Coliru still not cooperating
I'm trying to implement a container in C++ that uses a flat array to store the data but iterates over that data in pairs. Now I could easily change the implementation such that the container holds a vector of std::pair however I want to iterate through pairs starting at element 0 or at element 1.
To illustrate what I want to achieve, if my underlying array looks like:
1,2,3,4,5,6,7,8
I want to define two iterators, one which returns the pairs:
(1,2), (3,4), (5,6), (7,8)
and the second iterator to return the pairs:
(2,3), (4,5), (6,7)
is this possible to do while still allowing the elements of the iterator to be references of the underlying array?
It is possible to write your own iterator, which iterates over the elements. The following question shows some explanations on how that is done:
Custom Iterator in C++.
You can then return the desired values as std::pair and iterate to the next element-pair (by incrementing the counter by 2).
Boost library has got Iterator Adaptor that allows you to wrap other iterator types and change or adapt their functionality. Here's how you could use it for your purpose:
#include <boost/iterator/iterator_adaptor.hpp>
#include <vector>
struct iterator :
public boost::iterator_adaptor<
iterator, // the name of our class, see docs for details
std::vector<int>::iterator, // underlying base iterator
std::pair<int&, int&>, // our value type
boost::forward_traversal_tag // the category you wish to give it
>
{
// need this to convert from vector::iterator to ours
explicit iterator(std::vector<int>::iterator i)
: iterator::iterator_adaptor_(i) {}
value_type operator*()
{
return value_type(
*base_reference(),
*(base_reference()+1)
);
}
};
Example of usage:
std::vector<int> v {1,2,3,4};
iterator it(v.begin());
++it;
(*it).first = 0; // TODO: operator->
(*it).second = 0;
for (int i : v) std::cout << i << ' '; // prints 1 0 0 4
You'll also need to override comparison to properly handle end condition, etc. Hope that helps.
Just thought I'd put in what I actually used in my code. I didn't want to use boost as suggested by #jrok but the type std::pair<int&, int&> in their answer gave me a hint of what was required.
Below is the class that I constructed which uses two iterators. A RepeatIterator that returns pairs starting on even indexes in the underlying data, and a SpacerIterator that returns pairs starting on odd indexes.
class RepeatArray {
typedef std::vector<int> storage_t;
public:
class RepeatIterator {
public:
typedef RepeatIterator self_t;
typedef int value_t;
typedef int& reference_t;
typedef int* pointer_t;
typedef std::pair<reference_t, reference_t> return_t;
RepeatIterator(storage_t::iterator input) : current_pos(input){}
return_t operator *() {
return return_t(*(current_pos), *(current_pos + 1 ));
}
self_t operator++() { self_t i = *this; current_pos += 2; return i; }
self_t operator++(int junk) { current_pos+=2; return *this; }
bool operator==(const self_t& rhs) { return current_pos == rhs.current_pos; }
bool operator!=(const self_t& rhs) { return current_pos != rhs.current_pos; }
bool operator<(const self_t& rhs) { return current_pos < rhs.current_pos; }
bool operator<=(const self_t& rhs) { return current_pos <= rhs.current_pos; }
bool operator>(const self_t& rhs) { return current_pos > rhs.current_pos; }
bool operator>=(const self_t& rhs) { return current_pos >= rhs.current_pos; }
private:
storage_t::iterator current_pos;
};
class SpacerIterator {
public:
typedef SpacerIterator self_t;
typedef int value_t;
typedef int& reference_t;
typedef int* pointer_t;
typedef std::pair<reference_t, reference_t> return_t;
SpacerIterator(storage_t::iterator input) : current_pos(input){}
return_t operator *() {
return return_t(*(current_pos), *(current_pos + 1 ));
}
self_t operator++() { self_t i = *this; current_pos += 2; return i; }
self_t operator++(int junk) { current_pos+=2; return *this; }
bool operator==(const self_t& rhs) { return current_pos == rhs.current_pos; }
bool operator!=(const self_t& rhs) { return current_pos != rhs.current_pos; }
bool operator<(const self_t& rhs) { return current_pos < rhs.current_pos; }
bool operator<=(const self_t& rhs) { return current_pos <= rhs.current_pos; }
bool operator>(const self_t& rhs) { return current_pos > rhs.current_pos; }
bool operator>=(const self_t& rhs) { return current_pos >= rhs.current_pos; }
private:
storage_t::iterator current_pos;
};
void add(int start, int end) {
positions.push_back(start);
positions.push_back(end);
}
void dump() {
for (auto i : positions) {
std::cout <<i<<",";
}
std::cout <<std::endl;
}
RepeatIterator repeatBegin(){return RepeatIterator(positions.begin());}
RepeatIterator repeatEnd(){return RepeatIterator(positions.end());}
SpacerIterator spacerBegin(){return SpacerIterator(positions.begin() + 1);}
SpacerIterator spacerEnd(){return SpacerIterator(positions.end() - 1);}
protected:
storage_t positions;
};
And then the tesing program compiled using clang++ -std=c++0x -o testRepeatArray RepeatArray.cpp
int main() {
RepeatArray r = RepeatArray();
r.add(1,3);
r.add(7,12);
std::cout<<"original:"<<std::endl;
r.dump();
std::cout << "Testing Repeat iterator:"<<std::endl;
for (RepeatArray::RepeatIterator it2 = r.repeatBegin(); it2 != r.repeatEnd(); ++it2) {
std::cout << (*it2).first <<","<< (*it2).second << std::endl;
}
std::cout << "Testing Spacer iterator:"<<std::endl;
for (RepeatArray::SpacerIterator it3 = r.spacerBegin(); it3 != r.spacerEnd(); ++it3) {
std::cout << (*it3).first <<","<< (*it3).second << std::endl;
}
std::cout<<"Testing modification:"<<std::endl;
RepeatArray::RepeatIterator it = r.repeatBegin();
(*it).first = 0;
(*it).second = 123;
r.dump();
return 0;
}
I have problem with set. I don't know what I'm doing wrong. Maybe some one of you can help me. So lets begin , the output of my program should be :
Iksinski Adam, Kowalski Jan, Nowak Adam, Nowak Jan,
So its sorted by first string.
And here's my program :
#include <set>
#include <iterator>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
class Person{
public:
Person(){}
Person(string v , string v1):nazw(v),imie(v1){}
bool operator<(const Person & K) const
{
return ((this->getN()>K.getN())?0:1);
//return ((this->getN()<K.getN())?1:0);
}
string getN()const
{
return nazw;
}
/*
bool operator()(Person & K, Person & K1)
{
return ((K->getN()<K1.getN())?1:0);
}
*/
friend ostream& operator<<(ostream & o , const Person&K)
{
o << K.nazw << " " << K.imie;
return o;
}
private:
string nazw,imie;
};
struct cmp
{
bool operator()(const Person &K , const Person &K1)
{
return ((K.getN()<K.getN())?1:0);
}
};
int main()
{
//typedef set<Person> kontener_typ;
typedef set<Person,cmp> kontener_typ;
kontener_typ c;
c.insert(Person("Nowak","Jan"));
c.insert(Person("Nowak","Adam"));
c.insert(Person("Kowalski","Jan"));
c.insert(Person("Nowak","Adam"));
c.insert(Person("Iksinski","Adam"));
std::copy (c.begin(), c.end(), ostream_iterator<Person>(cout, " ,"));
std::cout << std::endl;
}
Ok so in main i can only edit typdef , and copy function ( but I need to use it to output the set).
Like you see i tried to overload operator< in Person (because set compering Person to Person) but it doeasnt work . I also trying with functor but it then the output looks like
Iksinski Adam ,Nowak Adam ,Kowalski Jan ,Nowak Adam ,Nowak Jan ,
So second string should be deleted .
Good luck :).
Your code is using your comparator cmp functor object. There is a bug in it:
struct cmp
{
bool operator()(const Person &K , const Person &K1)
{
// one of these _should_ be K1
return ((K.getN()<K.getN())?1:0);
}
};
I like to name my variables in a way that it becomes clear how they are being compared, for instance:
struct cmp
{
bool operator()(const Person &left , const Person &right)
{
return left.getN() < right.getN();
}
};
This clarifies (for me at least) that the operator is comparing like this: left < right.
However, you also need to sort by "first name" as a secondary criteria, which would make the function look like this:
struct cmp
{
bool operator()(const Person &left , const Person &right)
{
if(left.getN() < right.getN())
return true;
else if(left.getN() > right.getN())
return false;
// assuming the getI() function returns the first name,
// just as the getN() function returns the last name
else if(left.getI() < right.getI())
return true;
else
return false;
}
};
You must compare by both last and first names:
bool operator<(const Person & other) const
{
if ( getN() < other.getN() )
return true;
if ( other.getN() < getN() )
return false;
if ( imie < other.imie() )
return true;
return false;
}
Or, if you want to use struct cmp:
struct cmp
{
bool operator()(const Person &K , const Person &K1)
{
if (K.getN() < K1.getN())
return true;
if(K1.getN() < K.getN())
return false;
if(K.imie < K1.imie) // will need a friend declaration or a getter() func
return true;
return false;
}
}
If you have C++'s std::tie, then the guts of either function gets much simpler:
return std::tie(nazw, imie) < std::tie(other.nazw, other.imie);
return std::tie(K.nazw, K.imie) < std::tie(K1.nazw, K1.imie);