向量的向量,从数组中分离出不同的值

Vector of vectors , Separating different values from array

本文关键字:向量 分离出 数组      更新时间:2023-10-16

>我需要从二维数组中分离值。我需要做的就是存储具有特定值的字段的所有索引。

例如,我可能有一个数组,其中包含 3 个值为 1 的单元格和 10 个值为 2 的字段。我尝试创建 1 个向量,该向量存储值 1 的所有索引,另一个向量存储值 2 的所有索引。

这是我一直在尝试编写的代码,但它似乎没有改变

void searchForGrains(Cell **tab, int _size){

storage.push_back(tab[0][0]);
Point p(0,0); // Point refers to array indexes
storage[0].points.push_back(p);
for(int i=0 ; i<_size ; ++i){
    for(int j=0 ; j<_size ; ++j){
        int counter = 0;
        for(unsigned int k=0 ; k<storage.size() ; k++){
            if(tab[i][j].value == storage[k].value){
                Point pp(i,j);
                storage[k].points.push_back(pp);
            }
            else
                counter++;
        }
            if(counter == storage.size())
                storage.push_back(tab[i][j]);
    }
}

}

我认为这是一个非常简单的逻辑错误。问题是,当您找到一个新值时,尽管您向存储向量添加了新条目,但您不会添加找到新值的点。除了你做了一个特例的 0,0 处,但你不需要这样做。试试这个

void searchForGrains(Cell **tab, int _size)
{
    for(int i=0 ; i<_size ; ++i)
    {
        for(int j=0 ; j<_size ; ++j)
        {
            int counter = 0;
            for(unsigned int k=0 ; k<storage.size() ; k++)
            {
                if(tab[i][j].value == storage[k].value)
                {
                    Point pp(i,j);
                    storage[k].points.push_back(pp);
                }
                else
                    counter++;
            }
            if(counter == storage.size())
            {
                storage.push_back(tab[i][j]);
                Point pp(i,j);
                storage[storage.size() - 1].points.push_back(pp);
            }
        }
    }
}

毫无疑问,这可以提高效率,但我认为它有效。