使用 std:sort 在本地排序
Using std:sort to sort locally
我正在制作一个Soduku求解器,所以我需要测试行,列和正方形的合法性。我有每个功能要做。
bool Board::isRowLegal(int row){
sort(theBoard[row].begin(), theBoard[row].end());
for(int i = 1; i < theBoard[row].size() - 1; ++i){
if(theBoard[row][i] != 0){
if(theBoard[row][i] == theBoard[row][i + 1]){
return false;
}
}
}
return true;
}
bool Board::isColumnLegal(int column){
vector<int> currentColumn;
int current = 0;
for(int i = 1; i < theBoard.size(); ++i){
currentColumn.push_back(theBoard[i][column]);
}
sort(currentColumn.begin(), currentColumn.end());
for(int j = 0; j < currentColumn.size() - 1; ++j){
if(currentColumn[j] != 0){
if(currentColumn[j] == currentColumn[j + 1]){
return false;
}
}
}
return true;
}
bool Board::isPanelLegal(int rowStart, int colStart){
vector<int> currentPanel;
for(int i = rowStart; i < rowStart + THREE; ++i){
for(int j = colStart; j < colStart + THREE; ++j){
currentPanel.push_back(theBoard[i][j]);
}
}
sort(currentPanel.begin(), currentPanel.end());
for(int k = 0; k < currentPanel.size() - 1; ++k){
if(currentPanel[k] != ZERO){
if(currentPanel[k] == currentPanel[k + 1]){
return false;
}
}
}
return true;
}
我对电路板进行排序,以便可以测试重复项。当我的程序命中isColumnLegal
函数时,我遇到了问题。似乎板的向量已经与其行相对应进行了排序,这意味着我的列函数无法检测到列的合法性,因为这些行不再对应。所以我的问题是,有没有办法使用 std::sort
函数并在本地排序,而无需将vector
复制到另一个vector
?可以想象,这个程序已经效率低下了,我不想再通过复制向量来制作它了。我知道这只是 10 x 10 vector
的int
但仍然如此。
创建一个包含 9 个bool
元素的数组,初始化为 false。 遍历向量,将找到的任何数字的索引(减一)设置为 true。 如果在此过程中遇到已设置为 true 的元素,则该行无效。
bool present[9] = {};
for (auto const i : theBoard[row])
{
if (i != 0)
{
if (present[i-1])
return false;
present[i-1] = true;
}
}
return true;
相关文章:
- 对字符串进行排序时,在c++中处理sort()
- std::sort()函数无法对向量的一部分进行排序
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 按字母顺序对字符串中的字母进行排序,而无需使用内置的 sort()
- 使用 std::sort 对向量进行稳定排序
- 如何使用 QSortFilterProxyModel::sort 对 Qlist 中的数据进行排序
- 使用 std::sort 对二维 c 数组进行排序
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- std::vector 未按 std::sort 的预期排序
- 通过 std::sort 对 C 2D 数组进行排序
- 对整个范围进行排序时,std::p artial_sort() 与 std::sort() 的性能?
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 使用 std::sort 对矩阵进行排序
- 使用c 中的sort()函数对字符串进行排序的最坏情况是什么是什么
- 为什么用std :: sort()对上升阵列(1〜100,000)排序比仅使用100,000次使用的速度要快
- 如何在 c++ 中使用 sort() 对向量进行排序
- 如何使用 std::sort 以'custom'的方式就地对数组进行排序
- 如何使用 std::sort 对数组中的特定对象进行排序
- 在STD中崩溃:: Sort-分类而没有严格的弱排序
- 我们如何在 c++ 中使用 std::sort 对 2D 字符串数组进行排序