Skip to content

Instantly share code, notes, and snippets.

@duckie
Created June 27, 2012 13:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duckie/3004021 to your computer and use it in GitHub Desktop.
Save duckie/3004021 to your computer and use it in GitHub Desktop.
C++ : How to sort a vector of a user struct/class by using one of its members
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Donnees
{
int m_1;
std::string m_2;
float m_3;
Donnees() : m_1(0), m_3(0.f) {}
Donnees(int iM1, std::string const & iM2, float iM3) : m_1(iM1), m_2(iM2), m_3(iM3) {}
bool operator < (const Donnees &iData) const
{
return m_1 < iData.m_1;
}
};
int main(int argc, char* argv[])
{
std::vector<Donnees> vect;
vect.push_back(Donnees(5,"C1",0.2f));
vect.push_back(Donnees(2,"C2",0.4f));
vect.push_back(Donnees(8,"C3",0.25f));
vect.push_back(Donnees(4,"C4",0.15f));
vect.push_back(Donnees(3,"C5",0.6f));
std::sort(vect.begin(), vect.end());
for(std::vector<Donnees>::iterator it = vect.begin(); it != vect.end(); it++)
std::cout << "(" << it->m_1 << "," << it->m_2 << "," << it->m_3 << ")" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment