传递一个结构类型c++

passing a type of a struct c++

本文关键字:一个 结构 类型 c++      更新时间:2023-10-16

我想将一种类型的结构传递给函数,然后函数将循环通过这些结构的向量来检查条件。这可能吗?

#define EMPTY -1
struct CHAMPION{
    int champ_ID;
    int weaponL_ID;
    int weaponR_ID;
}
vector<string> Champions;
int getChampIndex("struct_obj" obj, int value){
    for(int i=0; i<Champions.size(); i++){
        if(Champions[i].obj == value){return i;}
    }
}
int main(){
    //fill Champions vector
    SearchedChamp = getChampIndex(champ_ID, 17);
    //process SearchedChamp
    NoWeaponL = getChampIndex(weaponL_ID, EMPTY);
    //process NoWeaponL
    NoWeaponR = getChampIndex(weaponR_ID, EMPTY);
    //process NoWeaponR
}

不能用字段来实现。我不确定是否可以使用第一个参数(对象)的占位符绑定实例函数。如果是这样,您可以使用"类绑定"std::function<int(void)>作为getChampIndex的第一个参数,将其绑定到结构的值getter(是的,这种方法需要int get_champID()等),并与冠军列表的所有成员连续调用它,将实际的冠军实例作为第一个参数传递。这至少需要C++11(不确定什么时候会出现,我在过去几个月里一直在用C++14进行编码),此外,就可读性和健壮性而言,这是一个糟糕的设计。如果你需要这个,它肯定是一个严重设计错误的代码气味。

我假设vector<string> Championsvector<CHAMPION>,因为否则整个getChampIndex就没有意义了。

您可以使用指向成员的指针将该成员传递给getChampIndex

#include <vector>
#include <algorithm>
static constexpr int EMPTY = -1;
struct CHAMPION{
    int champ_ID;
    int weaponL_ID;
    int weaponR_ID;
};
typedef int CHAMPION::*FieldPointer;
std::vector<CHAMPION> Champions;
std::vector<CHAMPION>::size_type getChampIndex(FieldPointer field, int value){
    auto const i = std::find_if( Champions.begin(), Champions.end(), [&](auto const& c) {return (c.*field) == value;} );
    // what do we do if there is no element with searched value?
    return i - Champions.begin();
}
int main(int argc, char* argv[]) {
        //fill Champions vector
    auto SearchedChamp = getChampIndex(&CHAMPION::champ_ID, 17);
    //process SearchedChamp
    auto NoWeaponL = getChampIndex(&CHAMPION::weaponL_ID, EMPTY);
    //process NoWeaponL
    auto NoWeaponR = getChampIndex(&CHAMPION::weaponR_ID, EMPTY);
    //process NoWeaponR
}

我认为结构本身的设计不是很合适,但这很难从问题描述中判断出来。如果你必须坚持设计,我可能不会使用这种技术,只使用lambda函数:

template<typename Predicate>
std::vector<CHAMPION>::size_type getChampIndex(Predicate pred){
    auto const i = std::find_if( Champions.begin(), Champions.end(), pred );
    return i - Champions.begin();
}
int main(int argc, char* argv[]) {
        //fill Champions vector
    auto SearchedChamp = getChampIndex([](CHAMPION const& c) {return c.champ_ID == 17; } );
    //process SearchedChamp
    auto NoWeaponL = getChampIndex([](CHAMPION const& c) {return c.weaponL_ID == EMPTY;} );
    //process NoWeaponL
    auto NoWeaponR = getChampIndex([](CHAMPION const& c) {return c.weaponR_ID == EMPTY;});
    //process NoWeaponR
}
相关文章: