-1

我这样做对吗,我想要一个以 Integer 作为键,以 struct 作为值的映射。什么是最简单的方法,比如说我想要1. 如何检索 的值isIncluded?代码中的最后两行,我试过这样做,但后来我意识到我真的不知道在编号的 Map 数组中检索结构值的方法是什么。

我是否需要调用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);
}

Map 被声明为私有实例变量,如下所示:

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
4

1 回答 1

2

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";
于 2012-11-21T17:49:12.997 回答