Reputation: 1212
I got a struct that a user can define what string values go in where. I've tried ordering it alphabetically but had no luck with what research I found online. I was hoping if one of use can see where im going wrong
libraries being used : iostream, string, fstream and algorithm
struct House
{
int room_num;
string person;
};
struct compare_by_word
{
bool operator()(const House& lhs, const House& rhs)
{
return lhs.person < rhs.person;
}
};
I get errors on this line, by the way im using visual studios 2010
void asc_order()
{
sort(data.begin(), data.end(), compare_by_word());
//for loop will be displayed here to show table
}
Errors I get:
Error: Identifier data is undefined
struct compare_by_word Error: type name is not allowed
Upvotes: 0
Views: 1102
Reputation: 96810
You need to pass an instance of compare_by_word
. This is done by calling its constructor:
std::sort(data.begin(), data.end(), compare_by_word());
// ^^^^^^^^^^^^^^^^^
I also see that you're not compiling with any headers that introduce an object with a begin
or end
method. These are commonly used in vectors and other dynamic containers. So I think you should try passing the address range instead as feasible alternative:
std::size_t len = sizeof(data)/sizeof(*data);
std::sort(data, data + len, compare_by_word());
Or if you're compiling in C++11 you can pass a lambda callback in place of an explicit functor and use the begin
and end
library functions instead of the address range:
using std::begin;
using std::end;
std::sort(begin(data), end(data), [] (House const& lhs, House const& rhs)
{
return lhs.person < rhs.person;
});
Upvotes: 1
Reputation: 5191
There is an error in sort statement.Replace it by:
sort(&data[0],&data[5],compare_by_word());
Upvotes: 0
Reputation:
An alternative would be
struct compare_by_word
{
bool operator()(const House& lhs, const House& rhs)
{
return lhs.person < rhs.person;
}
} compare_by_word; // Here.
Upvotes: 0
Reputation: 18358
You're passing the type as comparator. You need to pass object of compare_by_word
as comparator to sort
.
Upvotes: 2