0

如以下代码。

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

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

}
4

1 回答 1

3

调用push_backorerase可能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++;
    }

}

由于obj1除了 when 之外没有使用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());

}
于 2016-05-12T05:38:31.943 回答