I am trying to take a std::vector<Card> and organize it by one of the int values stored inside the Card class. How could I go about doing this with iterators and the sort() method? Or is it not possible? Ty :)

Recommended Answers

All 3 Replies

First, you'll have to create a < operator for your class and then you'll have to create a function that compares two objects of that class using the < operator and then call the sort algorithm

sort(your_vector.begin(), your_vector.end(), sort_function);

Here's a simple example

#include <iostream>
#include <vector>
#include <algorithm>

class myint
{

public:

    myint(int val):itsvalue(val) {}

    bool operator <(const myint & m) const { return itsvalue < m.itsvalue; }

    int getitsvalue() const { return itsvalue; }

private:

    int itsvalue;

};

bool myint_compare(const myint & a, const myint & b)
{
    return a < b;
}

std::ostream& operator <<(std::ostream & out, const myint & m)
{
    return out << m.getitsvalue();
}

int main()
{
    std::vector<myint> the_ints;

    for (int i = 8; i > 0; --i)
        the_ints.push_back(i);

   for (int i = 0; i < 8; ++i)
           std::cout << the_ints[i] << std::endl;

   sort(the_ints.begin(), the_ints.end(), myint_compare);

   std::endl(std::cout);

   for (int i = 0; i < 8; ++i)
           std::cout << the_ints[i] << std::endl;

    return 0;
}

Just an example :

#include <iostream>
#include <vector>

using namespace std;

struct Person{
 int age_;
 float gpa_;
 Person(int age = 0, float gpa = 0.0f) : age_(age), gpa_(gpa) {}
};

ostream& operator << (ostream& stream, const Person& p){
    return stream << "[" << p.age_ << "," << p.gpa_ << "]";
}

template<typename ForwardIterator>
void print(ForwardIterator begin, ForwardIterator end){
 while( begin != end) cout << *begin++ << " ";
 cout << endl;
}

bool ageComparison(const Person& l, const Person& r){
 return l.age_ < r.age_;
}
int main(){
 std::vector<Person> students;
 students.push_back( Person(18,3.5f) );
 students.push_back( Person(20, 2.9f) );
 students.push_back( Person(11, 4.0f) );
 cout << "Original : ";
 print( students.begin(), students.end() );
 std::sort( students.begin(), students.end(), ageComparison );
 print( students.begin(), students.end() );
}

Both excellent explanations :) Got a new thread now with a different question xD Ty

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.