【问题标题】:c++ passing class member function pointer to another functionc ++将类成员函数指针传递给另一个函数
【发布时间】:2014-08-07 08:19:13
【问题描述】:

我在互联网上搜索并找到了一些解决方案,但我不想更改我的整个代码。 我想在vector<my_class *> 中搜索不同的对象,所以我写了这个但它不起作用:

static vector <attendant *> attendant_vec;
template<typename T, typename R>
int binary_search(int first_cell, int last_cell,int search_key, vector<T*>& v, R (T::*func)(void), void *sort){
    int index;
    quicksort(v, v.size(), 0, sort);
    if(first_cell > last_cell)
        return -1;
    else {
        int middle = (first_cell + last_cell)/2;
        if(search_key== v.at(middle).*func())
            index=middle;
        else
            if(search_key< v.at(middle).*func())
                index=binary_search(first_cell, middle-1, search_key, v, func,sort);
            else
                index=binary_search(middle+1, last_cell, search_key, v, func,sort);
    }
    return index;
}

void my_function() {
    int u = binary_search(0,attendant_vec.size(),12,
            attendant_vec,&attendant::get_personal_code,
            &sort_by_personal_code);//ERROR
    cout<<u;
}

我遇到了这些错误:

这一行有多个标记

  • 没有匹配函数调用‘binary_search(int, std::vector::size_type, int, std::vector&, int (话务员::)()const, bool ()(话务员*,话务员*))’
  • 候选人是:
  • 推断参数“_FIter”的冲突类型(“int”和“long unsigned int”)
  • 类型“R (T::)()”和“int (attendant::)()const”具有不兼容的 cv 限定符

【问题讨论】:

  • 您能否给出一个最小的情况并对变量进行去混淆处理?
  • D47'$ $0/\/\3 L337 (0D3 d00D
  • 双下划线指向 UB。
  • 好的 - 我将编辑代码。它是关于二分搜索算法函数的,我想在我的向量 中搜索几个对象,但我不想编写 2 个不同的搜索函数来完成它我想使用函数指针并将每个(give_object_name)函数传递给搜索函数并使用它。
  • 我已将您的代码编辑为人类可读的。如果 1337 不足以满足您的需求,则回滚。

标签: c++ class templates vector member-function-pointers


【解决方案1】:

您可以使用std::binary_search,如下所示:

void my_function() {
    int u = std::binary_search(attendant_vec.begin(), attendant_vec.end(), 12, &sort_by_personal_code);
    std::cout << u;
}

【讨论】:

  • 我想自己写!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 2015-03-22
  • 1970-01-01
相关资源
最近更新 更多