1

Hi I have a C++ code where there is a struct and list of structs. In my struct, the first element is a string. In list of struct, how do I sort with the first element of the structure so that after sorting all the elements in the list will be arranged alphabetically? please find piece of sample code below. thanks in advance.

struct samplestruct
{
    string Name;
    int Number
};
samplestruct obj_samplestruct;
vector<samplestruct> List;
obj_samplestruct.Name = "Tom";
obj_samplestruct.Number = 1;
list.push_back(obj_samplestruct);

obj_samplestruct.Name = "Jerry";
obj_samplestruct.Number = 2;
list.push_back(obj_samplestruct);

obj_samplestruct.Name = "Tom";
obj_samplestruct.Number = 3;
list.push_back(obj_samplestruct);

Now in the above code how do I sort as per Name in structure so that in list the members should be arranged alphabatically..

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
user3164377
  • 59
  • 2
  • 6
  • 2
    Possible duplicate? http://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects – Mike Jan 20 '14 at 12:06

3 Answers3

4

The sort function requires something that can be called with two arguments and returns a bool, this could be a lambda function:

sort( list.begin( ), list.end( ), 
    []( const samplestruct& a, const samplestruct&b ){
    return a.Name < b.Name;
} );

By default it looks for an operator<, so this would work as well:

bool operator<( const samplestruct& a, const samplestruct&b ){
    return a.Name < b.Name;
}
sort( list.begin( ), list.end( ) );
pentadecagon
  • 4,717
  • 2
  • 18
  • 26
1

The following code should solve your problem:

struct samplestruct_lessThan
{
    bool operator()(samplestruct const & a, samplestruct const & b) const
    {
        return a.Name < b.Name;
    }
};

std::sort(object.begin(), object.end(), samplestruct_lessThan());
akhikhl
  • 2,552
  • 18
  • 23
  • Thats brillant, it solves my problem exactly. Thanks a lot. Now trying to crack down and understand your logic. – user3164377 Jan 20 '14 at 12:17
1

Others,

struct samplestruct{

 string Name;

 int Number;

 bool operator<( const samplestruct& a) const { 

 //just + 'const': maybe patch for the bug of GCC(clang-802.0.42)

 return Name < a.Name;

 }

};

sort( );

Vittore Marcas
  • 1,007
  • 8
  • 11