Hi everyone,

I'm trying sort a C++ struct and print the result as output file.

I don't know how to sort the structure. Did anyone develop this before?

Thanks a lot,

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

#define N_P 6

struct p_t {
  int id1;
  int id2;
  int id3;
  string gender;
  } indP [N_P];

void printP (p_t p);

int main ()
  string mystr;
  int n;

  for (n=0; n<N_P; n++)
    cout << "Enter id1: ";

    getline (cin,mystr);
    stringstream(mystr) >> indP[n].id1;

    cout << "Enter id2: ";
    getline (cin,mystr);
    stringstream(mystr) >> indP[n].id2;

    cout << "Enter id3: ";
    getline (cin,mystr);
    stringstream(mystr) >> indP[n].id3;


  cout << "\nYou have entered these pFile:\n";
  for (n=0; n<N_P; n++)

  return 0;


void printP (p_t p)
  cout << "ID1 " << p.id1  << "\n";
  cout << "ID2 " << p.id2 << "\n";
  cout << "ID3 " << p.id3 << "\n";

5 Years
Discussion Span
Last Post by sadsdw

you can use std::sort. Here is an example :

struct DaniwebMember{
  int ranking;
  int age;
  DaniwebMember() : ranking() , age() {}
  DaniwebMember( int r , int a ) : ranking(r) , age(a){}
bool compareByRanking(const DaniwebMember& m1, const DaniwebMember& m2){ return m1.ranking < m2.ranking; }
bool compareByAge(const DaniwebMember& m1, const DaniwebMember& m2){ return m1.age < m2.age; }

int main(){
 DaniwebMember members[100]; 
 //populate members ...
 std::sort( members , members + 100 , compareByAge ) ;//sort by age
 std::sort( members, members + 100, compareByRanking ); //sort by ranking

so you see, all you have to do is create a compare function and pass it onto std::sort


Hi firstPerson,

Thanks a lot. I will try your code.


This question has already been answered. Start a new discussion instead.
Please be thoughtful and detailed and be sure to adhere to our posting rules.