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

时间:2016-11-03 16:53:37

标签: c++ sudoku

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

我通过一个带有可能值集的方形向量来做到这一点,其中某些值将从可能值的集合中删除,遵守数独的规则(例如,在相同的x和y值中,或者在相同的子方)

我遇到的问题是我不知道如何从集合中删除特定值,我设置如下:

 vector< vector< std::set <int> > > gameboard;

..在这里循环加倍循环...

 int removeValue = *gameboard[x][y].begin();


 gameboard[x][y].erase(removeValue); 

但是我很确定只是在向量中的任何位置移除值,这不是我想要的。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

从集合中删除值的语法看起来不错。但是,我认为你没有得到正确的价值。

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;
}
相关问题