[C ++ Note] 7 Library vector Type, libraryvector

Source: Internet
Author: User

[C ++ Note] 7 Library vector Type, libraryvector
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, when we initialize a vector <int> from a single int value, that value might represent the vector's size or it might be an element value. similarly, if we supply exactly two int values, those values cocould be a size and an initial value, or they cocould be values for a two-element vector. we specify which meaning we intend by whether we use curly braces or parentheses:

vector<int> v1(10);  // v1 has ten elements with value 0vector<int> v2{10};  // v2 has one elements with value 10vector<int> v3(10,1);  // v3 has tem elements with vlaue 1vector<int> v4{10,1};  // v4 has two elements with values 10 and 1

When we use parentheses, we are saying that the values we supply are to be 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 re saying that, if possible, we want to list initialize the object. that is, if there is a way to use the values inside the curly braces as a list of element initializers, the class will do so. only if it is not possible to list initialize the object will 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 are list initialized; the resulting vectors have one and two elements, respectively.

On the other hand, if we use braces and there is no way to use the initializers to list initialize the object, then those values will be used to construct the object. for example, to list initialize a vector of strings, we must supply values that can be used as strings. in this case, there is 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 elementvector<string> v6("hi");  // error: can't construct a vector from a string literalvector<string> v7{10};  // v7 has ten default-initialized elementsvector<string> v8{10,"hi"};  // v8 has tem elements with value "hi"

Although we used braces on all but one of 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 an int to initialize a string, so the initializers for v7 and v8 can't be 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 values from 0 to 9, we can easily use list initialization. What if we wanted elements from 0 to 99 or 0 to 999? List initialization wocould be too unwieldy. In such cases, it is 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=0; i!= 100; ++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 when we want to create a vector where we don't know until run time how many elements the vector shocould have. 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 an unknown number of values in text.

Starting with an empty vector and adding elements at run time is distinctly different from how we use built-in arrays in C and in most other ages. in particle, if you are accustomed to using C or Java, you might should CT that it wocould be best to define the vector at its expected size. in fact, the contrary is usually the case.

Other vector Operations

In addition to push_back, vector provide only a few other operations, most of which are similar to the corresponding operations 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 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 are equal if they have the same number of elements and each element in v1 is equal to the corresponding element in v2.
<, <=,>,> = Have their normal meaning using dictionary ordering.

We access the elements of a vector the same way that we access the characters in a string: through their position in the vector. for example, we can use a range for to process all the elements in a vector:

vector<int> v{1,2,3,4,5,6,7,8,9};for(auto &i: v)  // for each element is v (note: i is a reference)    i*= i;  // square the element valuefor(auto i: v)  // for each element in v    cout<< i << " ";  // print the elementcout<<endl;

The output shocould be

1 4 9 16 25 36 49 64 81

To use size_type, we must name the type in which it is defined. A vector type always limit des 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(decltype(ivec.size()) ix= 0; ix!= 10; ++ix)    ivec[ix]= ix;  // disaster: ivec has no elements

However, it is in error: ivec is an empty vector; there are no elements to subscript! As we 've seen, the right way to write this loop is to use 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 are Known to Exist!

It is crucially important to understand that we may use the subscript operator (the [] operator) to fetch only elements that 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 an error to subscript an element that doesn't exist, but it is an error that the compiler is unlikely to detect. Instead, the value we get at run time is undefined.

Attempting to subscript elements that do not exist is, unfortunately, an extremely common and pernicious programming error. So-calledBuffer overflowErrors are the result of subscripting elements that don't exist. Such bugs are the most common cause of security problems in PC and other applications.

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.