字符串向量的排序向量在C ++ [英] sorting vector of vector of strings in C++

查看:233
本文介绍了字符串向量的排序向量在C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何对字符串向量的向量进行排序,这里是测试代码。

I am having trouble to figure out, how to sort a vector of vector of strings, here is the testing code.



#include <iostream>
#include <vector>
#include <boost/algorithm/string.hpp>

int main(int argc, char** argv) {
  std::vector <std::vector <std::string> > data_var;
  std::vector <std::string> temp;

  std::string str1 = "1,hello3,temp2";
  std::string str2 = "2,hello2,temp1";
  std::string str3 = "3,hello1,temp3";

  boost::split(temp, str1, boost::is_any_of(","));
  data_var.push_back(temp);
  boost::split(temp, str2, boost::is_any_of(","));
  data_var.push_back(temp);
  boost::split(temp, str3, boost::is_any_of(","));
  data_var.push_back(temp);

  // sorting code here...
}

提前感谢...

推荐答案

如果您只想基于第二列排序,那么您只需要提供自定义比较运算符。一个方法是:

If you only want to sort based on the second column, then you just need to provide a custom comparison operator. Once way to do that is:

struct StringListCompare
{
  bool operator()(const vector<string>& lhs, const vector<string>& rhs)
  {
    // what do we do if lhs or rhs don't have two elements?
    if (lhs.size() < 2 || rhs.size() < 2)
    {
      // ?
    }
    else
    {
      return lhs[1] < rhs[1];
    }
  }
} StringListComparer;

int main()
{
  // ...
  sort(data_var.begin(), data_var.end(), StringListComparer);
}

编辑:如果直到运行时才知道,排序,可以在排序对象中对其进行编码:

If you won't know until runtime which column you'll be sorting on, you can encode that in the sorting object:

class StringListCompare
{
public:
  explicit StringListCompare(int column) : m_column(column) {}
  bool operator()(const vector<string>& lhs, const vector<string>& rhs)
  {
    // what do we do if lhs or rhs don't have (m_column + 1) elements?
    return lhs[m_column] < rhs[m_column];
  }
private:
  int m_column;
};

注意我们如何添加一个构造函数,你可以这样使用它:

Notice how we've added a constructor that takes which column it'll act on. You can use it like this:

  // We set it up so the columns are 0-based:
  StringListCompare compare_column_0(0), compare_column_1(1), compare_column_2(2);

  cout << "Original:\n" << data_var << endl;
  sort(data_var.begin(), data_var.end(), compare_column_2);
  cout << "Sorted on column 2:\n" << data_var << endl;
  sort(data_var.begin(), data_var.end(), compare_column_1);
  cout << "Sorted on column 1:\n" << data_var << endl;
  sort(data_var.begin(), data_var.end(), compare_column_0);
  cout << "Sorted on column 0:\n" << data_var << endl;

如果您不想要,您甚至不需要创建局部变量:

You don't even need to make the local variable if you don't want to:

  sort(data_var.begin(), data_var.end(), StringListCompare(2));
  cout << "Sorted on 2, no local sort variable:\n" << data_var << endl;

[Code at ideone]

这篇关于字符串向量的排序向量在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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