Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Vector to implement a dynamic Array in C++

Shulou Source: shulou.com Published: 2022-05-31 22:39:33 09月16日 Update

This article introduces the knowledge of "how to use Vector to achieve a dynamic array in C++". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The use of Vector in C++

The header file # include needs to use the std namespace using namespace std;. The following usage takes the int data type as an example. You can customize the data type when using it. Note: the interval below is left closed and right open.

1. Define (initialize) Vector

Vector v; create an empty vector vector v (5); create a vector with 5 vector v (5) elements; create a vector vector v2 (v1) with 5 elements and a value of 10 for each element; copy another vector to make v2 equal to v1 vector v (begin,end); copy elements from another array in the [begin,end) interval to vector

Int a [] = {2, 4, 4, 6, 8, 10, vector v (& a [1], & a [3])

two。 Add elements to Vector

V.push_back (x) adds an element to the tail x v.insert (pos,x) adds an element x before the pos address points to the element

V.insert (v.begin (), 666); / / insert element 666v.insert (v.begin () + 1666) before the first element; / / insert element 666 before the second element

V.insert (v.begin (), 3666); / / insert 3 elements before the first element

V.insert (pos,first,last) inserts data between another vector of the same type [first,last) in front of the pos address pointing to the element

V.insert (v.begin (), v2.begin (), v2.end ()); / / before inserting all elements of v2 into v1

3. Delete elements in Vector

V.pop_back () deletes the last element in the vector

V.clear () clears all elements in the vector

V.erase (v.begin ()); / / Delete the first element

V.erase (first,last): delete elements in [first,last) in a vector

V.erase (v.begin () + 1je v.end ()-1); / / Delete the element from the second to the last

4. Traversing elements in Vector

V [I] Direct access to the element v.at (pos) in Vector returns the value of the pos location element pos subscript starts at 0 (similar to an array)

V.begin () returns the vector header pointer, points to the first element v.end (), returns the vector tail pointer, points to the next position of the last element of the vector, v.rbegin () reverse iterator, and points to the last element.

V.rend () reverse iterator, pointing to the position before the first element

/ / iterate directly through the element for (int item0sidi

Tags: Elements vectors points iterations arrays types categories numbers locations addresses data dynamic maximum same content interval pointers quantities methods more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information NVidia Apple Linux OPPO Reno