如何基于向量< string>对结构的向量进行排序.在要排序的向量内? [英] How to sort a vector of structs based on a vector<string> within the vector to be sorted?

查看:70
本文介绍了如何基于向量< string>对结构的向量进行排序.在要排序的向量内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to alphabetically sort a vector of structures based on the first word in every vector of all the structures in the vector of structures?

struct sentence{
    vector<string> words;
};

vector<sentence> allSentences;

换句话说,如何基于单词[0]对allSentences排序?

In other words, how to sort allSentences based on words[0]?

编辑:我使用了以下解决方案:

I used the following solution:

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

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

推荐答案

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

Provide a suitable comparison binary function and pass it on to std::sort. For example

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匿名函数

Alternatively, in C++11 you can use a lambda anonymous function

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

这篇关于如何基于向量&lt; string&gt;对结构的向量进行排序.在要排序的向量内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆