关于数组:什么C ++数据结构可以处理类似于Java ArrayList的’insert’?

What C++ data structure can handle 'insert' similar to a Java ArrayList?

我正在尝试将Java项目转换成C++项目。在Java项目中,我使用了一个ARARYLIST,但我不知道处理C++中所做的最好的方法。

目前我使用的是std::vector,因为它允许在任意位置访问元素,而且它有一个insert方法。像Java ARAYLIST一样,我希望能够在向量中的某个位置(int p)插入一个元素,并且元素当前在p(如果有的话)转移到p+ 1。随后的元素也会被移动。

std::vector.insert用于单个条目,如下所示:

1
iterator insert (iterator position, const value_type& val);

以及http://www.cplusplus.com/reference/vector/vector/insert/中的描述。

Because vectors use an array as their underlying storage, inserting elements in
positions other than the vector end causes the container to relocate all
the elements that were after position to their new positions.

这是否意味着insert实际上将新元素放在p+1,而不是p?它是否也不会移动当前位于p的元素?

另外,为什么insert方法采用迭代器而不是数字索引?我看不出有什么优势。它只会使插入到任意位置更加困难。有没有什么方法可以构造一个迭代器在一个特定的位置而不必在那里迭代?我只在http://www.cplusplus.com/reference/iterator/randomaccessiterator上看到比较。/


矢量做的正是你需要的,但是边界条件有点不同。

给它的迭代器指向要在前面插入的元素。

在其他wirds中,如果向它传递指向第一个元素的迭代器,那么它将在向量的开头插入新元素,并将第一个元素推到第二个位置。

Also, why does the insert method take in an iterator instead of just a number index? I don't see the advantage. It just makes it more difficult to insert at arbitrary positions. Is there some way to construct an iterator to be at a specific location without having to iterate there?

为什么更难?

要获取指向第17个元素的迭代器,请执行以下操作:

1
vec.begin() + 17;

我不知道"必须在那里迭代"是什么意思,但是您不需要将迭代器增加17倍。