C + + vector usage (detailed!!) function, implementation) __jquery

Source: Internet
Author: User
Tags throw exception

1, briefly describe the basic operation of Vector, its size,capacity (), Clear,reverse,reserve,

Push_back, etc...

2, say, is the vector storage characteristics, whether sequential storage or as a list, if it is sequential storage, then how to perform

Erase,insert, etc. function, ... (If the space behind is not enough, we need a reasonable algorithm to find a new

The corresponding space ... Copy, Recycle ... is not particularly troublesome), if it is chained storage, then how does it do fast

Access (by subscript) ...


1 Basic operations

(1) header file #include<vector>.

(2) Creating a Vector object,vector<int> VEC;

(3) Tail Insert number: Vec.push_back (a);

(4) Use subscript to access elements,cout<<vec[0]<<endl; remember that subscripts start at 0.

(5) Accessing elements using iterators.

<span style= "FONT-SIZE:18PX;" >vector<int>::iterator it;
For (It=vec.begin (); It!=vec.end (); it++)
    cout<<*it<<endl;</span>

(6) Insert element: Vec.insert (Vec.begin () +i,a); Insert a after the first element;

(7) Delete element: Vec.erase (Vec.begin () +2); Delete 3rd element

Vec.erase (Vec.begin () +i,vec.end () +j); Delete interval [i,j-1]; interval starting from 0

(8) Vector size: vec.size (); (9) Empty: Vec.clear ()//Empty, vec.size () to 0


A simple program:

<span style= "FONT-SIZE:18PX;"
> #include <stdio.h> #include <vector> #include <iostream> using namespace std;
        int main () {int i=0;
        Vector<int> VEC;   for (i=0; i<10; i++) {vec.push_back (i); 10 elements are entered sequentially, resulting in a for (unsigned int i=0; i<vec.size (); i++) {cout<< "Initialization traversal:"
        ;<vec[i]<<endl;

        //The result is: 0,1,2,3,4,5,6,7,8,9  vector<int>::iterator it;
        for (it = Vec.begin (); It!=vec.end (); it++) {cout<< "iterative traversal:" <<*it<<endl;
  The result is: 0,1,2,3,4,5,6,7,8,9 Vec.insert (Vec.begin () +4,0); Results are:         for (unsigned int i=0; i<vec.size (); i++)          {        cout<< "Insert traversal:" <<vec[i]<<
Endl        //Result: 0,1,2,3,0,4,5,6,7,8,9
        vec.erase (Vec.begin () +2);         for (unsigned int i=0; i<vec.size (); i++)     
    {        cout<< "erase traversal:" <<vec[i]<<endl;        //Result: 0,1,3,0,4,5,6,7,8,9        
  
Vec.erase (Vec.begin () +3,vec.begin () +5);
        for (Vector<int>::iterator it = Vec.begin (); It!=vec.end (); it++)         {        cout<< "iterative traversal:" <
<*it<<endl;
       }         return 0; } </span>

2:

Vector elements can not only make int,double,string, but also structural body, but note: The structure is defined as global, otherwise there will be errors. The following is a short program code:

<span style= "FONT-SIZE:18PX;" > #include <stdio.h>
#include <algorithm>
#include <vector>
#include <iostream >
using namespace std;

typedef struct RECT
{
    int id;
    int length;
    int width;

For vector elements that are structural, you can define comparison functions within the structure, sorted by Id,length,width ascending order.
bool operator< (const RECT &a)  const
    {
        if (id!=a.id) return
            id<a.id;
        else
        {
            if (length!=a.length) return
                length<a.length;
            else return width<a.width;}}}
Rect;

int main ()
{
    vector<rect> vec;
    Rect Rect;
    rect.id=1;
    rect.length=2;
    rect.width=3;
    Vec.push_back (rect);
    Vector<rect>::iterator It=vec.begin ();
    cout<< (*it) .id<< ' << (*it) .length<< ' << (*it) .width<<endl;    

return 0;

} </span>

3 algorithm


(1) Use reverse to flip the element: Requires a header file #include<algorithm>

Reverse (Vec.begin (), Vec.end ()); Flip the element (in vector, if two iterators are required in a function,

Usually the latter one is not included.)

(2) Use sort order: Need header file #include<algorithm>,

Sort (Vec.begin (), Vec.end ());(default is in ascending order, that is, from small to large.

You can compare the sort comparison functions by overriding them in descending order, as follows:

To define a sort comparison function:

BOOL Comp (const int &A,CONST int &b)
{
Return a>b;
}
When called: Sort (Vec.begin (), Vec.end (), Comp), sorted in descending order.




Vector:c++ the sequential container in the STL, encapsulates an array

1. Vector container Memory self-growth

Unlike other containers, its memory space only grows and does not decrease. Let's take a look at what "C + + Primer" says: To support a quick random visit

Q, the elements of the vector container are kept in a continuous manner, and each element is stored next to the previous element. Imagine, when the vector adds an element,

In order to satisfy the continuous storage of this feature, it is necessary to redistribute space, copy elements, undo the old space, so the performance is difficult to accept. So the STL implementation in the

When a vector allocates memory, it actually allocates more capacity than is currently required. That is, the vector container reserves some additional storage

Area to hold the newly added elements so that you do not have to reassign the entire container's memory space for each new element.

With regard to the vector's memory space, there are two functions to note: the size () member refers to the number of elements currently owned; capacity () member refers to the current (container must be divided into

The number of elements that can be stored before the new storage space is assigned. The reserve () member can be used to control the space reserved for the container. Another characteristic of vector is its

The memory space grows, and whenever the vector container has to allocate new storage space, it is redistributed with an allocation policy that doubles the current capacity. For example

The current capacity is 50, when the 51st element is added, the reservation space is not available, and the vector container will reallocate the memory space of size 100 as a new

The location of the contiguous storage.


<span style= "FONT-SIZE:18PX;" > #include <iostream>
using namespace std;
#include <vector>

int main ()
{
        vector<int> arry;
        Arry.reserve (ten);
        cout << arry.capacity () <<endl;
        Arry.push_back (1);
        Cout<<arry.capacity () <<endl;
        Arry.push_back (2);
        Cout<<arry.capacity () <<endl;
        Arry.push_back (3);
        Cout<<arry.capacity () <<endl;

}
</span>
Run Result:

When we remove the comment above:



2. Vector Memory Release

Because the vector's memory footprint only increases, such as you first allocated 10,000 bytes, and then erase off the back 9,999, leaving a valid element, but memory accounted for

is still 10,000. All memory space can be reclaimed by the system during vector destructor. Empty () is used to detect whether the container is empty, clear () to empty all elements.

However, even if clear (), the memory space occupied by the vector remains the same, and memory recovery is not guaranteed.

Consider using deque if space is needed to shrink dynamically. If the vector is not available, you can use Swap () to help you free up memory. The specific methods are as follows:

<span style= "FONT-SIZE:18PX;" >vector<int> nums; 
Nums.push_back (1);
Nums.push_back (1);
Nums.push_back (2);
Nums.push_back (2); 
Vector<int> (). Swap (Nums); or Nums.swap (vector<int> ()) </span>

Or, as shown below, use a pair of curly braces, meaning the same:
<span style= "FONT-SIZE:18PX;" >//plus a pair of curly braces is the time to allow TMP to exit {} automatically destructor
{ 
    std::vector<int> tmp =   nums;  
    Nums.swap (TMP); 
}

</span>

The simplest way to release vector memory is Vector<int>.swap (Nums), which is the commutative function that causes the vector to leave its own scope, forcing the release of the vector's memory space. If Nums was a member of a class, Vector<int>.swap (Nums) could not be written into the destructor of the class, or it would result in a double free or corruption (fasttop) error, possibly because of repeated release of memory. The standard solution is as follows:
<span style= "FONT-SIZE:18PX;" >template < class T >
void clearvector (vector< t >& vt) 
{
    vector< t > vttemp; 
    Vetemp.swap (VT);
</span>

3. Use vector to release the pointer

If the vector holds pointers, then when the vector is destroyed, the objects pointed to by these pointers are not destroyed and the memory is not freed. As in the following case, the element in the vector is dynamically requested by the new Action object pointer:

<span style= "FONT-SIZE:18PX;" > #include <vector> 
using namespace std; 

Vector<void *> v;</span>

Call V.push_back () the pointer after each new, and release the memory in the program exit or, as needed, with the following code:
<span style= "FONT-SIZE:18PX;" >for (vector<void *>::iterator it = V.begin (); it!= v.end (); it +) 
    if (NULL!= *it) 
    {
        Delete *it;
  *it = NULL;
    }
V.clear ();</span>





3,

Vector is a linear container, its elements are strictly sorted by a linear sequence, similar to a dynamic array, and arrays, whose elements are stored in a contiguous storage space, which means that we can not only use iterators (iterator) to access elements, but also to access them using the pointer's offset. Unlike conventional arrays, vectors can automatically store elements that automatically grow or shrink storage space,

The advantages of vector:

1. You can use the subscript to access individual elements

2. Iterators can traverse containers in different ways

3. You can add or remove elements at the end of the container

While the container consumes more memory when it automatically handles the size of the capacity, the container can provide the same performance as the array, and it can adjust the storage space very well.

Compared to other standard sequential containers (deques or lists), you can more efficiently access elements within the container and add and remove elements at the end, add and remove elements in other locations, vectors are less than other sequential containers, and the iterators and references are no better than the lists support

The size of the container and the capacity of the container are different, size refers to the number of elements, capacity is allocated memory size, capacity is generally equal to or greater than the size of the container, Vector::size () return the size of the container, vector::capacity () return capacity value, More than the size of the container is used to prevent increased use of containers, each reallocation of memory will affect the performance of the program, so the general allocation of capacity is greater than the size of the container, to specify the size of the allocated capacity, you can use Vector::reserve (), but the specified value is greater than the size () value,


1. Construct and copy constructors

Explicit vector (const allocator& = allocator ());

Explicit vector (size_type N, const t& value= T (), const allocator& = allocator ());

Template <class inputiterator>

Vector (Inputiterator, inputiterator last, const allocator& = allocator ());

Vector (const vector<t,allocator>& x);

Explicit: is to prevent implicit conversions, allocator is a memory allocation mode, typically using the default

Vector<int> A; Create a container that is empty

Vector<int> B (10,100); Create individual elements, each with a value of

Vector<int> C (B.begin (), B.end ()); Using iterators, you can create a new container by taking part of the element

Vector<int> D (C); Copy the constructor and create a container that is exactly the same

2. destructor

~vector ()

Destroys the container object and reclaims all allocated memory

3. overloaded = Symbol

Vector<int> E;

E = B; Use = Symbol

B = vector<int> (); Place B as an empty container

4. Vector::begin () returns the iterator of the first element

Function Prototypes:

Iterator begin (); Returns a variable iterator

Const_iterator begin () const; Returns an iterator for a constant, not variable

5.vector::end () returns the first position after the crossing, which is the next position of the last element.

Iterator End ();

Const_iterator end () const;

6.vector::rbegin () The first element of the reverse sequence, which is the last element of the positive sequence

Reverse_iterator Rbegin ();

Const_reverse_iterator rbegin () const;

7.vector::rend () The last element of the reverse sequence is the next position, and the first element of the positive sequence is the previous position

Reverse_iterator rend ();

Const_reverse_iterator rend () const;

Same as the vector::end () principle

8.vector::size () returns the number of elements in a container

Size_type size () const;

Notice the difference with the vector::capacity ()

9.vector::max_size ()

Size_type max_size () const;

Returns the maximum number of elements that can be stored in a container, which is a limit that can no longer automatically grow when the container expands to this maximum value

Vector::resize ()

void Resize (Size_type sz, t C = t ());

Redistribute the number of elements of the container, this can also change the capacity of the container, if the number of reassigned elements than the original small, will truncate the sequence, the next part of discarded, if more than the original number, the following value is the value of C, the default is 0

Vector::capacity ()

Size_type capacity () const;

Returns the size of the actual storage space of a vector, which is generally greater than or equal to the number of vector elements, noting the difference from the size () function

Vector::empty ()

BOOL empty () const;

Returns True when the number of elements is 0 o'clock, otherwise false, based on the number of elements rather than the size of the container's storage space

Vector::reserve ()

void Reserve (Size_type n);

The size of the reallocation space, but this n value is larger than the original capacity (), otherwise the storage space remains unchanged, n value is larger than the original actual storage space to redistribute space, but the maximum value can not be greater than the max_size value, or it will throw an exception

Vector::operator[]//overloaded [] Symbol

Reference operator[] (size_type N);

Const_reference operator[] (size_type n) const;

Implementation of subscript access element

Vector::at ()

Const_reference at (size_type N) const;

Reference at (size_type N);

The function has the same operational aspect as the subscript access element, and the difference is that when the function crosses the line, it throws an exception Out_of_range

Vector::front ()

Reference Front ();

Const_reference Front () const;

Returns the value of the first element, which differs from the Begin () function and the Begin () function returns the iterator of the first element

Vector::back ()

Reference back ();

Const_reference back () const;

Again, returns the value of the last element, noting the difference from the end () function

Vector::assign ()

Template <class inputiterator> void assign (Inputiterator-I, Inputiterator, last);

void Assign (size_type n, const t& u);

The original element is discarded and the element is reassigned, and the first function uses an iterator, and the second function uses n elements, and the value of each element is U.

Vector::p ush_back ()

void push_back (const t& x);

Inserts an element x in the last position of the container, and if the size value is greater than the capacity value, the space is redistributed

Vector::p op_back ()

void Pop_back ();

Delete last Element

Vector::insert ()

Iterator insert (iterator position, const t& x);

void Insert (iterator position, Size_type N, const t& x);

Template <class inputiterator>

void Insert (iterator position, Inputiterator, Inputiterator last);

Inserts a new element,

The first function inserts an element with the value x before the position specified by the iterator

A second function that inserts n an element of x before the position specified by the iterator

A third function that inserts a sequence iterator of another container before the position specified by the iterator first to last

If a new element is inserted and the total number of elements is greater than capacity, the space is redistributed

Vector::erase ()

Iterator Erase (iterator position);

Iterator Erase (iterator, iterator last);

Delete an element or a sequence of paragraphs

Vector::swap ()

void swap (vector<t,allocator>& VEC);

Swap the contents of these two containers, which involves reallocation of storage space

Vector::clear ()

void Clear ();

Empty the contents of the container, the size value is 0, but the storage space does not change

<span style= "FONT-SIZE:18PX;"

> #include <vector> #include <iostream> using namespace std; int _tmain (int argc, _tchar* argv[]) {       //constructor, copy constructor (consistent element type),     vector<int> a; //Create an empty container     vector<int> B (10,100); Create a 10 element with each element value of     vector<int> C (B.begin (), B.end ()); Using iterators, you can create a new container     vector<int> D (C) by taking part of the element; Copy the constructor, create an identical container               //overload =   
 vector<int> E;
    e = B;       //vector::begin (), returns the iterator         vector<int> F (10); Create a container with 10 elements            for (int i = 0; i < i++)            {        f[i] = i;           }     /*     vector<int> F; Create an empty container     for (int i = 0; i < i++)     {        f.
Push_back (i);    &nbsp         */    vector<int>::iterator
Beginiter = F.begin ();     cout << *beginiter << Endl;
Output 0     //vector::end () returns the iterator     vector<int>::iterator enditer = F.end ();     EndIter--; Move back one position     cout << *enditer << Endl; Output 9       //vector::rbegin () returns the first element in reverse, equivalent to the last element     vector<int>::
Reverse_iterator Reverbeiter = F.rbegin ();     cout << *reverbeiter << Endl; Output 9     //vector::rend () The last element of the reverse sequence is the next position, which corresponds to the first position     vector<int&gt:
Reverse_iterator Revereniter = F.rend ();     ReverEnIter--;     cout << *revereniter << Endl; Output 0     //vector::size () returns the number of elements     cout << f.size () << Endl; Output     //vector::max_size ()     cout << f.max_size () << Endl; Output 1073741823, this is the limit element number     //vector::resize ()     cout << f.size () << Endl ;
Output     f.resize (5);     for (int k = 0; k < f.size (); k++)         cout << f[k] << " ";
Output 0 1 2 3 4          cout << Endl;          //vector::capacity ()     cout << f.size () << Endl; 5     cout << f.capacity () << Endl;
    //vector::empty ()          b.resize (0);     cout <&Lt B.size () << Endl; 0     cout << b.capacity () << Endl;     cout << b.empty () << Endl; True     //vector::reserve ()//reallocating storage space size             cout << c.capacity () << Endl;
    c.reserve (4);     cout << c.capacity () << Endl;
    c.reserve (14);     cout << c.capacity () << Endl;     //vector::operator []     cout << f[0] << Endl; The first element is 0     //vector::at ()     try     {      cout & lt;< "f.size =" << f.size () << Endl; 5            cout << f.at (6) << Endl; Throw exception    &nbsp}     catch (out_of_range)     {    
       cout << "at () access out of Bounds" << Endl;    &nbsp}     //vector::front () returns the value of the first element             cout << f.front () << Endl; 0     //vector::back ()     cout << f.back () << Endl; 4     //vector::assign ()     cout << a.size () << Endl;
0     vector<int>::iterator-c.begin ();
    vector<int>::iterator end = C.end ()-2;
    a.assign (first,end);     cout << a.size () << Endl; 8     cout << a.capacity () << Endl; 8     a.assign (5,3); All of the original elements will be discarded and then assigned     cout << a.size () << Endl; 5     cout << a.capacity () << Endl; 8     //vector::p ush_back ()     cout << * (F.End ()-1) << Endl;
4     f.push_back (100);     cout << * (F.end ()-1) << Endl;     //vector::p op_back ()     cout << * (F.end ()-1) << Endl;
    f.pop_back ();     cout << * (F.end ()-1) << Endl; 4     //vector::swap ()     f.swap (D); Swap the contents of both containers     for (int f = 0; F < f.size (); f++)         cout << F
[F] << "";
    cout << Endl;      for (int d = 0; d < d.size (); d++)         cout << d[d] <<
" ";
         cout << Endl;
    //vector::clear ()     f.clear ();     cout << f.size () << endl;    //0     cout << F.capacity () << Endl; 10     return 0; } </span>



This article draws lessons from: http://www.cnblogs.com/wang7/archive/2012/04/27/2474138.html
http://blog.csdn.net/bizhu12/article/details/6769976

Http://www.cnblogs.com/summerRQ/articles/2407974.html

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.