STL Source Code Learning--vector Usage Summary

Source: Internet
Author: User

First, the container vector

Using the vector you must include the header file <vector>:

#include <vector>

The type vector is a template defined within the namespace std:

[CPP]View Plaincopyprint?
    1. Template < class _ty,
    2. class _ax = allocator<_ty> >
The second parameter defines a memory model.

We generally adopt the default memory model.


Second, the function of vector

The vector molds a dynamic array. The vector copies its elements into an internal dynamic array.

There is always a sort of order between elements, which is an ordered cluster.

Support is immediately accessible.

Its iterator is a random access iterator. So it works for any STL algorithm.

Add an element to the vector or delete one of the elements, and all subsequent elements move to the position, and each move invokes the assignment operator.

So. The ability to add or remove elements at the end is very good.

But in the first or middle words. Poor performance.

One of the secrets of Vector's excellent performance is that it configures a lot of other memory than the elements it holds. We need to understand the relationship between size and capacity .

The function size () can return the size of the vector. That is, the number of actual elements in the vector.

and Capacity () returns the capacity. is the number of elements that the current vector can actually hold. It should always be greater than or equal to the size of the vector.

Suppose you need to place a lot of other elements in the vector than capacity. You need to configure the internal memory again.

The capacity of the vector also increases.

Look at the following demo sample code:

[CPP]View Plaincopyprint?
  1. #include <iostream>   
  2. #include <vector>   
  3. #include <string>   
  4. #include <algorithm>   
  5. using   namespace std;
  6. int Main ()
  7. {
  8. vector<string> sentence (1);
  9. cout << "max_size ():" << sentence.max_size () << Endl;
  10. cout << "size ():" << sentence.size () << Endl;
  11. cout << "Capacity ():" << sentence.capacity () << Endl;
  12. Sentence.reserve (5);
  13. Sentence.push_back ("Hello,");
  14. Sentence.push_back ("how");
  15. Sentence.push_back ("is");
  16. Sentence.push_back ("You");
  17. Sentence.push_back ("?" )  );
  18. Copy (Sentence.begin (), Sentence.end (),
  19. Ostream_iterator<string> (cout,""));
  20. cout << Endl;
  21. cout << "max_size ():" << sentence.max_size () << Endl;
  22. cout << "size ():" << sentence.size () << Endl;
  23. cout << "Capacity ():" << sentence.capacity () << Endl;
  24. Swap (sentence[1],sentence[3]);
  25. Sentence.insert (Find (Sentence.begin (), Sentence.end (),"?" ),  
  26. "Always"  );
  27. Sentence.back () = "!"  ;
  28. Copy (Sentence.begin (), Sentence.end (),
  29. Ostream_iterator<string> (cout,""));
  30. cout << Endl;
  31. cout << "max_size ():" << sentence.max_size () << Endl;
  32. cout << "size ():" << sentence.size () << Endl;
  33. cout << "Capacity ():" << sentence.capacity () << Endl;
  34. }
Execution Result:


In the program. When the element is inserted again into the vector. Because the vector has insufficient capacity, it causes the memory to be allocated again. However, the result of capacity () is related to the actual version number, Max_size is also.


the capacity of the vector is very important because:

1. Once the memory is configured again, all reference, pointers and iterators associated with it will fail.

2, memory configuration is very time-consuming.

The methods to solve the problem are:

1, can use reserve () reserves the appropriate capacity, reduce the number of times to configure memory. Demo Sample code:

[CPP]View Plaincopyprint

";

    1. vector<string> sentence (1);
    2. Sentence.reserve (50);
2. Pass additional parameters to the constructor during initialization. Construct enough space.
[CPP]View Plaincopyprint

";

    1. Vector<t> V (5);
Of course, the type of such an element must provide a default constructor. However, assuming that the element's type is more complex, the initialization operation is also time consuming.

Let's say it's just to keep enough memory. Use 1 better.

Note: Reserve cannot reduce the vector's capacity. Thus, we can know. Even if the element is deleted. Its reference, pointers, Iterators will continue to work, pointing to the position before the action occurs.

However, the insert operation may invalidate reference, pointers, iterators (due to the possibility of another configuration space).


Use the SWAP function to reduce the vector capacity.

Since two vectors exchange content, their capacity is also interchangeable.

1.

[CPP]View Plaincopyprint

";

    1. Template < class t>
    2. void shrinkcapacity (vector<t> &v)
    3. {
    4. vector<t> tmp (v);
    5. V.swap (TMP);
    6. }
2.
[CPP]View Plaincopyprint?

    1. Vector<t> (v). Swap (v);
The above two methods are equivalent.
is to construct a temporary vector object, initialized with the elements of V, and then exchanged with V.

It is important to note that temporary objects are generally the exact amount of memory that is actually allocated.

So you can reduce the effect of vector capacity.


Third, the operation function of vector

All constructors and destructors are as follows:


Non-volatile operation:


Assignment operation:


This is done by assigning the new element to the vector and removing all the old elements ! Demo Sample code:

[CPP]View Plaincopyprint?
  1. #include <iostream>   
  2. #include <vector>   
  3. #include <string>   
  4. #include <algorithm>   
  5. using   namespace std;
  6. int Main ()
  7. {
  8. vector<string> sentence (1);
  9. cout << "max_size ():" << sentence.max_size () << Endl;
  10. cout << "size ():" << sentence.size () << Endl;
  11. cout << "Capacity ():" << sentence.capacity () << Endl;
  12. Sentence.reserve (5);
  13. Sentence.push_back ("Hello,");
  14. Sentence.push_back ("how");
  15. Sentence.push_back ("is");
  16. Sentence.push_back ("You");
  17. Sentence.push_back ("?

    ");

  18. Copy (Sentence.begin (), Sentence.end (),
  19. Ostream_iterator<string> (cout,""));
  20. cout << Endl;
  21. Sentence.assign (3,"new");
  22. Copy (Sentence.begin (), Sentence.end (),
  23. Ostream_iterator<string> (cout,""));
  24. cout << Endl;
  25. }
Execution Result:

Be able to see that the original element is all deleted.


Element access

In these functions, the only check for subscript is the at function.

So. When calling operator[], it must be psychologically clear whether the index is valid.


Iterator-related functions


The two scenarios in which iterators fail are:

1. Delete or move the element in a smaller position.

2, because the transformation of capacity causes memory allocation again.


Inserting and removing elements


Inserts and removes elements. Will invalidate the reference, pointers, and iterators of the elements after the "action point". The insert operation may also cause memory to be allocated again, so all reference, pointers, iterators on the container will be invalidated.


four, the vector as General Array Use

Today's C + + standard guarantees that vector elements must be distributed in contiguous spaces . For a legitimate index in a vector, the following expressions are satisfied:

&v[i] = &v[0] + i;

We must ensure that the vector can hold all the data.

Suppose you are using c-string, and remember that there is a '. ' At the end.

Only if we need an array of element type T, we can use Vector<t>, and then pass the address of the first element to it.

Note: Never pass an iterator as the address of the first element. Because the vector iterator is defined by the implementation version number, it is not necessarily a generic pointer.

[CPP]View Plaincopyprint

";

    1. printf ("%s", V.begin ()); //error (might work,but not portable)   
    2. printf ("%s", &v[0]); //ok

STL Source Code Learning--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.