如下代码。

我想将向量中的元素向后移动。


  例如:
    [(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调用erasestd::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++;
    }

}


由于除了obj1时,除了递增以外不使用i==0,因此您可以编写得更简单

#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());

}

09-06 20:39