Regression season--c++ STL vector

Source: Internet
Author: User

Bloggers began to leave the ACM Army a few years ago, so far it has taken a few days to improve the environment. The recent regression Program Ape Army, found that code force plummeted, has not been a night before the OJ of the program ape Preparation army. Has now become a code slag slag. This is a new beginning to write a blog, the new strength of code. will continue to learn the process of updating out, I hope that the code force to recover t_t early.

Recently Brush Leetcode, only to find the original in the brush ACM, with a lot of C instead of STL practices in the Leetcode implementation is not convenient, so the bitter taste. From a long time ago do not want to learn the STL began to start, have heard that STL is a good thing, just used to write C, will not bother to learn C + + things. Now that you want to study hard, just study it and see if you can appreciate the greatness of STL.

Bloggers learn things more and more, will not scrupulous the introduction of the concept of anything, usually think of what to test what, and then put the conclusion. Of course, if there is a new concept will be elaborated. The main purpose of the blog is to make notes for themselves to remind.

All right, it's officially started.


Vector, Chinese is the "vector", how difficult to understand the name, vectors is clearly the concept of geometry, okay? Before the vector or foggy, listen to the students bragging about using vectors to do the storage, really worship a, in fact, this thing is an array of plainly. But it's a little bit special that vectors can do arrays of various data types, depending on your definition. Like what:

Vector<int>vector<string>vector<struct a>vector< vector<int> >//Note that there are spaces between the last two >

Example:

#include <cstdio> #include <iostream> #include <vector> #include <string>using namespace std; struct A{int a;int B;char c;}; void Test () {vector<int> a;//cout << a.at (+) << Endl;//When the index is greater than the range, it w Ould Show Error.for (int i = 0; i <, i + +) {a.push_back (i); cout << a[i];} cout << endl;vector<int> b;for (int i = 1; i < +, i + +) {B.push_back (i + 1);} cout << (A = = b) << Endl; Tow vectorstruct a bb;bb.a = 1;bb.b = 2;BB.C = ' c '; vector<struct a> strctv;strctv.push_back (BB); cout << (St RCTV[0].A = = strctv[1].b); string str1, Str2;str1 = "ABCD"; str2 = "Zyxw";vector<string> vs;vs.push_back (STR1); Vs.push_back (str2) cout << vs[0] << vs[1] << endl;vector<vector<int> > Vv;vv.push_back (A ); Vv.push_back (b); cout << vv[0][0] << vv[1][1] << Endl;} int main (void) {test (); return 0;}

Simple assignment and output code show that vectors can be loaded in various types. As well as the vector variable can be done = =,! =, <=, >=, <, > Operations. However, if the vector contains structs, these operators need to be overloaded.

It is important to note that vectors can be used as almost all types of containers, but only one type can be found in a single container. For example, Bo Master originally wanted to do vector<vector>, the result mercilessly was error.


Once you know how to define it, let's say a few simple operations, assignment, invocation, and state based on the example above.

Assignment value:

1, assign (int num, TYPE val); Assign (input_iterator start, Input_iterator end);

After a vector has been defined or used for a period of time, the contents of the previous vector are emptied, and the assign is re-assigned with a value of NUM, which is the Val of type.

Vector<int> Vi;vi.assign (12, 1);//At this time, the content of VI is {1,1,1,1,1...,1}
There is another form, as below, that can be done with the same result.

Vector<int> Vi2 (12, 1);

So, assign is a good initialization function, just because it's just the same thing, so it might not be particularly useful.

The Assign function also has another overloaded assign (input_iterator start, Input_iterator end), which means that another vector is assigned a section of a vector with the iterator of the other vector.

Give an example:

void Test1 () {vector<int> vi;for (int i = 0; i <; i++) {vi.push_back (i);} for (int i = 0; i < i++) {cout << vi[i];} cout << Endl;std::vector<int>::iterator it;it = vi.begin () + 3;vector<int> vi2;vi2.assign (it, Vi.end ( )-3); Std::vector<int>::iterator it2;for (it2 = Vi2.begin (); It2! = Vi2.end (); it2++) {cout << *it2;} cout << endl;<span style= "White-space:pre" ></span>vi.assign (Vi.begin () + 3, Vi.end ()-3); <span Style= "White-space:pre" ></span>for (it2 = Vi2.begin (); It2! = Vi2.end (); it2++) {<span style= "White-space: Pre "></span>cout << *it2;<span style=" White-space:pre "></span>}<span style=" White-space:pre "></span>cout << Endl;}
The output is:

01234567891011345678345678

The first 3 values are removed because the iterator it = Vi.begin () +3, and the second parameter of assign is also Vi.end ()-3. This means that the assign iterator is flexible enough to be used as a parameter directly from the vector instance's begin (), end (), or by an iterator variable. Let's pay attention to the third output, this is VI using assign action on their own. In other words, you can use assign () to continuously reduce the vector itself.

In fact, when the vector is defined, the vector's constructor can accomplish almost the same function as assign. The main forms are as follows four kinds:

(1) vector ()

(2) vector (size_type n, const type &V);

(3) vector (const vector &from)

(4) vector (input_iterator start, Input_iterator end);

Vector<int> first;                                Empty Vector vector<int> second (1);                       12 1vector<int> Third (Second.begin (), Second.end ());  The same thirdvector<int> fourth (third) is obtained by the iterator and second;                       Initialize fourth directly with third

2, Push_back (), Pop_back ().

The two are paired, so together, the void push_back (const type val) is added at the end of the vector to a type of element with a value of Val (the type must be a vector containing the types). void Pop_back () removes the last element of the vector, noting that there is no return value for this place.

Example:

void Test2 () {vector<int> vi;std::vector<int>::iterator it;for (int i = 0; i <; i++) {vi.push_back (i);} for (it = Vi.begin (); It! = Vi.end (); it++) {cout << *it;} cout << endl;for (int i = 0; i < ten; i++) {Vi.pop_back ();} for (it = Vi.begin (); It! = Vi.end (); it++) {cout << *it;} cout << Endl;}

Output Result:

0123456789101101
Push_back () 12 times, Pop_back () 10 times, so the last two values are left.

3. Insert ()

Insert () has three main forms: (1) iterator insert (Iteartor loc, const TYPE &val); (2) void Insert (iterator loc, Size_type num, Cost_type &val); (3) void Insert (Iterator loc, input_iterator start, Input_iterator end);

(1) In the location where the Loc iterator is located, insert a single value Val and return the iterator where the value is located.

(2) Insert a value of type num at LOC location Val;

(3) in the LOC position, insert the value between the iterator start to end.

Example:

void Test3 () {vector<int> vi;std::vector<int>::iterator it;for (int i = 0; i <; i++) {vi.push_back (i);} for (it = Vi.begin (); It! = Vi.end (); it++) {cout << *it << "";} cout << endl;cout << *vi.insert (Vi.begin (), +) << Endl;; Vi.insert (Vi.begin () + 4, $); for (it = Vi.begin (); It! = Vi.end (); it++) {cout << *it << "";} cout << Endl;vi.insert (Vi.begin (), Vi.begin (), Vi.end ()); for (it = Vi.begin (); It! = Vi.end (); it++) {cout << * It << "";} cout << Endl;}
Output Result:

0 1 2 3 4 5 6 7 8 9 10 11 100100 0 1 2 3 4 5 6 7 8 200 200 200 200 9 10 11 100 0 1 2 3 4 5 6 7 8 200 200 200 200 9 10 11 1 00 0 1 2 3 4 5 6 7 8 200 200 200 200 9 10 11

Seems very well understood.

Call:

The call of the vector seems to be very useful, as the most open said that the vector is actually an array, so you can directly use the array call form to do.

For example: A[0], a[1], a[2], so.

at (int index):

Another form is to use the at (int index) function to directly access the contents of the vector's index mini-tag.

So a[0] is equivalent to a.at (0). The difference is that if you go out of bounds, the at () function returns an error, and [0] does not return an error.


(1) Front (), Back ()

This is a function of two return values, each of which returns a reference to the elements within the first and last vector.

Example:

void Test4 () {vector<int> VI (ten, 1); Std::vector<int>::iterator It;int i = 0;for (it = Vi.begin (); It! = Vi.end ( ); It + +) {*it = i++;cout << *it << "";} cout << endl;cout << "front:" << vi.front () << endl;cout << "back:" << vi.back () < ;< Endl;vi.front () + = 10;vi.back ()-= 10;for (it = Vi.begin (); It! = Vi.end (); it + +) {cout << *it << "";} cout << Endl;}

Output Result:

void Test4 () {vector<int> VI (ten, 1); Std::vector<int>::iterator It;int i = 0;for (it = Vi.begin (); It! = Vi.end ( ); It + +) {*it = i++;cout << *it << "";} cout << endl;cout << "front:" << vi.front () << endl;cout << "back:" << vi.back () < ;< Endl;vi.front () + = 10;vi.back ()-= 10;for (it = Vi.begin (); It! = Vi.end (); it + +) {cout << *it << "";} cout << Endl;}


(2) Iterator iterator

Iterators are something I've been having a headache with since I contacted STL, because the name is too long = ... Unexpectedly today in the collation of the front content, gradually has been the use of iterator straightened out.

Iterator you can actually think of as a traversal tool. It's kind of like a pointer, specifying a location in the container, traversing the next through + +. is a very useful tool, in the STL has a lot of function return values and parameters are also used iterator type, convenient for us to operate. So I'm going to introduce it with the basic iterator function.

Definition: Std::vector<int>::iterator it; The name is very long, but it is not difficult to remember that STD is namespace;vector<int> is the type of container that the iterator corresponds to, and the type of container it is to manipulate must be the same; iterator is the English of fixed iterators; it is the variable name of the iterator.

(2.1) Begin (), End ():

These functions return iterators at the position of the beginning element of the vector and at the location of the end element.


Give an example:

<span style= "White-space:pre" ></span>vector<int> VI (1); std::vector<int>::iterator it; int i = 0;for (it = Vi.begin (); It! = Vi.end (); it + +) {*it = i++;cout << *it << "";}
The corresponding has this other pair of functions rbegin (), rend (): They will return a reverse iterator, rbegin () to the end of the list, rend () to the beginning of the list. So we can give the vector a reverse value.

Give an example:

<pre name= "code" class= "CPP" >void test5 () {vector<int> VI (1), RVi (1); std::vector<int>:: Reverse_iterator rit;std::vector<int>::iterator it;int i;for (i = 1, it = Vi.begin (); It! = Vi.end (); it++) {*it = i+ +;} for (i = 1, rit = Rvi.rbegin (); RIT! = Rvi.rend (); rit + +) {*rit = i++;} for (int i = 0; i < i++) {cout << vi[i] << "";} cout << endl;for (int i = 0; i < i++) {cout << rvi[i] << "";} cout << Endl;}


The output is:

(2.2) Erase ():

Removes the function for the specified element. There are two forms of this function:

Iterator Erase (iterator Loc); Removes an iterator to the element pointed to by a LOC and returns an iterator to the latter element

Iterator Erase (iterator start, iterator end); Removes an iterator within the [Start, end] interval and returns an end iterator.

Example:

<pre name= "code" class= "CPP" >void Test6 () {vector<int> VI (1); Std::vector<int>::iterator It;int I ; for (i = 1, it = Vi.begin (); It! = Vi.end (); it++) {*it = i++;} cout << "Original:"; for (it = Vi.begin (); It! = Vi.end (); It + +) {cout << *it << "";} cout << endl;cout << "Delete:" << * (Vi.begin () + 3) << Endl;vi.erase (Vi.begin () + 3); cout << ; "Erase1 Result:"; for (it = Vi.begin (); It! = Vi.end (); It + +) {cout << *it << "";} cout << endl;cout << "Delete from" << * (Vi.begin () + 1) << "until" << * (Vi.end ()-1) < ;< endl;cout << "Stop at:" << *vi.erase (Vi.begin () + 1, vi.end ()-1) << endl;cout << "Erase2 Result: "; for (it = Vi.begin (); It! = Vi.end (); It + +) {cout << *it << "";} cout << Endl;}


Output:


Status:

(1) Vector Capacity Related: capacity (), size (), resize (), reserve (),

Capacity (void) is a function that returns the current capacity of a vector. That is, the current system to the vector allocated space to store how much capacity.

Reserve (type_size size) is a function that sets the vector capacity to size. When the vector is not set, it is usually based on the number of elements placed, from 0, 1, 2, 4, 8, 16, 32, 64, 128,256 ... Such multiples grow. For example, if you use Push_back () to add elements to a vector variable, the capacity of this variable will be

When you insert the first element, it becomes 1,
When you insert the second element, it becomes 2,
When you insert a third element, it becomes 4.
When you insert a fifth element, it becomes 8.
When you insert a nineth element, it becomes 16.
When you insert a 17th element, it becomes 32.
。。。。。。

But if you know beforehand that you might just insert 50 elements, then use Reserver (50) directly, then the size of the vector will not change unless the total number of elements exceeds 50.

To introduce the example of reserve () on C + + website, click to enter the original address.

Vector::reserve#include <iostream> #include <vector>int main () {  std::vector<int>::size_ Type sz;  std::vector<int> foo;  SZ = foo.capacity ();  Std::cout << "making foo grow:\n";  for (int i=0; i<100; ++i) {    foo.push_back (i);    if (sz!=foo.capacity ()) {      sz = foo.capacity ();      Std::cout << "Capacity changed:" << sz << ' \ n ';    }  }  std::vector<int> Bar;  SZ = bar.capacity ();  Bar.reserve (+);   The only difference with Foo above  std::cout << "Making bar grow:\n";  for (int i=0; i<100; ++i) {    bar.push_back (i);    if (sz!=bar.capacity ()) {      sz = bar.capacity ();      Std::cout << "Capacity changed:" << sz << ' \ n ';    }  }  return 0;}

Output is

Making foo grow:capacity changed:1capacity changed:2capacity changed:4capacity changed:8capacity changed:16capacity C Hanged:32capacity changed:64capacity changed:128making Bar grow:capacity changed:100

Size () returns the number of elements in the current vector, and resize is the number that is redefined.

Size_type size (void) is simple to use and directly invokes the number of returned elements.

Resize () has several variations in its function in the form of void resize (size_type n, type val = 0). n is the number of targets to reset the vector, and Val is a default parameter, which defaults to 0.

When n < size (), the first n elements are preserved; when n > Size (), an element (N-size ()) with a Val value is added at the end of the vector.

Example:

void Test7 () {vector<int> VI (1, 1); Vector<int>::iterator it;cout << "1:original size:" << Vi.size () << endl;for (it = Vi.begin (); it = Vi.end (); it++) {cout << *it << "";} cout << endl;vi.resize (2, 2); cout << "2:new size:" << vi.size () << endl;for (it = Vi.begin (); it ! = Vi.end (); it++) {cout << *it << "";} cout << endl;vi.resize (3, 3); cout << "3:new size:" << vi.size () << endl;for (it = Vi.begin (); it ! = Vi.end (); it++) {cout << *it << "";} cout << endl;vi.resize (4, 4); cout << "4:new size:" << vi.size () << endl;for (it = Vi.begin (); it ! = Vi.end (); it++) {cout << *it << "";} cout << endl;vi.resize (1); cout << "5:end size:" << vi.size () << endl;for (it = Vi.begin (); it! = Vi.end (); it++) {cout << *it << "";} cout << Endl;}

The output is:


(2) Swap () function

The swap (vector &from) function is the current vector and the from vector exchange all elements, regardless of the size () of how many, all Exchange. The equivalent of exchanging pointer content. It's a very simple function.

Example:

void Test8 () {vector<int> vi1 (3, 3);vector<int> vi2;vector<int>::iterator it;for (int i = 0; i <; I + +) {Vi2.push_back (i + 1);} cout << "Original:" << endl;cout << "VI1:" << endl;for (it = Vi1.begin (); It! = Vi1.end (); it++) {cout << *it << "";} cout << endl;cout << "vi2:" << endl;for (it = Vi2.begin (); It! = Vi2.end (); it++) {cout << *it << "";} cout << endl;cout << "Swap:vi1.swap (VI2);" << Endl;vi1.swap (VI2); cout << "VI1:" << endl;fo R (it = Vi1.begin (); It! = Vi1.end (); it++) {cout << *it << "";} cout << endl;cout << "vi2:" << endl;for (it = Vi2.begin (); It! = Vi2.end (); it++) {cout << *it << "";} cout << Endl;}
Output Result:


(3) Clear (), empty ()

Both functions are used differently and are put together because they are very similar in meaning to English. And it's the last two functions that need to be explained.

void Clear (void) is the emptying of all elements within the vector.

bool Empty (void) is the return vector if it is empty, or true if it returns false if not.

Very simple, no examples are provided.


Vector is my first study of the STL, feel through this solid learning, the use of STL and understanding has been a very comprehensive improvement. It is not known whether the function of vector can be analogous to the usage of other STL containers, and it should be able to save some time for future STL learning. STL I have been tangled for several years, although know is simple things, although actually involved in the grammar and change is not much, but has not been attentively to learn, each use is to go to Baidu related usage, and look up dictionary general. It is not good to feel this way, but less. Instead of checking every time, it's better to understand the efficiency at once.





Regression season--c++ STL vector

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.