C++ vector use

1. Introduction to vector

  1. vector is a sequence container similar to an array, it can change size
  2. Like an array, a vector stores its elements in contiguous memory, which means that its elements can also be accessed with regular pointer offsets, just as efficiently as an array. But unlike arrays, the size of vectors can be allocated dynamically, and their storage is automatically resolved by the container.
  3. Essentially, vectors use a dynamically allocated array to store their elements. This array may need to allocate space, in order to increase the size of the space, when inserting new elements, which means re-allocating a new array and copying all elements into the new array. Relatively speaking, this is a time-consuming task, so the vector does not re-allocate space every time an element is added to the container.
  4. Instead, the vector container may allocate some additional storage space to accommodate possible growth, so the container may have an actual capacity larger than strictly required to store the element size. Different libraries use different strategies for balancing space usage and reallocation, but in some cases reallocation should only occur in logarithmic growth, so that inserting a single element at the end of the vector is guaranteed to be done in constant time Interpolation data within assignment degree
  5. Therefore, vector takes up more storage space, in order to gain the ability to manage storage space, and dynamically grow in an efficient way
  6. Compared with other dynamic sequence containers (deque, list and forward_list), vector is more efficient when accessing elements, and adding and removing elements at the end is relatively efficient. For other deletion and insertion operations that are not at the end, it is less efficient. Better than list and forward_list unified iterators and references

2. The use of vector

Vector is very important in practice. In practice, we only need to be familiar with common interfaces. The following lists which interfaces should be mastered.

2.1. Definition of vector (constructor)

insert image description here
insert image description here

2.2. Use of vector iterators

insert image description here

insert image description here
insert image description here
insert image description here

2.3. Vector space growth problem

insert image description here
insert image description here
insert image description here
The expansion mechanism of vector in VS (1.5 times growth)
insert image description here
The expansion mechanism of vector in g++ (2 times growth)
insert image description here
insert image description here
insert image description here

2.4. Addition, deletion, modification and query of vector

insert image description here
insert image description here
insert image description here
insert image description here

Vector iterator invalidation problem (emphasis)

The main function of the iterator is to allow the algorithm to not care about the underlying data structure. The underlying data structure is actually a pointer, or a pointer is encapsulated . For example, the iterator of vector is the original ecological pointer T*. Therefore, the invalidation of the iterator actually means that the space pointed to by the corresponding pointer at the bottom of the iterator is destroyed, and a piece of space that has been released is used, resulting in a program crash (that is, if you continue to use the invalid iterator, the program may crash. ).

The operations that may invalidate its iterators for vector are:

  1. Operations that cause changes in the underlying space may cause the iterator to fail, such as: resize, reserve, insert, assign, push_back, etc.
#include <iostream>
using namespace std;
#include <vector>
int main()
{
    
    
    vector<int> v{
    
     1,2,3,4,5,6 };
    auto it = v.begin();
    // 将有效元素个数增加到100个,多出的位置使用8填充,操作期间底层会扩容
    // v.resize(100, 8);
    // reserve的作用就是改变扩容大小但不改变有效元素个数,操作期间可能会引起底层容量改变
    // v.reserve(100);
    // 插入元素期间,可能会引起扩容,而导致原空间被释放
    // v.insert(v.begin(), 0);
    // v.push_back(8);
    // 给vector重新赋值,可能会引起底层容量改变
    v.assign(100, 8);
    /*
    出错原因:以上操作,都有可能会导致vector扩容,也就是说vector底层原理旧空间被释放掉,
    而在打印时,it还使用的是释放之间的旧空间,在对it迭代器操作时,实际操作的是一块已经被释放的
    空间,而引起代码运行时崩溃。
    解决方式:在以上操作完成之后,如果想要继续通过迭代器操作vector中的元素,只需给it重新
    赋值即可。
    */
    while (it != v.end())
    {
    
    
        cout << *it << " ";
        ++it;
    }
    cout << endl;
    return 0;
}
  1. The deletion operation of the element at the specified position –erase

#include <iostream>
using namespace std;
#include <vector>
int main()
{
    
    
    int a[] = {
    
     1, 2, 3, 4 };
    vector<int> v(a, a + sizeof(a) / sizeof(int));
    // 使用find查找3所在位置的iterator
    vector<int>::iterator pos = find(v.begin(), v.end(), 3);
    // 删除pos位置的数据,导致pos迭代器失效。
    v.erase(pos);
    cout << *pos << endl; // 此处会导致非法访问
    return 0;
}

After erase deletes the element at position pos, the element after position pos will move forward without causing any change in the underlying space. Theoretically speaking, the iterator should not fail, but: if pos happens to be the last element, after deletion, pos happens to be end position, and the end position has no elements, then pos will be invalid. Therefore, when deleting an element at any position in the vector, VS considers that the iterator at that position is invalid.

  1. Note: Under Linux, the g++ compiler is not very strict in the detection of iterator failure, and the processing is not as extreme as that of vs.
    insert image description here
    insert image description here
    insert image description here
    insert image description here
    An error will be reported in VS

g++
insert image description here
insert image description here
[first array]
insert image description here
[second array]
insert image description here

  1. Similar to vector, the iterator of string will also be invalid after insertion + expansion operation + erase

insert image description here

Solution to iterator invalidation: Just reassign the iterator before using it.

Guess you like

Origin blog.csdn.net/zxj20041003/article/details/130714412