移动数组元素

时间:2011-04-13 06:58:19

标签: c++

我已经能够学到很多关于数组操作的知识,但是想知道如何在数组中移动元素,我想尝试在数组中再添加一个sot,用0初始化它转移元素。

3 个答案:

答案 0 :(得分:1)

首先我想提一下,数组中的移位元素是一个算法上很昂贵的问题:它是O(N),如果你打算经常这样做,你应该考虑使用链接列表,插入是一个O(1)操作(但是您丢失了索引功能,并且需要更多内存来存储数据)。现在代码执行你一直要求的:

#include <iterator>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int, char**) {
    vector<int> rands(5);
    generate(rands.begin(), rands.end(), rand);

    cout << "Initial array:\n";
    copy(rands.begin(), rands.end(), ostream_iterator<int>(cout, "\n"));

    vector<int> zeros(3);
    fill(zeros.begin(), zeros.end(), 0);

    vector<int>::size_type insert_position = 3, insert_count = 2;

    // Here's the actual insertion
    // insert from other collection:
    rands.insert(rands.begin() + insert_position, zeros.begin(), zeros.end());
    // insert a value into the beginning:
    rands.insert(rands.begin(), insert_count, -1);

    cout << "Initial array with inserted elements:\n";
    copy(rands.begin(), rands.end(), ostream_iterator<int>(cout, "\n"));
}

因此插入实际上是向量的一种方法。调用它会调整向量的大小,将元素复制到新的移位位置,然后将元素从其他数据结构复制到新的位置。调整向量大小还可能触发新内存块的分配,将旧元素复制到其中并删除旧数组。如果你使用c风格的数组而不是矢量,那么你自己就不必担心上述所有步骤。

答案 1 :(得分:0)

你无法用数组做到这一点。看看STL,特别是list数据集。

答案 2 :(得分:0)

假设你有一个数组:

char*  cArr = new char[20];

for(int i = 0; i < 20; ++i)
{
    cArr[i] = i;
}

如果要移动数组以在特定索引处添加内容,则必须首先设置指向旧数组的备份指针,创建新数组,然后复制数据。实际上,如果大小要改变,你必须考虑为你想做的很多数组操作做这个。

// create backup and new array one larger
char* backup = cArr;
cArr = new char[20 + 1];

// lets say you want to shift the 3rd position to the right, which in 0-indexing is 2
int shiftIndex= 2;

// copy the unshifted data from the backup to the beginning of the new array
memcpy(cArr, backup, shiftIndex);    
// copy the shifted data the the later part of the new array
memcpy(cArr + shiftIndex + 1, backup + shiftIndex, 20 - shiftIndex);

// cleanup the backup array
delete [] backup;
backup = nullptr;

现在您在cArr [shiftIndex]中未设置数据或数组中的空位。所以,这只是你能做的一个例子。 [免责声明,我没有在编译器中输入这个例子,而且我正忙着学习期中考试,所以如果有任何错误我会道歉]
无论如何,我希望这能帮到你!

供参考,请查看:memcpy