gpt4 book ai didi

c++ - 根据 getter 成员函数对 STL 容器进行排序,无需编写额外的代码

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:33 25 4
gpt4 key购买 nike

让我们考虑以下代码示例:

// Example program
#include <iostream>
#include <string>
#include <algorithm>

class A
{
public:
A( const std::string& name ) : name( name ) {}

inline const std::string& getName() const { return name; }

private:
std::string name;
};

int main()
{
std::vector<A> v;
v.push_back( A("b") );
v.push_back( A("a") );

// want to sort the container, based on it's name!
}

我知道如何做到这一点(定义内部或外部 operator< ,或声明一个提供 operator() 的仿函数结构/类并将其传递给 std::sort 函数),例如:

bool operator<( const A& a ) const
{
return getName() < a.getName();
}

但是,每次我想根据包含的类属性对容器进行排序时,我都懒得这样做,特别是当类为其提供 getter 函数时。

是否可以请求根据类成员函数结果值进行排序(如果这个有可用的比较器,显然)?

类似于:

std::sort( v.begin(), v.end(), &(A::getName) );

无需声明新的运算符或仿函数?

可选问题:如果 vector 包含指针 ( std::vector<A*> v ) 怎么办...单行语句可以根据 A::getName 对其进行排序吗结果?

最佳答案

您可以使用 lambda 函数对 vector 进行排序:

std::sort(v.begin(), v.end(), [] (A const& a, A const& b) {
return a.getName() < b.getName();
});

它比你的版本长,但你不需要在调用 sort 之前写任何东西。

如果你需要经常做那种事情,你可以把所有东西都放在一个小的仿函数中(并让它同时适用于AA* 和 smart指针),它使用 mem_fn (感谢@T.C.):

template <typename T, typename R>
struct cmp_attr {

using fun_t = R (T::*) () const;

cmp_attr (fun_t g) : _g(g) { }

template <typename U>
bool operator() (U const& a, U const& b) const {
auto fn = std::mem_fn(_g);
return fn(a) < fn(b);
}

private:
fun_t _g;
};

// Utility function to have template parameters deduced, a like std::make_pair
template<typename T, typename R>
auto make_cmp_attr (R (T::*g) () const) {
return cmp_attr<T, R>(g);
}

然后:

struct A { const std::string& getName(); }
struct B: public A { }

std::vector<A> v1; // vector of A
std::sort(v1.begin(), v1.end(), make_cmp_attr(&A::getName));
std::vector<A*> v2; // vector of A*
std::sort(v2.begin(), v2.end(), make_cmp_attr(&A::getName));
std::vector<B> v3; // vector of child class
std::sort(v3.begin(), v3.end(), make_cmp_attr(&A::getName));
std::vector<B*> v4; // vector of pointer of child class
std::sort(v4.begin(), v4.end(), make_cmp_attr(&A::getName));

关于c++ - 根据 getter 成员函数对 STL 容器进行排序,无需编写额外的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36932391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com