如何从向量中随机删除元素&lt; vector <short>&gt;?

时间:2016-11-10 22:04:00

标签: stdvector

下面是一个Sudoku初始化程序,我试图创建一个基于用户输入的函数,擦除板上的随机元素。随机元素可以从电路板的任何部分中删除。

class cell{
    bool m_occu; //occupied is shown '.'
    int m_num;

public:
    cell() : m_occu(false), m_num(0) {}
    void setMark(const int num){m_num = num; m_occu = true;}
    bool isMarked() const { return m_occu; }
    int getNum(){ return m_num;}
    friend ostream& operator << (ostream& o, const cell& c){
        if (!c.m_occu) return o << setw(2) << '-';
        return o << setw(2) << c.m_num;
    }
};

class board {
    vector<vector <cell> >m_map;
    bool col_row;

public:
    board() {
        vector<cell> a_row(9);
        col_row = false;
for (int i = 0; i < 9; ++i)
        {
            for(int j = 0; j < 9; j++)
            {
                a_row[j].setMark(j+1);
            }
            random_shuffle(a_row.begin(), a_row.end());
            m_map.push_back(a_row);
        }
    }

    void erase(){

    }

1 个答案:

答案 0 :(得分:0)

以下是擦除功能的代码:

void erase(std::vector your_vector){
   your_vector.erase(your_vector.begin() + random(1,your_vector.size()));
}

这是随机数生成的代码:

int random(int min, int max) //range(min, max)
{
   bool first = true;
   if ( first ) 
   {  
      srand(time(NULL)); //seeding only for the first time
      first = false;
   }
   return min + rand() % (max - min);
}