2D 矢量中的擦除行 - 分割错误
Erasing row in 2D Vector - segmentation error
我是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;
- C++映射分割错误(核心转储)
- 由cin中的字符串中未捕获空白引起的分割错误
- 删除映射和分割错误中的一个过去结束元素
- 在指向函数中读取变量时出现分割错误
- 在链表中的第 n 位插入显示分割错误
- 较高值 n 的分割错误(例如 n=999997)
- 尝试通过memcpy复制大尺寸浮点向量时的分割错误
- 分割错误:向量中的擦除功能
- 向量向量的分割错误
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- C ++分割错误,为什么使用"long long"我没有得到答案?
- 在尝试使用递归查找集合子集的总数时,我遇到了分割错误
- 分割错误 11:尝试使用 cin 输入 B[1] 时
- 集合布局上的 Qt 分割错误
- 高达20亿的筛子会产生分割错误
- 对向量使用推回函数时的分割错误
- 绘制精灵会导致分割错误
- 将矢量的整数内容打印为字符串会导致分割错误
- 分割错误:使用向量时为 11 c++
- 结构的分割错误错误