Saad Alarifi
Saad Alarifi

Reputation: 11

sorting alphabetically from a file C++

i am trying to read a file and sorting it alphabetically, i do not know how to tackle this issue.

so i am reading a file that contains , States, counties, and cities. and i need to sort the State alphabetically. can you please guide on how to solve this?

i have tried this:

void sorting(struct state* array, int x){
    int narray = sizeof(array[x].name)/sizeof(array[0].name);
    sort(array[x].name, array[x].name + narray);
    for(int i = 0; i < narray; ++i) {
        cout << array[i].name<< endl;
    }
}

here is my struct:

struct state {
    string name; //name of state
    struct county *c; //name of counties
    int counties; //number of counties in state
    int population; //total population of state
};

and here is how i read the file:

 File >> array[i].name;
 File >> array[i].population;
 File >> array[i].counties;

it gave me an errors, am i on the right track?

the error i got are:

main.cpp:193:45: error: invalid operands to binary expression ('string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') and 'int')
sort(array[x].name, array[x].name + narray);
~~~~~~~~~~~~~ ^ ~~~~~~  

and i got this error 8 times with different numbers:

   /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string:3987:1: note: candidate template ignored: deduced conflicting types for parameter '_CharT' ('char' vs. 'int')
operator+(const basic_string<_CharT, _Traits, _Allocator>& __lhs, _CharT __rhs)

Upvotes: 0

Views: 500

Answers (1)

Jonathan Mee
Jonathan Mee

Reputation: 38959

Create comparison operators for struct state using lexicographical_compare

bool operator< (const state& rhs) {
    return lexicographical_compare(name.cbegin(), name.cend(), rhs.name.cbegin(), rhs.name.cend());
}

bool operator== (const state& rhs) {
    return name == rhs.name;
}

You can then use sort directly on array:

sort(begin(array), end(array));

I've trimmed your class a bit, but this is how it would work: http://ideone.com/SwaivI

Upvotes: 1

Related Questions