如何根据要排序的向量中的向量对结构<string>向量进行排序?

How to sort a vector of structs based on a vector<string> within the vector to be sorted?

本文关键字:向量 排序 string gt lt 何根 结构      更新时间:2023-10-16

根据结构向量中所有结构的每个向量的第一个单词按字母顺序排序结构向量的最佳方法是什么?

struct sentence{
    vector<string> words;
};
vector<sentence> allSentences;

换句话说,如何根据单词[0]对所有句子进行排序?


EDIT:我使用了以下解决方案:

bool cmp(const sentence& lhs, const sentence & rhs)
{
  return lhs.words[0] < rhs.words[0];
}
std::sort(allSentences.begin(), allSentences.end(), cmp);

提供合适的比较二进制函数并传递给std::sort。例如

bool cmp(const sentence& lhs, const sentence & rhs)
{
  return lhs.words[0] < rhs.words[0];
}
然后

std::sort(allSentences.begin(), allSentences.end(), cmp);

或者,在c++ 11中,您可以使用lambda匿名函数

std::sort(allSentences.begin(), allSentences.end(), 
          [](const sentence& lhs, const sentence & rhs) {
                     return lhs.words[0] < rhs.words[0];}
         );

您需要一些可以传递给std::sort的比较函数:

bool compare(const sentence& a, const sentence& b)
{
  return a.words[0] < b.words[0];
}

可以看到,它接受两个sentences,如果第一个sentence的第一个单词"小于"第二个sentence的第一个单词,则返回true。

那么你可以很容易地排序allSentences:

std::sort(allSentences.begin(), allSentences.end(), compare);

当然,使用这种比较意味着像{"hello", "world"}{"hello", "friend"}这样的句子将比较相等。但这是你要求的。

一般来说,您应该考虑比较实现的三种不同类型的场景。

  1. 对象的比较,使总是有意义。它独立于你想比较对象的场景。然后:为你的类实现operator<。这个操作符在比较两个对象时使用(与<比较,这是标准算法所做的)。(对于单个场景,您仍然可以使用下面的其他方法"覆盖"此行为)。

    为此,使用以下函数扩展类:
    struct sentence{
        vector<string> words;
        bool operator<(const sentence &other) const {
            return this->words[0] < other.words[0];
        }
    };
    

    然后,在没有其他参数的句子向量上调用标准排序算法:

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

    然而,你的场景听起来不像这是最好的方法,因为按第一个单词比较是你不希望总是的,也许只有一种情况。

  2. 对象的比较,它将只使用一次。在c++ 11中,您有lambda函数(匿名,字面上的内联函数),可以将其直接传递给将使用它的算法函数,如本场景中的std::sort。这是我最喜欢的解决方案:

    // Sort lexicographical by first word
    std::sort(allSentences.begin(), allSentences.end(),
              [](const sentence& a, const sentence& b) {
        a.words[0] < b.words[0];
    });
    

    在c++ 03中,如果没有lambdas,请使用第三种解决方案:

  3. 一组不同的、可重用的比较方法,可能是一个参数化的比较函数。例如:通过第一个单词比较,通过长度比较,通过其他东西比较……在这种情况下,将比较函数实现为独立函数并使用函数指针,或者将它们实现为函子(可以参数化)。此外,在这种情况下,存储在变量中的lambdas可以完成这项工作。

    此方法的优点是命名比较方法,赋予它们意义。如果您对同一个对象使用不同的比较,但是重用它们,这是一个巨大的优势:

    // Lexicographical comparison by the first word only
    bool compareLexByFirstWord(const sentence& a, const sentence& b) {
        return a.words[0] < b.words[0];
    }
    // Lexicographical comparison by all words
    bool compareLex(const sentence& a, const sentence& b) {
        return a.words < b.words;
    }
    // Decide which behavior to use when actually using the comparison:
    std::sort(sentence.begin(), sentence.end(), compareLexByFirstWord);
    std::sort(sentence.begin(), sentence.end(), compareLex);