2012-11-21 135 views
-1

我在做這個工作嗎?我想要一個Integer作爲鍵的映射,並將struct作爲值。說我想要的對象是1,最簡單的方法是什麼?我如何檢索isIncluded的值?代碼中的最後兩行,我試過,但後來我意識到我不知道在編號的Map數組中檢索結構值的方式。C++數組中的結構

我是否需要調用cells.get(1)並將其分配給新的臨時結構以獲取其值?

/** set ups cells map. with initial state of all cells and their info*/ 
void setExcludedCells (int dimension) 
{ 
    // Sets initial state for cells 
    cellInfo getCellInfo; 
    getCellInfo.isIncluded = false; 
    getCellInfo.north = 0; 
    getCellInfo.south = 0; 
    getCellInfo.west = 0; 
    getCellInfo.east = 0; 

    for (int i = 1; i <= (pow(dimension, 2)); i++) 
    { 
     cells.put(i, getCellInfo); 
    } 
    cout << "Cells map initialized. Set [" << + cells.size() << "] cells to excluded: " << endl; 
    cells.get(getCellInfo.isIncluded); 
    cells.get(1); 
} 

的地圖,被聲明爲像這樣的私人實例變量:

struct cellInfo { 
    bool isIncluded; 
    int north; // If value is 0, that direction is not applicable (border of grid). 
    int south; 
    int west; 
    int east; 
}; 
Map<int, cellInfo> cells;  // Keeps track over included /excluded cells 
+0

「cells」的聲明是什麼? –

+0

你的意思是你想要一個'std :: map '結構嗎? – tadman

+0

它是一個私有實例變量:Map cells; –

回答

2

documentation for Map,似乎.get()返回ValueType

你會這樣使用它:

// Display item #1 
std::cout << cells.get(1).isIncluded << "\n"; 
std::cout << cells.get(1).north << "\n"; 

或者,由於查找是比較昂貴的,你可以把它複製到一個局部變量:

// Display item #1 via initialized local variable 
cellInfo ci = cells.get(1); 
std::cout << ci.isIncluded << " " << ci.north << "\n"; 

// Display item #2 via assigned-to local variable 
ci = cells.get(2); 
std::cout << ci.isIncluded << " " << ci.north << "\n"; 

我最好的建議是使用標準庫的std::map代替數據結構:

// Expensive way with multiple lookups: 
std::cout << cells[1].isIncluded << " " << cells[1].north << "\n"; 

// Cheap way with one lookup and no copies 
const cellinfo& ci(maps[1]); 
std::cout << ci.isIncluded << " " << ci.north << "\n";