使用sort for struct的c ++麻烦

时间:2013-03-31 21:39:39

标签: c++ arrays sorting struct

我有一个结构,用户可以定义哪些字符串值在哪里。我尝试按字母顺序排序,但我在网上找到的研究没有运气。我希望如果其中一个使用可以看到我出错的地方

正在使用的库:iostream,string,fstream和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;
    }
};

我在使用Visual Studio 2010

的方式上遇到了错误
  void asc_order()
    {
        sort(data.begin(), data.end(), compare_by_word());
//for loop will be displayed here to show table
    }

我得到的错误:

错误:标识符数据未定义

struct compare_by_word 错误:不允许输入类型名称

4 个答案:

答案 0 :(得分:2)

您将类型作为比较器传递。您需要将compare_by_word对象作为比较符传递给sort

答案 1 :(得分:1)

您需要传递compare_by_word的实例。这是通过调用它的构造函数来完成的:

std::sort(data.begin(), data.end(), compare_by_word());
//                                  ^^^^^^^^^^^^^^^^^

Live Demo

我还发现您没有使用任何带有beginend方法的对象的标头进行编译。这些通常用于载体和其他动态容器中。所以我认为你应该尝试传递地址范围作为可行的替代方案:

std::size_t len = sizeof(data)/sizeof(*data);

std::sort(data, data + len, compare_by_word());

Live Demo

或者,如果您在C ++ 11中进行编译,则可以使用lambda回调代替显式仿函数,并使用beginend库函数代替地址范围:

using std::begin;
using std::end;

std::sort(begin(data), end(data), [] (House const& lhs, House const& rhs)
{
    return lhs.person < rhs.person;
});

Live Demo

答案 2 :(得分:0)

另一种选择是

struct compare_by_word
{
    bool operator()(const House& lhs, const House& rhs)
    {
        return lhs.person < rhs.person;
    }
} compare_by_word;  // Here.

答案 3 :(得分:0)

排序语句中有错误。请按以下方式删除:

sort(&data[0],&data[5],compare_by_word());

DEMO AT IDEONE