The Vector class container usage in C + + programming _c language

Source: Internet
Author: User

Vector Introduction
Vector is the most common container in the STL, which is a sequential container that supports random access. Vector is a continuous allocation of memory, from the point of view of data arrangement, and arrays are very similar, different place is: the array is static allocation space, once the size of the space allocated, it can not be changed, and vector is the dynamic allocation of space, with the constant insertion of elements, It will continue to expand its capacity according to its own set of mechanisms.

Vector expansion mechanism: increase by one times the container's current capacity. Vector containers are allocated a contiguous memory space, each time the container growth, not in the original continuous memory space after a simple overlay, but to reapply a larger new memory, and the existing container to copy the elements of the past, and then destroy the old memory. The original iterator that points to the old memory space is invalidated, so when the container is operated, the iterator is updated in time.

Vector's data structure
vector data structure, using a continuous linear space, belong to the linear storage. He uses 3 iterators _first, _last, and _end to point to different ranges of assigned linear spaces, and the following is the source code that declares 3 iterator variables.

Template<class _ty, class _a= allocator< _ty> > 
class vector{ 
... 
Protected: 
iterator _first, _last, _end; 

_first points to the head of the space used, _last points to the end of the space size (size), _end to the tail of the space capacity (capacity). For example:

int data[6]={3,5,7,9,2,4}; 
Vector<int> vdata (data, data+6); 
Vdata.push_back (6); 
...

When vector initialization, the requested space size is 6, storing the 6 elements in data. When the 7th element "6" is inserted into the vdata, the vector uses its own expansion mechanism to reapply for space, and the data storage structure is shown in the figure:

A brief description. When inserting the 7th element "6", the vector finds itself out of space and then applies for a new 12-size memory space (one-fold), copies the previous data to the front of the new space, and then inserts the 7th element. At this point the _last iterator points to the last valid element, and the _end iterator points to the last valid space position of the vector. We use the member function size of the vector to get the size of the current vector, at 7, using the capacity member function to get the current vector's capacity, at this point 12.


vector Container Type
a vector container is a template class that can hold objects of any type (but must be of the same class object). The vector object can efficiently add elements at run time, and the elements in the vector are continuously stored.
The construction of vectors

Function Prototypes:

Template<typename t>
Explicit vector ();                 The default constructor, the vector object is an empty
explicit vector (size_type n, const t& v = T ());  Creates a vector object vector with n elements
(const vector& x);
Vector (Const_iterator-const_iterator, last);

Note: All objects stored within the vector container are initialized. If you do not specify an initial value for the stored object, the built-in type will be initialized with 0, and the class type will invoke its default constructor for initialization (if there are other constructors without a default constructor, then the element initializer must be supplied to be placed in the container).

Example:

Vector<string> v1;     Creates an empty container with an object type of String class
Vector<string> v2 (a);   Creates a container vector<string> v3 (5, "Hello") for a string class object that has an initial value (that is, an empty string)
;//create a container vector of 5 string class objects with a value of "Hello"
<string> v4 (V3.begin (), V3.end ()); V4 is the same container as V3 (full copy)

Vector Operations (all of the following functions are member functions)

BOOL empty () const;      Returns true if the container is empty, otherwise returns false Size_type max_size () const;        Returns the maximum number of elements that a container can hold size_type size () const;      Returns the number of elements in the container Size_type capacity () const;       The number of elements the container can store: capacity () >= size () void reserve (Size_type n);  Ensure capacity () >= n void Resize (size_type n, t x = t ());

Make sure that after returning, there are: size () = n; if the size () is <n, then the value of element x is fully completed.           Reference Front ();          
Returns a reference to the first element in the container (the container must be Non-null) const_reference front () const;           Reference back ();

Returns a reference to the last element in the container (the container must be Non-empty) const_reference back () const;  Reference operator[] (size_type POS);
Returns a reference to the element labeled POS (subscript starting from 0; If the subscript is not correct, it is undefined behavior.) 
Const_reference operator[] (size_type pos) const;      Reference at (size_type POS);

Returns a reference to the element marked as a pos, or, if the subscript is not correct, throws an exception Out_of_range const_reference at (size_type pos) const;      void push_back (const t& x);            Add an element void Pop_back () to the end of the container; The last element in the pop-up container (the container must be non-null)//NOTE: The following insert and delete operations will take place the movement of elements (in order to preserve the nature of continuous storage), so previous iterators may fail iterator insert (iterator it, const t& x = T ());   Inserts an element before the insertion point element (or inserts an element at the insertion point) void Insert (iterator it, Size_type N, const t& x);

Note iterators may no longer be valid (possibly reallocating space) void insert (iterator it, Const_iterator, Const_iterator last);      Iterator Erase (iterator it); Deletes the specified element and returns the position of the element after the deletion (if there is no element, returns end ()) iterator erase (iterator-A, iterator last);

Note: After deleting an element, the corresponding iterator for the element after the deletion point is no longer valid.          void clear () const;  Emptying the container is equivalent to calling erase (begin (), end ()) void assign (size_type n, const t& x = T ());

Assigns the specified element sequence to replace all elements in the container void assign (Const_iterator-I, const_iterator last);     Const_iterator begin () const;
Iterative sequence iterator begin ();
Const_iterator end () const;

Iterator End ();
Const_reverse_iterator rbegin () const;
Reverse_iterator Rbegin (); 
Const_reverse_iterator rend () const;

 Reverse_iterator rend ();

Comparison of Vector objects (non-member functions)

There are six comparison operators for vector objects: operator==, operator!=, operator<, operator<=, operator>, and operator>=.

Of these, for operator== and operator!=, two vector objects are equal if the vector object has the same number of elements and the corresponding position element is all equal;
For operator<, operator<=, operator>, operator>=, a dictionary ranking strategy is used to compare.

Note: In fact, only need to implement operator== and operator!= on the other can be based on these two implementations. Because, operator!= (LHS, RHS) is! (LHS = = RHS), operator<= (LHS, RHS) is! (RHS < LHS),operator> (LHS, RHS) is (RHS < LHS), operator>= (LHS, RHS) is! (LHS, RHS).

Iterators for vector classes

The vector class iterator supports arithmetic operations in addition to the common prefix self-add operators: it + N, it-n, it2-it1. Note that the It2-it1 return value is Difference_type (signed type).

Note that any operation that alters the size of the container can cause previous iterators to fail.

Instance
1.vector of data stored and exported:

#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
void Main ()
{
 int i = 0;
  Vector<int> v;
  for (i = 0; i < i++)
 {
      v.push_back (i);//Save the element one at a vector
 } to the
stored data for
 (i = 0; i < V.size (); i++)//v.size () indicates the number of vectors stored in the element
 {
     cout << v[i] << ""; Show each element
 }
 cont << Endl;
}

Note: You can also use V.begin () and V.end () to get the pointer position of the vector's starting and ending element addresses. You can also do this:

Vector<int>::iterator iter;
for (iter = V.begin (); Iter!= v.end (); iter++)
{
  cout << *iter << Endl;
}

2. Definition of a two-dimensional vector.
(1) define a 10 vector element and a value of 1-10 for each vector character.

#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
void Main ()
{
int i = 0, j = 0;
Defines a two-dimensional, dynamic array with 10 rows, each of which is a vector that stores this row of data.
so the length of each row can be changed. Vector<int> (0) is used to initialize vectors, otherwise the vectors cannot be stored in the element.
vector< vector<int> > Array (vector<int> (0));
for (j = 0; J < + j)
{for
 (i = 0; i < 9; i++)
 {
  array[J].push_back (i);
 }
For
(j = 0; J < + j) {for
 (i = 0; i < array[J].size (); i++)
 {
  cout << arra y[J [i] << "";
 }
 cout<< Endl
}
}

(2) defines an array in which the rows and columns are variable.

#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
void Main ()
{
int i = 0, j = 0;
vector< vector<int> > Array;
vector< int > line;
for (j = 0; J <; J + +)
{
 array.push_back (line);//The element cannot be saved to initialize each vector. For
 (i = 0; i < 9; i++)
 {
  array[J].push_back (i);
 }
}
for (j = 0; J < + j)
{for
 (i = 0; i < array[J].size (); i++)
 {
  cout << array[J] [ I] << "";
 }
 cout<< Endl
}
}

(3) Delete the specified element using Vettor Erase

#include "iostream"
#include "vector"
using namespace std;
int main ()
{
  vector<int> arr;
  Arr.push_back (6);
  Arr.push_back (8);
  Arr.push_back (3);
  Arr.push_back (8);
  For (Vector<int>::iterator It=arr.begin (); It!=arr.end ();)
  {
    if (* it = = 8)
    {
      it = arr.erase (it);
    }
    else
    {
      ++it;
    }
  }
  cout << "after remove 8:\n";
  for (Vector<int>::iterator it = Arr.begin (); it < Arr.end (); ++it)
  {
    cout << * it << ""; 
   }
  cout << Endl;
}


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.