"C + + considerations" 7 Library Vector Type

Source: Internet
Author: User

List Initializer or Element Count?

In a few cases, what initialization means depends upon whether we use curly braces or parentheses to pass the initializer ( s). For example if we initialize a vector< int > from a single int value, that value might represent the vector ' s Size or it might is an element value. Similarly, if we supply exactly both int values, those values could is a size and an initial value, or they could is values For a two-element vector. We specify which meaning we intend by whether we use curly braces or parentheses:

 vector<int>V1 (Ten);//V1 have ten elements with value 0 vector<int>v2{Ten};//V2 have one elements with value vector<int>V3 (Ten,1);//V3 have TEM elements with Vlaue 1 vector<int>v4{Ten,1};//V4 has both elements with values and 1

When we use parentheses, we is saying that the values we supply is to being used to construct the object. Thus, V1 and V 3 use their initializers to determine the vector's size, and its size and element values, respectively.

When we use curly braces, {...}, we ' re saying that, if possible, we want to list initialize the object. That's, if there is a-to-use the values inside the curly braces as a list of element initializers, the class would do So. Only if it isn't possible to list initialize the object would the other ways to initialize the object be considered. The values we supply when we initialize V2 and V4 can be used as element values. These objects is list initialized; The resulting vectors has one and both elements, respectively.

On the other hand, if we use braces and there is the no-use-the-initializers to list initialize the object, then those Values would be used to construct the object. For example, the to list initialize a vector of strings, we must supply values the can be used as strings. In this case, there are no confusion about whether to list initialize the elements or constructs a vector of the given size :

 vector<string>v5{"HI"};//List initialization:v5 has one element vector<string>V6 ("HI");//Error:can ' t construct a vector from a string literal vector<string>v7{Ten};//V7 has ten default-initialized elements vector<string>v8{Ten,"HI"};//V8 have TEM elements with value "HI"

Although we used braces on all but one of the these definitions, only V5 is list initialized. In order to list initialize the vector, the values inside braces must match the element type. We can ' t use a int to initialize a string, so the initializers for V7 and V8 can ' t is element initializers. If list initialization isn ' t possible, the compiler looks for other ways to initialize the object from the given values.

Adding Elements to a vector

As one example, if we need a vector with the values from 0 to 9, we can easily the use list initialization. What if we wanted elements from 0 to 0 to 999? List initialization would be too unwieldy. In such cases, it's better to create an empty vector and use a vector member named Push_back to add elements at run time.

The push_back operation takes a value and "pushes" that value as a new last element onto the ' back ' of the vector.

vector<int> v2;  // empty vectorfor(int i=0100; ++i)    v2.push_back(i);  // append sequential integers to v2// at end of loop v2 has 100 elements, values 0 ... 99

We use the same approach if we want to create a vector where we don ' t know until run time how many elements the vector s Hould. For example, we might read the input, storing the values we read in the vector:

// read words from the standard input and store them as elements in a vectorstring word;vector<string> text;  // empty vectorwhile(cin>> word)    text.push_back(word);  // append word to text

Again, we start with an initially empty vector. This time, we read and store a unknown number of values in text.

Starting with a empty vector and adding elements at run time was distinctly different from how do we use built-in arrays in C And in the most other languages. In particular, if you is accustomed to using C or Java, and you might expect that it would is best of define the vector at it s expected size. In fact, the contrary was usually the case.

Other vector Operations

In addition to push_back, vector provide-a few other operations, most of which is similar to the corresponding opera tions on strings.

Operations Notes
v.empty () Returns True if V is empty; otherwise Returns false.
v.size () Returns The number of elements in V.
v.push_back (t) Adds An element with the value T to end of V.
v[n] Returns A reference to the element at position N in v.
v1=v2 replaces the elements in V1 with a copy of the elements in V2.
v1={a,b,c ...} replaces the elements in V1 with a copy of the elements in the comma-separated list.
v1==v2,v1!=v2 v1 and v2 is equal if they has the same number of elements and each element In V1 are equal to the corresponding element in V2.
<, <=, >= have their normal meaning using dictionary ordering.

We access the elements of a vector the same is the we access the characters in a string:through their position in the V Ector. For example, we can use a range of-to-process all of the elements in a vector:

 vector<int>v{1,2,3,4,5,6,7,8,9}; for(Auto&AMP;I:V)/per element is V (note:i is a reference)i*= i;//square The element value for(AutoI:V)/per element in V    cout<< I <<" ";//Print the elementcout<<endl;

The output should be

1 4 9 16 25 36 49 64 81

To use Size_type, we must the name of the type in which it is defined. A vector type always includes its element type:

vector<int>:: size_type  // okvector::size_type  // error
subscripting Does not Add Elements

Programmers new to C + + sometimes think that subscripting a vector adds elements; It does not. The following code intends to add TEM elements to Ivec:

vector<int> ivec;  // empty vectorfor(decltype010; ++ix)    ivec[ix]= ix;  // disaster: ivec has no elements

However, it is in Error:ivec are an empty vector; There is no elements to subscript! As we ' ve seen, the right-of-the-push_back:

for(decltype(ivec.size()) ix= 0; ix!= 10; ++ix)    ivec.push_back(ix);  // ok: adds a new element with value x

The subscript operator on vector (and string) fetches an existing element; It does not add an element.

Subscript only Elements that is known to exist!

It's crucially important to understand we'll use the subscript operator (the [] operator) to fetch only elements th At actually exist. For example,

vector<int> ivec;  // empty vectorcout<< ivec[10];  // error: ivec has no elements!vector<int> ivec2(10);  // vector with ten elementscout<< ivec2[10];  // error: ivec2 has elements 0...9

It is a error to subscript a element that doesn ' t exist, but it's an error that the compiler was unlikely to detect. Instead, the value we get at run time is undefined.

Attempting to subscript elements it does not exist are, unfortunately, an extremely common and pernicious programming error . So-called buffer overflow Errors is the result of subscripting elements that don ' t exist. Such Bugs is the most common cause of security problems in PCs and other applications.

"C + + considerations" 7 Library Vector Type

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.