【问题标题】:std::sort using member function in the same class?std::sort 在同一个类中使用成员函数?
【发布时间】:2017-06-13 03:06:04
【问题描述】:

我有一个类“PclProc”,我想使用 std::sort。

我在同一个类中编写了一个比较函数,因为这种比较需要“in_ptr”,它是同一个类中的一个变量。

但正如我所做的那样,总是有一个错误:

错误:没有匹配的调用函数 '排序(标准::向量::迭代器,标准::向量::迭代器, )’ std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);

bool PclProc::MyCompare(int id1,  int id2)
{
    return in_ptr->points[id1].z<in_ptr->points[id2].z;
}


float PclProc::MedianZDist(pcl::PointIndices cloud_indice)
{
    std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);
    int size=cloud_indice.indices.size();
    float median_x,median_y;
...

【问题讨论】:

  • std::sort 不适用于普通成员函数。如果您的 C++ 编译器支持 lambda 函数,则可以使用函数运算符 (functor) 或 lambda 函数。有关于此的先前线程,例如this one
  • @rcgldr 谢谢。我的情况是 C++11 不可用。所以无法使用 lambda 函数。我知道函数运算符重载。但是你能给我更多关于如何为我的特殊情况写作的提示吗?

标签: class sorting member-functions


【解决方案1】:

用于 std::sort 的仿函数示例。向量 D 是数据,向量 I 是 D 的索引。 I 使用仿函数根据 D 和 std::sort 排序。 std::sort 只创建一个小于类的实例,然后使用该实例进行所有比较。

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <vector>

typedef unsigned int uint32_t;

#define SIZE 16

class example{
public:
    std::vector<uint32_t> D;    // data
    std::vector<uint32_t> I;    // indices

example(void)
{
    D.resize(SIZE);
    I.resize(SIZE);
    for(uint32_t i = 0; i < SIZE; i++){
        D[i] = rand()%100;
        I[i] = i;
    }
}

void displaydata(void)
{
    for(size_t i = 0; i < SIZE; i++)
        std::cout << std::setw(3) << D[I[i]];
    std::cout << std::endl;
}

class lessthan                  // lessthan functor for std::sort
{
public:
const example &x;
    lessthan(const example &e ) : x(e) { }
    bool operator()(const uint32_t & i0, const uint32_t & i1)
    {
        return x.D[i0] < x.D[i1];
    }
};

void sortindices(void)
{
    std::sort(I.begin(), I.end(), lessthan(*this));
}
};

int main()
{
example x;
    x.displaydata();
    x.sortindices();
    x.displaydata();
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    相关资源
    最近更新 更多