排序一个矢量<结构体>按字母顺序矢量、字母、顺序、结构

2023-09-11 01:59:07 作者:清歌一曲叹红尘

我有一个的std ::矢量< Word和GT;数据即关以下结构的:

I have a std::vector<Word> data that is off of the struct below:

struct Word
{
    std::string word;
    int line_number;
};

我已经阅读从一个文件的话,并把它推到我的载体存储字符串中的字以上随着这个词出现在的行号。现在我需要的话按字母顺序排序,我尝试了以下内容:

I have read in words from a file and pushed it in to my vector storing the words in the string above along with the line number that the word appears on. Now I need to sort the words alphabetically and I attempt the following:

    std::sort(data.begin(), data.end());

然而,当我尝试编译我收到错误的疯狂的一长串以下。我相信这是由于排序算法试图比较vector.begin()来vector.end(),但它不知道如何将结构字评价到另一个结构字。

However when I try to compile the following I get a crazy long list of errors. I believe this is due to the sort algorithm trying to compare the vector.begin() to vector.end() but it doesn't know how to evaluate the struct word to another struct word.

不过我也是。我难倒就如何比较与包含在载体结构中的字符串。

However neither do I. I am stumped on how to compare the string contained with the structs in the vector.

推荐答案

在这种情况下,你应该写一个函数来比较两个结构和功能传递给的std ::排序

In this scenario you should write a function that compares two Word structs and pass that function to std::sort.

bool compare_by_word(const Word& lhs, const Word& rhs) {
    return lhs.word < rhs.word;
}

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

在这个问题你可以找到解决办法,如果你想编写一个通用的比较器,基于属性的比较对象。

In this question you can find solution if you want to write a generic comparator for comparing objects based on an attribute.