C + + Stl:vector and List

Source: Internet
Author: User
Tags arrays
STL Description:

The C + + standard module library is a set of template classes that provide a common programming data structure and function, such as a double join table (list), paired array (map), extensible array (vector), large string of storage operations (rope), and so on. The STL library can be obtained from the http://www.sgi.com/tech/stl/.


STL can be divided into the following categories: Container class: Sequential container:Vector: A dynamic array variable, struct, or object. You can insert data at the end to support quick random access.deque: Supports inserting elements, two-terminal queues, before and after arrays.List: A variable, structure, or object that is based on a linked list. You can insert and delete elements anywhere. Support for quick inserts, deletes. Associated containers:Set(No duplicate elements are allowed in set),Multiset(can have duplicate elements): Balanced binary tree structure ordered data collection, can quickly search.Map(Unique keys),Multimap(Allow repeat keys): A balanced binary tree structure that associates key-value pairs. Container adapters:StackLIFO StackQueueFIFO queuepriority_queueReturns the highest-priority element, the priority queue string:string: string and its operationRope: String storage and manipulationBitset: An intuitive storage bit and an action bit. Generic algorithm:Iterator iterator: Represents the position in the container, and an iterator is defined as a container class type.algorithm Algorithm: A class that provides lookups, counts, and searches for elements in a container.Smart pointer auto_ptr: A class that associates memory pointers to avoid memory leaks.STL Vector: Initialize:       Vector<int> Ivec;      Vector<int > Vec2 (IVEC);       Vector c (iter.begin,iter.end);        Vecotr<int > C (5,0); Vector<int> C (5);
Example 1:Use vector to store STL strings and access the elements in the vector with three method classes:

#include <iostream> #include <vector> #include <string> using namespace std;

   Main () {vector<string> SS;
   Ss.push_back ("The number is 10");
   Ss.push_back ("The number is 20");

   Ss.push_back ("The number is 30");

   cout << "Loop by index:" << Endl;
   int II;
   For (Ii=0 II < ss.size (); ii++)//First method access {cout << ss[ii] << Endl;

   } cout << Endl << "Constant iterator:" << Endl;
   Vector<string>::const_iterator CII;
   For (Cii=ss.begin (); Cii!=ss.end (); cii++)//The second method {cout << *cii << Endl;

   } cout << Endl << "Reverse iterator:" << Endl;
   Vector<string>::reverse_iterator Rii;
   For (Rii=ss.rbegin (); Rii!=ss.rend (); ++rii)//third method {cout << *rii << Endl;

   } cout << Endl << "Sample Output:" << Endl;
   cout << ss.size () << Endl;

   cout << ss[2] << Endl; Swap (SS[0], ss[2]);
cout << ss[2] << Endl;
                
 }

vector to represent two-dimensional, three-dimensional arrays:
A two-dimensional array is the length of the array that two Vector,vector constructors can initialize and sets the initial value. Example 2: vector two-dimensional array

#include <iostream>
#include <vector>

using namespace std;

Main ()
{
   //declaration of large and initialized two-dimensional arrays
   vector< vector<int> > Vi2matrix (3, vector<int> (2,0));    

   Vi2matrix[0][0] = 0;
   VI2MATRIX[0][1] = 1;
   Vi2matrix[1][0] = ten;
   VI2MATRIX[1][1] = one;
   Vi2matrix[2][0] =;
   VI2MATRIX[2][1] =;

   cout << "Loop by index:" << Endl;

   int II, JJ;
   For (Ii=0 II < 3; ii++)
   {for
      (jj=0; J.J. < 2; jj++)
      {
         cout << VI2MATRIX[II][JJ] << End l;
      }}}

                
Example 3 :Vector three-dimensional array
#include <iostream>
#include <vector>

using namespace std;

Main ()
{
                               //Vector length of 3 initialized to 0
   vector<int> Vi1matrix (3,0);

                               Vector length of 4 initialized to hold another 

                               /vector vi1matrix which has been initialized to 0
   vector< V Ector<int> > Vi2matrix (4, Vi1matrix);

                               Vector of length 5 containing two dimensional vectors
   vector< vector< vector<int> > > Vi3matrix ( 5, Vi2matrix);

   ...

or, in a statement, define:

#include <iostream>
#include <vector>

using namespace std;

Main ()
{
   vector< vector< vector<int> > > Vi3matrix (2, vector< vector<int> > (3, Vector<int> (4,0)));

   for (int kk=0; kk<4; kk++)
   {for
      (int jj=0; jj<3; jj++) {for
         (int ii=0; ii<2; ii++)
            { cout << Vi3matrix[ii][jj][kk] << Endl}}}



using iterators: Example 4:Using iterators for two-dimensional vectors
#include <iostream>
#include <vector>

using namespace std;

Main ()
{
   vector< vector<int> > Vi2matrix;    Declare two-dimensional array
   vector<int> A, B;
   vector< vector<int> >::iterator Iter_ii;
   Vector<int>::iterator   iter_jj;

   A.push_back (ten);
   A.push_back (a);
   A.push_back (a);
   B.push_back (m);
   B.push_back ();
   B.push_back ();

   Vi2matrix.push_back (A);
   Vi2matrix.push_back (B);

   cout << Endl << "Using iterator:" << Endl;

   For (Iter_ii=vi2matrix.begin (), Iter_ii!=vi2matrix.end (); iter_ii++)
   {for
      (iter_jj= (*iter_ii). Begin (); Iter_jj!= (*iter_ii). end (); iter_jj++)
      {
         cout << *iter_jj << endl;
      }
   }
}
                

Constructor/declaration:

Method/Action Description
Vector<t> v; Declares a vector variable V with a data type of "T".
Vector<t> V (size_type N); Declares a vector variable with a size of n, containing the data type T
Vector<t> V (size_type n,const t& T); Declares a vector variable with a size of n, containing a data type of T, and an element with a value of t
Declaration:vector (size_type N, const t& T)
Vector<t> V (begin_iterator,end_iterator); Copy a vector from the start position of the iterator to the end position
Declaration:template Vector (Inputiterator, inputiterator)

Size Method/action:


td>returns bool (true/false). True if empty. Declaration:bool Empty () const
method/operator Description
empty ()
size () number of elements of vector.
Declaration:size_type size () const
resize (n, t=t ()) Adjust by adding or Deleti ng elements of vector so it's size is "n".
Declaration:void Resize (n, t = t ())
Capacity () Max number of elements of vector before reallocation.
Declaration:size_type capacity () const
Reserve (size_t N) Max Number of element s of vector set to "n" before reallocation.
Declaration:void Reserve (size_t)
max_size () max number of elements of vector possible.
Declaration:size_type max_size () const
Other methods and actions:
Method/operator Description
Erase ()
Clear ()
Erase all elements of vector.
Declaration:void Clear ()
Erase (iterator)
Erase (Begin_iterator,end_iterator)
Erase element of vector. Returns iterator to next element.
Erase element range of vector. Returns iterator to next element.
Declarations:iterator Erase (iterator pos) iterator erase (iterator-I, iterator, last)
=
Example:x=y ()
Assign/copy entire contents of one vector into another.
declaration:vector& operator= (const vector&)
< Comparison of one vector to another.
Declaration:bool operator< (const vector&, const vector&)
== Returns BOOL. True if every element is equal.
Declaration:bool operator== (const vector&, const vector&)
at (index)
V[index]
Element of Vector. Left and right value assignment:v.at (i) =e; and e=v.at (i);
Declaration:reference operator[] (size_type N)
Front ()
V[0]
The vector of the A-element. (Left and right value assignment.)
Declaration:reference Front ()
Back () last element of vector. (Left and right value assignment.)
Declaration:reference back ()
Push_back (const t& value) ADD element to end of vector.
Declaration:void push_back (const t&)
Pop_back () Remove element from end of vector.
Declaration:void Pop_back ()
Assign (Size_type n,const t& T) Assign the elements a value "T".
Assign (Begin_iterator,end_iterator) Replace data in range defined by iterators.
Declaration:
Insert (iterator, const t& T) Insert at Element "iterator", element of value "T".
Declaration:iterator Insert (iterator pos, const t& x)
Insert (iterator Pos, size_type N, const t& x) Starting before Element "POS", insert a-n elements of value "X".
Declaration:void Insert (iterator pos, size_type N, const t& x)
Insert (iterator POS, begin_iterator,end_iterator) Starting before Element "POS", insert range begin_iterator to End_iterator.
Declaration:void Insert (iterator Pos, Inputiterator F, inputiterator L)
Swap (vector& v2) Swap contents of two vectors.
Declaration:void Swap (vector&)

Iterator Methods/Actions
Method/operator Description
Begin () Return iterator to a vector.
Declaration:const_iterator begin () const
End () Return iterator to end of vectors (not last element of vector but past last element)
Declaration:const_iterator End () const
Rbegin () Return iterator to a vector (reverse order).
Declaration:const_reverse_iterator Rbegin () const
Rend () Return iterator to end of vectors (not last element but past last element) (reverse order).
Declaration:const_reverse_iterator rend () const
++ Increment iterator.
-- Decrement iterator.

STL list:

Two examples: the first for the data type int second for class instance Example 1:

Standard Template Library Example

#include <iostream>
#include <list>
using namespace std;< C4/>main ()
{
   list<int> L;
   L.push_back (0);              Insert a new element at the end
   L.push_front (0);             Insert a new element
   at the beginning L.insert (++l.begin (), 2);     Insert "2" before position of the argument
                                //(place before second argument)
   L.push_back (5);
   L.push_back (6);

   List<int>::iterator i;

   For (I=l.begin (); I!= l.end (); ++i) cout << *i << "";
   cout << Endl;
   return 0;
}


Example 2: If you use a custom type, you need to include the following: A. Copy constructors
B. Assignment operator (=) overload C. Less than operator overload < d. equals operator = = Overload
#include <iostream> #include <list> using namespace std;

The STL list needs to be overloaded operators =, = =.

   Class AAA {friend Ostream &operator<< (ostream, const AAA &);
      Public:int x;
      int y;

      float Z;
      AAA ();
      AAA (const AAA &);
      ~aaa () {};
      AAA &operator= (const AAA &AMP;RHS);
      int operator== (const AAA &AMP;RHS) const;
int operator< (const AAA &AMP;RHS) const;

};
   AAA::AAA ()//constructor {x = 0;
   y = 0;
z = 0;
   } aaa::aaa (const AAA &in)//copy constructor, pass value {x = copyin.x;
   y = copyin.y;
z = copyin.z;  } ostream &operator<< (ostream &output, const AAA &aaa) {output << aaa.x << ' <<
   Aaa.y << ' << aaa.z << Endl;
return output;
   } aaa& aaa::operator= (const AAA &AMP;RHS) {this->x = rhs.x;
   This->y = Rhs.y;
   This->z = rhs.z;
return *this; int aaa::operator== (const AAA &AMP;RHS) Const {if (this->x!= rhs.x) return 0;
   if (this->y!= rhs.y) return 0;
   if (this->z!= rhs.z) return 0;
return 1; //This function is to allow the STL list to support sort int aaa::operator< (const AAA &AMP;RHS) Const {if (this->x = = Rhs.x && THIS-&G
   T;y = = Rhs.y && this->z < rhs.z) return 1;
   if (this->x = = rhs.x && this->y < RHS.Y) return 1;
   if (This->x < rhs.x) return 1;
return 0;
   Main () {list<aaa> L;

   AAA Ablob;
   ablob.x=7;
   ablob.y=2;
   ablob.z=4.2355;  L.push_back (ABLOB);
   Inserts a new element at the end ablob.x=5;  L.push_back (ABLOB);
   Pass the value, using the default copy constructor//ablob.z=3.2355; 

   L.push_back (ABLOB);
   ablob.x=3;
   ablob.y=7;
   ablob.z=7.2355; 

   L.push_back (ABLOB);

   List<aaa>::iterator i; For (I=l.begin (); I!= l.end (); ++i) cout << (*i). x << "";      

   Print member cout << Endl; For (I=l.begin (); I!= l.end (); ++i) cout << *i << " ";

   Print with overloaded operator cout << Endl;
   cout << "Sorted:" << Endl;
   L.sort (); For (I=l.begin (); I!= l.end (); ++i) cout << *i << "";

   Print with overloaded operator cout << Endl;
return 0;

                
 }

Output results:
7 5 5 3 
7 2 4.2355
 5 2 4.2355
 5 2 3.2355
 3 7 7.2355
 
Sorted:
3 7 7.2355 5 2
 3.2355
 5 2 4.23
 7 2 4.2355

STL vector and list function comparison:
Function Vector List
Constructor Yes Yes
destructor Yes Yes
Empty () Yes Yes
Size () Yes Yes
Resize () Yes Yes
Capacity () Yes No
Reserve () Yes No
Max_size () Yes Yes
Erase () Yes Yes
Clear () Yes Yes
Operator= Yes Yes
operator< Yes Yes
operator== Yes Yes
Operator[] Yes No
at () Yes No
Front () Yes Yes
Back () Yes Yes
Push_back () Yes Yes
Pop_back () Yes Yes
Assign () Yes Yes
Insert () Yes Yes
Swap () Yes Yes
Push_front () No Yes
Pop_front () No Yes
Merge () No Yes
Remove () No Yes
Remove_if () No Yes
Reverse () No Yes
Sort () No Yes
Splice () No Yes
Unique () No Yes

Related Article

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.