作为以下代码。
我想把向量中的元素移到后面。
例如:[(1),2,3,4]->[2,3,4,(1)]
但是,它会导致双自由问题。这段代码中的逻辑很简单。
我想我滥用了擦除功能。这是真的吗?有人能告诉我细节吗?
谢谢你的阅读。
这是输出:
*** Error in '/home/ubuntu/workspace/hello-cpp-world.cc.o': double free or corruption (out): 0x00000000016ffca0 ***
这是代码片段:
#include <iostream>
#include <vector>
int main() {
std::vector<int*> targets;
int* a = new int;
*a = 1;
int* b = new int;
*b = 2;
targets.push_back(a);
targets.push_back(b);
int i =0;
for (std::vector<int*>::iterator obj1 = targets.begin(); obj1 != targets.end(); i++)
{
if(i==0)
{
int* tmp = *obj1;
targets.push_back(tmp);
targets.erase(obj1);
}
else obj1++;
}
}
调用push_back
或erase
到std::vector
可能会使迭代器无效。使用索引更容易。
#include <iostream>
#include <vector>
int main() {
std::vector<int*> targets;
int* a = new int;
*a = 1;
int* b = new int;
*b = 2;
targets.push_back(a);
targets.push_back(b);
int i =0;
for(size_t obj1 = 0; obj1 < targets.size(); i++)
{
if(i==0)
{
int* tmp = targets[obj1];
targets.push_back(tmp);
targets.erase(targets.begin() + obj1);
}
else obj1++;
}
}
由于除了i==0
之外,obj1
不用于递增,因此可以更简单地编写
#include <iostream>
#include <vector>
int main() {
std::vector<int*> targets;
int* a = new int;
*a = 1;
int* b = new int;
*b = 2;
targets.push_back(a);
targets.push_back(b);
int* tmp = targets[0];
targets.push_back(tmp);
targets.erase(targets.begin());
}