2D 矢量中的擦除行 - 分割错误



我是C++新手,现在正在学习向量。我正在尝试从 2D 矢量中删除一行,但到目前为止,我的所有尝试都导致了段数错误。这是我一直在尝试的代码段 -

vector<vector<int> > myVector;
...
vector<vector<int> >::iterator row = myVector.begin();
while(row!=myVector.end())
{
    if((*row)[0] == -1)
        myVector.erase(row);
    else
        row++;
}

myVector 是一个 2D 矢量,其中包含以下值:

 1 0
-1 1
 2 1
-1 0 ...

我需要删除第一个元素为 -1 的任何行。

我尝试使用myVector.erase(myVector.begin() + row2delete)但这也给了我一个核心转储。我做错了什么吗?谢谢你的帮助!

这是你可以做到的。在使用iterator迭代项目时,不能从vector中完全擦除该项目,同时会使iterator无效。但是,您可以myVector[i].clear(),但这不会完全删除该行。要做您想做的事,我可以建议两种方法:

vector<vector<int> > v(100); //Allocate space for 100 vectors
for(int i=0;i<100;i++)
    v[i].resize(100); //set the size of these 100 vectors to say 100 again
vector<int> indices; //This vector will store the indices of the vectors which have 1st element as -1
for(int i=0;i<v.size();i++) //iterator through vector storing vecgtors
    if(v[i].size()>0 && v[i][0]==-1) //Condition check
        indices.push_back(i); //add these indices you want to delete. *You cannot delete while looping
for(int i=0;i<indices.size();i++) //Now, delete them
    v.erase(v.begin()+indices[i]);



在这里,您必须迭代两次,这并不完全是您需要的。一种更聪明的方法是保持计数变量由 while 循环控制,这不会增加父容器的大小。您基本上在这里以非线性方式进行迭代。方法如下:

vector<vector<int> > v(100); //Allocate space for 100 vectors
for(int i=0;i<100;i++)
    v[i].resize(100); //set the size of these 100 vectors to say 100 again
int cnt=0; //Keep a counter variable
while(cnt<v.size())
{
    if(v[cnt].size()>0 && v[cnt][0]==-1)
        v.erase(v.begin()+cnt); //Do not increment count here! As the vector next comes here now after resizing
    else
        cnt++;
}
//Done!

我希望这有帮助!

您遇到的分段错误来自 .erase(( 使迭代器无效的事实。这就是为什么 erase 会返回一个迭代器,以便您可以将其用作下一个迭代器。

要删除 2-dim 向量中的行,您可以执行以下操作(我使用 std::array 在声明中获取固定大小(

std::vector<std::array<int,100>> dim2(100);
std::cout << dim2.size() << std::endl;
dim2[10][10] = 100001;
std::cout << dim2[10][10] << std::endl;
dim2.erase(dim2.begin()+9); // erase the 10th row
std::cout << dim2.size() << std::endl;
std::cout << dim2[10][10] << std::endl;

来自 http://www.cplusplus.com/reference/vector/vector/erase/

iterator erase (iterator position);

指向position及以后的迭代器、指针和引用将失效......

当你做myVector.erase(row)时,迭代器row失效,因此在下一次循环迭代中,比较/取消引用它的尝试会中断。

vector::erase() 将迭代器返回到被擦除的元素之后的元素,因此您可能希望执行row = myVector.erase(row);

你能做的最好的事情就是制作另一个 2D 向量并将所有没有 -1 作为第一个元素的元素移动到新向量,然后在移位完成后删除第一个向量。例如:-

vector<vector<int> > myVector;vector<vector<int> > myVector2;
int i=0;
while(i<myVector.size()){
    if(myVector[i][0] != -1){
        myVector2.push_back(myVector[i]);
}
return myVector2;

最新更新