STL program design practice 1: Carefully use the subscript operator

zhaozj2021-02-11  251

STL program design practice 1: Carefully use the subscript operator

STL is a very important position, and some containers support the same subscript operator like an array, allowing it to access as convenient to array, but also exists, such as vector and dual-end queues. So be careful in your application. for example:

Vector NVEC (10, 7); // Define the integrated vector of 7 size 10

INT n = nVEC [0]; // Get the first element of the vector

Deque NDEQ (1,0); // Define a shaped double-end queue

NDEQ [0] = 7; // Modify the element

NDEQ [1] = 8; // Add element

INT Ni = NDEQ [1]; // Access the second element of the double-end queue

Ni = NDEQ [2]; // Access the third element of the double-end queue

There is no problem when compiling this code. However, it is very clear that the last value of Ni is as uncertain as the array, this is not wrong because the memory allocation of the STL is dynamic, it is allocated at a time, 4K is 4K under Windows (this There is a relationship with the operating system), but if the debugger is too large, it will be illegally accessed. This is because it is caused by off -ral access, so it must pay attention to check whether it is in the application.

The image container in the STL also supports the subscript operation, but there is a difference between the two-end queue.

Map D;

D [1] = 9;

Cout << D.Size () << endl; // output is 1

INT DD = D [2];

Cout << D.size () << endl; // output is 2

This means that when you use the subscript operation to access the image, if the object to be accessed does not exist, the image is added to the image, but the value of its storage object is related to the implementation. So this kind of situation is accidentally occurring in the application, it is likely to cause an incorrect error.

The rush of the article, there is a typison or error, please pay more. Thank you for your trip, I am grateful, welcome to communicate with you (- Yuan Kai ----).

转载请注明原文地址:https://www.9cbs.com/read-5596.html

New Post(0)