【发布时间】:2014-10-15 14:54:27
【问题描述】:
我的主要问题是如何在 C++ 中轻松地将对象从一个向量交换到另一个向量。因此,将一个对象添加到一个向量并从另一个向量中删除它。
更准确地说:我正在尝试以以下方式遍历单元格网格:
- 将所有单元格添加到未知集中(并将一个起始单元格添加到已知集中)
- 将已知单元格的邻居添加到候选集中(并从未知集中删除)
- 选择候选集中具有最低值的单元格并将其添加到已知集中(并将其从候选集中删除)
- 选择这个最低的单元格并返回到第 2 步
- 如果未知集为空;退出。
草率的伪代码:
vector<Cell> knownset = vector<Cell>();
vector<Cell> unknownset = vector<Cell>();
vector<Cell> candidateset = vector<Cell>();
Cell currentCell = some_cell;
// Iterate until all cells are known
while (unknownset.size() > 0){
for each (direction in directions){
c = currentCell+direction;
// Add cell to candidate set
candidateset.push_back(c);
// Remove cell from unknown set
unknownset.remove(c);
// Search the cell with the lowest value
for each( candidate in candidateset ){
if ( candidate.value < lowestValue ){
lowestValue = candidate.value;
lowestCell = candidate;
}
}
// Remove the cell with the lowest value
knownset.push_back(lowestCell);
candidateset.remove(lowestCell);
currentCell = lowestCell;
}
}
有人对如何以这种方式轻松交换单元格有任何建议吗? (网格比较大,也欢迎大家给点性能建议)
【问题讨论】:
-
您尝试将
std::swap包含在<algorithm>中吗? -
@Caduchon:你会交换哪两个对象?