【问题标题】:Passing structure members to a function将结构成员传递给函数
【发布时间】:2016-10-20 05:33:33
【问题描述】:

我最近开始使用 c++ 进行编码,现在我正在处理结构......这是我的问题

这是我的基本结构。

struct myStruct
{
    string A;
    int B;
} myStruct[100];

我想将 'myStruct' 中的字符串(对于结构数组中的所有元素)传递给排序函数(我正在使用内置排序函数)。我该怎么做?我想要对所有字符串进行排序...... 我已尽力解释我的问题。我希望你能得到它并帮助我..

【问题讨论】:

  • 您想按字符串对字符串或结构数组进行排序?
  • 你可以先google一下。我相信这个例子解释就足够了cplusplus.com/articles/NhA0RXSz.

标签: c++ structure


【解决方案1】:

如果我理解正确,并且您想根据每个结构中的字符串A 对数组进行排序,您需要告知std::sort 如何比较您的结构。

一种方法是为您的自定义类型添加operator<。

bool operator< (myStruct const& lhs, myStruct const& rhs) {
  return lhs.A < rhs.A;
}

另一种方法是传递std::sort一个比较函数对象:

std::sort( std::begin(myArray), std::end(myArray),
           [](myStruct const& lhs, myStruct const& rhs)
           { return lhs.A < rhs.A; } );

【讨论】:

  • 我觉得提一下传递函数指针可能比传递 lambda(或函数对象,这就是 lambda)慢是个好主意。
猜你喜欢
  • 1970-01-01
  • 2012-10-06
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多