C + + Vector Usage Summary

Source: Internet
Author: User

1. size of the vector object

The empty and size operations are similar to the related operations of type string (Section 3.2.3). The member function size returns the value of the size_type defined by the corresponding vector class.

When you use the Size_type type, you must indicate where the type is defined. The vector type always includes the element type of the vector:

Vector<int>::size_type//OK

Vector::size_type//Error

2. Adding elements to vectors

The push_back () operation takes an element value and adds it to the back of the vector object as a new element, that is, "insert (push)" to the "back" of the vector object:

Read words from the standard input and store them as elements in a vector

string Word;

vector<string> text; Empty vector

while (CIN >> word) {

text. push_back  (word); Append Word to Text

}

The loop reads a series of string objects from the standard input, appending them to the back of the vector object. First, define an empty vector object text. A new element is added to the vector object once per loop, and the word value read from the input is assigned to the element. When the loop ends, the text contains all the elements that are read in.

3. Vector subscript operation

Objects in the vector are not named and can be accessed by the position of the objects in the vector. You typically use the subscript operator to get an element. The subscript operation of a vector is similar to a string-type subscript operation (3.2.3 section).

The Vector's subscript operator takes a value and returns the element at that corresponding position in the vector. The position of the vector element starts from 0. The following example uses a for loop to reset each element value in the vector to 0:

Reset the elements in the vector to zero

for (Vector<int>::size_type IX = 0; IX! = Ivec.size (); ++ix)

Ivec[ix] = 0;

Like the string subscript operator, the vector subscript operation results in an lvalue, so the write can be implemented as it did in the loop body. In addition, similar to the subscript operation of a String object, the Size_type type is used as the type of vector subscript.

In the example above, the for loop will execute correctly even if Ivec is empty. Ivec is empty, call size returns 0, and the test in for is compared with IX and 0. When the first loop occurs, the condition test fails and the For loop body does not execute once because IX itself is 0.

Key concepts: secure Generic programming

A C + + programmer accustomed to C or Java programming may find it difficult to understand that the for loop judgment condition uses! = instead of < to test whether the vector subscript value is out of bounds. C programmers are hard to understand also, the previous example did not call the size member function and save its return value before the for loop, but instead called the size member function in the For statement header.

C + + programmers are accustomed to using! = rather than < to write loop-judging conditions. In the above example, there is no particular reason for choosing or not to use an operator. After learning the generic programming of the second part of this book, you will understand the rationality of this habit.

Calling the size member function without saving the value it returns is also not required in this example, but it reflects a good programming habit. In C + +, some data structures, such as vectors, can grow dynamically. In the example above, the loop only needs to read the elements without adding new elements. However, the loop can easily add new elements, and if you do add new elements, then it is problematic to test the saved size value as the end condition of the loop because the newly added element is not counted. So we tend to test the current value of size in each loop instead of storing a copy of the size value when entering the loop.

We will learn in the 7th chapter that some functions in C + + can be declared as inline (inline) functions. Instead of making actual function calls, the compiler expands the code directly when it encounters an inline function. A small library function like size is almost defined as an inline function, so the cost of invoking it at the time of each loop is relatively small.

4. Subscript operation does not add elements

Novice C + + programmers may think that vector subscript operations can add elements, but not:

Vector<int> Ivec; Empty vector

for (Vector<int>::size_type IX = 0; IX! = ten; ++ix)

Ivec[ix] = IX; Disaster:ivec has no elements

The above program attempts to insert 10 new elements into the Ivec, with the element values sequentially from 0 to 9 integers. However, here Ivec is an empty vector object, and the subscript can only be used to get an existing element.

The correct notation for this loop should be:

for (Vector<int>::size_type IX = 0; IX! = ten; ++ix)

Ivec.push_back (ix); Ok:adds new element with value IX

Must be an existing element to be indexed with the subscript operator. When you assign a value by using the subscript operation, no element is added.

Warning: Subscript can only be done for elements that are known to exist

It is important to use the subscript operator ([] operator) to extract only elements that do exist, such as:

Vector<int> Ivec; Empty vector

cout << ivec[0]; Error:ivec has no elements!

Vector<int> IVEC2 (10); Vector with ten elements

cout << ivec[10]; Error:ivec has elements 0...9

Attempting to get an element that does not exist inevitably produces a run-time error. As with most similar errors, there is no guarantee that the execution process can catch such errors, and the result of running the program is indeterminate. Because the result of a non-existent element is undefined, different implementations result in different results, but the program will almost certainly fail in some interesting way when it runs.

This warning applies to any use of subscript operations, such as the subscript operation of type String, and the subscript operation of the built-in array that will be briefly described.

Unfortunately, trying to subscript non-existent elements is a serious mistake that is often made during programming. The so-called "buffer Overflow" error is the result of subscript operations on non-existent elements. Such defects often lead to the most common security issues in PCs and other applications.

C + + Vector Usage Summary

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.