按值而不是按位置从方形向量中移除元素

Removing an element by value rather than position from a square vector

本文关键字:向量 元素 方形 位置      更新时间:2023-10-16

作为数独游戏板实现的一部分,每个正方形都有一组可能的值,以及行号和列号。

我通过一个带有可能值集合的平方向量来实现这一点,其中某些值将从可能值集合中删除,遵循数独规则(例如在相同的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;
}