按值而不是按位置从方形向量中移除元素
Removing an element by value rather than position from a square vector
作为数独游戏板实现的一部分,每个正方形都有一组可能的值,以及行号和列号。
我通过一个带有可能值集合的平方向量来实现这一点,其中某些值将从可能值集合中删除,遵循数独规则(例如在相同的x和y值中,或者在相同的子平方中)
我遇到的问题是我不知道如何从集合中删除一个特定的值,我把它设置成这样:
vector< vector< std::set <int> > > gameboard;
. .这里的Double for循环循环遍历网格…
int removeValue = *gameboard[x][y].begin();
gameboard[x][y].erase(removeValue);
但是我很确定这只是在向量中移除任何位置的值,这不是我想要的。什么好主意吗?
从集合中删除值的语法看起来不错。但是,我认为你没有得到正确的值。
int removeValue = *gameboard[3][3].begin();
std::set<int> &rSquare = gameboard[3][3]; // get the set
std::set<int>::iterator iter = rSquare.begin(); // get an iterator
int first_possibility = *iter; // retrieve first possibility in set
当你想从一个集合中删除一个特定的值时,你已经知道你想要删除的值。你只需要这样做,就像你给的第二行一样。
gameboard[x][y].erase(removeValue);
下面是创建9x9网格,初始化所有可能性,然后删除特定可能性的完整工作演示:
#include <iostream>
#include <vector>
#include <set>
std::set<int> initialize_square(){
std::set<int> all;
for (int value = 1; value <= 9; ++value)
all.insert(value);
return all;
}
int main()
{
std::vector< std::vector< std::set <int> > > gameboard;
gameboard.resize(9);
for (int x = 0; x < 9; ++x){
gameboard[x].resize(9);
for (int y = 0; y < 9; ++y){
gameboard[x][y] = initialize_square();
}
}
std::set<int> &possibilities = gameboard[3][3];
std::cout << "possibilities before removing '5' are: ";
for (int n : possibilities)
std::cout << n << ", ";
std::cout << std::endl;
// remove 5 from a specific cell
// I would use possibilities.erase but this proves your syntax was good
int value_to_remove = 5;
gameboard[3][3].erase(value_to_remove);
std::cout << "possibilities after removing '5' are: ";
for (int n : possibilities)
std::cout << n << ", ";
std::cout << std::endl;
}
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C