A deep understanding of the use and characteristics of vector classes in C + + _c language

Source: Internet
Author: User
Tags array definition arrays int size memory usage
<vector>
Template < class T, class Alloc = allocator<t> > class vector;


Vectors (vector) is a sequential container (Sequence container) that encapsulates a dynamic array of sizes. As with any other type of container, it can hold various types of objects. It is simple to assume that a vector is a dynamic array that can hold any type.

The vector class provides an alternative representation of a built-in array, as in the string class the Vector class is part of the standard library introduced with standard C + +, in order to use vector we must include the associated header file:

#include <vector>


Capacitive Properties:

1. Sequential sequence

The elements in a sequential container are sorted in strict linear order. The corresponding element can be accessed by the position of the element in the sequence.

2. Dynamic array

Enables fast direct access to any element in a sequence, even through pointers. Action for adding/removing elements relatively quickly at the end of a sequence.

3. Able to perceive the memory allocator (Allocator-aware)

The container uses a memory allocator object to dynamically process its storage requirements.

Use:

Vectors are used in two different forms, the so-called array habits and STL habits.

An array of idioms
1. Defines a vector of a known length:

vector< int > Ivec (10); Similar array definition int ia[10];

Elements can be accessed by ivec[index number]

Use if (Ivec.empty ()) to determine whether it is empty, ivec.size () to determine the number of elements.

2. The vector element is initialized to the default value associated with its type: The default value for the arithmetic and pointer types is 0, and for the class type, the default value can be obtained by invoking the default constructor of this class, and we can also provide an explicit initial value for each element to complete the initialization, for example
vector< int > Ivec (10,-1);
Defines a ivec that contains 10 int elements, each of which is initialized to-1

For built-in arrays, we can explicitly initialize the elements of an array to a set of constant values, such as:

int ia[6] = {2,-1, 0, 1, 2, 1024};

Vectors cannot be explicitly initialized in the same way, but vectors can be initialized to all or part of an existing array, simply by specifying the starting address of the array to be used to initialize the vector and the next position of the last element of the array, for example:

Copy the 6 elements of IA to Ivec 
vector< int > Ivec (ia, ia+6); 

The two pointers passed to Ivec mark the range of values used to initialize the object, and the second pointer always points to the next position of the last element to be copied, and the marked element range can also be a subset of the array, for example:

Copy 3 elements ia[2], ia[3], ia[4] 
vector< int > Ivec (&ia[2], &ia[5]);


3. Different vectors with built-in arrays can be initialized by another vector or assigned to another vector such as

vector< string > Svec; 
void Init_and_assign () 
{ 
  ////Initializes a vector 
  vector< string > User_names (svec) with another vector; 
  // ... 
 
  A vector copy to another vector 
  Svec = user_names; 
}

Second, the STL idiom usage
the use of vectors in STL9 is completely different. Instead of defining a vector of known size, we define an empty vector
vector< string > text;


1. We insert elements into the vector, not indexed elements, and assign values to elements, such as the push_back () operation, which is to insert an element after the vector and the while loop reads a sequence of strings from the standard input and inserts a string into the vector at a time. In

string Word; 
while (CIN >> word) { 
text.push_back (word); 
// ... 
}

Although we can still iterate over the element with the subscript operator

cout << "Words read are: \ n"; 
 
for (int ix = 0; IX < text.size (); ++ix) 
   cout << text[IX] << '; 
 
cout << Endl; 

However, it is more typical to use the iterator returned by Begin () and end () in the vector operations set iterator
Right:

cout << "Words read are: \ n"; 
 
for (Vector<string>::iterator it = Text.begin (); 
  It!= text.end (); ++it) 
      cout << *it << '; 
 
cout << Endl 

Iterator is a class in the standard library that has the function of pointers

Copy Code code as follows:
*it;

Dereference the iterator and access the actual object it points to
Copy Code code as follows:
++it;

Move forward iterator it to point to the next element

2. Be careful not to mix these two idioms, for example, the following definition

vector< int > Ivec; 

Defines an empty vector and writes such a statement.

ivec[0] = 1024; 

Is wrong, because Ivec has not yet the first element, we can only index the element size () that already exists in the vector returns the number of elements that the vector contains.

3. Similarly when we define a vector with a given size, for example:

Vector<int> IA (10); 

Any insertion will increase the size of the vector, rather than overwrite an existing element, which may seem obvious, but the following bugs are not uncommon among beginners:

const int size = 7; 
int ia[Size] = {0, 1, 1, 2, 3, 5, 8}; 
vector< int > Ivec (size); 
 
for (int ix = 0; ix < size; ++ix) 
  Ivec.push_back (ia[ix)); 

The Ivec contains 14 elements at the end of the program, and the elements of IA are inserted from the eighth element.

Deep understanding
in a vector, all elements are stored sequentially. That is, not only can the individual elements be accessed through an iterator (iterators), but they can also be accessed by pointing to the element's pointer plus an offset. It also means that when a pointer to an element of a vector is passed to any function, the pointer can be directly considered to point to an element in an array.
The storage adjustment within the vector is automatically processed and extended or compressed on demand. In general, a vector consumes more storage space than a static array (arrays) because the additional memory is used by the future growth of the portion. Because of this, when inserting elements, vectors do not need to redistribute (reallocate) memory too frequently. The current maximum capacity can be queried by function capacity (). Additional memory can be returned to the operating system by calling the Shrink_to_fit () function.
When you increase the length of a sequence in a vector object, a memory reassignment (reallocation) occurs if the current storage limit is exceeded, that is, an array is reassigned internally, and then the elements are copied sequentially. Other insert and delete operations will modify the memory address of some elements in the sequence. In all of these cases, the iterator or reference that points to the modified part of the sequence will be invalidated. When a memory reassignment does not occur, only the iterator or reference to the element before the insertion or deletion point remains valid.

The standard library can perform different growth strategies to balance the memory usage against the performance of redistribution. However, in either case, the size of the reallocated memory must grow exponentially, so that the overall allocation of time complexity (amortized) required to insert elements one at the end of the vector is a constant value.

Memory redistribution is a high cost operation in terms of performance. If you know the number of elements before you use the vector, you can eliminate the memory redistribution by using the reserve ().

Vectors support the constant time-consuming insertion and deletion of elements at the end of a sequence. Inserting or deleting elements in the middle of a vector requires a linear time. std::d eque container performance will be much higher when it involves inserting and deleting elements only to the start or end of a sequence. The performance of the Std::list container can be much higher when it involves inserting and deleting operations anywhere in the sequence.
The algorithmic complexity (performance-related) of common operations is as follows:

    • Random access, time complexity of O (1)
    • Inserts or deletes the element at the end, the overall allocation time complexity is O (1)
    • Inserts or deletes an element elsewhere, relative to the distance from the current position to the end of the vector, time complexity O (n)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.