Get the App
SLTechnology News&Howtos  ›  Servers  › 

STL vector usage

Shulou Source: shulou.com Published: 2022-06-03 05:45:28 10月04日 Update

Memory management in embedded development is a very important part. How to use vector efficiently can not only expand the storage space quickly, but also maximize the use of storage space, and avoid the out-of-bounds problem of C array.

Scheme

Vector provides multiple constructors

1 vector vec

Vec.reserve (10)

The default constructor does not allocate any memory space until it calls reserve (10) to allocate 10 units of storage space. If the subsequent storage space is not enough, it will reallocate a large enough memory to avoid insertion failure.

2 vector vec (10)

Add elements. The number of elements in vec is 11.

Test code

# include

Int TestVector ()

{

Int v1 [10] = {1,2,3,4,5,6,7,8,9,10}

Std::vector v2

V2.reserve (10)

For (int I = 0; I < 10; iTunes +)

{

V2.push_back (v1 [I])

}

Std::vector::iterator iter = v2.begin ()

While (iter! = v2.end ())

{

Cout

Tags: Space storage allocation elements memory units constructor maximum important insufficient number code function multiple embedded array scheme problem limit ring Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Docker Apple Xiaomi Linux