我假設vector<string> Champions
是vector<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
}
搜索關於查找向量中的元素的問題。 – juanchopanza
提供的(僞)代碼沒有任何意義。 – Arunmu
這個問題寫得很差。但是,似乎你正試圖訪問一個結構的單個成員。如果是這樣,有一種方法。 – zeb