2016-07-22 113 views
-4

我想將一個結構類型傳遞給一個函數,然後這個函數將遍歷這些結構的向量來檢查一個條件。無論如何,這是可能的嗎?傳遞一個類型的結構C++

#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 

} 
+0

搜索關於查找向量中的元素的問題。 – juanchopanza

+0

提供的(僞)代碼沒有任何意義。 – Arunmu

+0

這個問題寫得很差。但是,似乎你正試圖訪問一個結構的單個成員。如果是這樣,有一種方法。 – zeb

回答

0

你不能在字段中做到這一點。我不確定是否可以使用佔位符爲第一個參數(對象)綁定實例函數。如果是這樣,你可以使用「分類綁定」std::function<int(void)>作爲getChampIndex的第一個參數,將它綁定到你的結構的值getters(是的,這種方法需要int get_champID()等),並連續調用它與冠軍列表的所有成員,傳遞實際的冠軍實例作爲第一個參數。 這應該至少需要C++ 11(不知道在過去幾個月裏我用C++ 14進行編碼時會得到什麼),而且在可讀性和健壯性方面這是可怕的設計。如果你需要這個,這絕對是一個嚴重的設計錯誤的代碼氣味。

0

我假設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 
}