Introduction to Std::vector in C + + (GO)

Source: Internet
Author: User

Vector is part of the C + + Standard Template Library, which is a multifunctional template class and function library that can manipulate a variety of data structures and algorithms. Vector is considered to be a container because it can store various types of objects like a container, in short, a vector is a dynamic array that can hold any type and can add and compress data. In order to use the vector, you must include the following code in your header file:#include <vector>the vector belongs to the STD named domain, so you need to complete your code by naming the qualification as follows:using Std::vector;vector<int> vints;or even together, use the full name:std::vector<int> vints; 
It is recommended to use the global naming domain: UsingNamespace std;
Function
Expression
c.assign (beg,end) c.assign (N,elem) assigns the data in the [beg; end] Interval to C. assigns a copy of n elem to C.
c.at (IDX) Returns the index IDX refers to the data, if the IDX is out of bounds, throws Out_of_range.
C.back () Returns the last data without checking to see if the data exists.
C.begin () Returns the first data address in an iterator.
C.capacity () Returns the number of data in the container.
C.clear () Removes all data from the container.
C.empty () Determines whether the container is empty.
C.end () Points to the last data address in the iterator.
c.erase (POS) c.erase (beg,end) deletes data from the POS location and returns the location of the next data. Delete the data from the [Beg,end] interval and return to the location of the next data.
C.front () Returns the first data.
Get_allocator Use the constructor to return a copy.
C.insert (Pos,elem) C.insert (Pos,n,elem) C.insert (pos,beg,end) inserts a elem copy at the POS location and returns the new data location. inserts n elem data at the POS location. no return value. inserts the data in the [Beg,end] interval at the POS location. no return value.
C.max_size () Returns the maximum number of data in a container.
C.pop_back () Delete the last data.
C.push_back (Elem) Add a data to the trailer.
C.rbegin () Returns the first data for a reverse queue.
C.rend () Returns the next position of the last data in a reverse queue.
C.resize (num) Re-specify the length of the queue.
C.reserve () Keep the appropriate capacity.
C.size () Returns the number of actual data in the container.
c1.swap (C2) Swap (C1,C2) swaps the C1 and C2 elements. above operation.
vector<elem> c vector<elem> C1 (C2) vector <Elem> C (n) vector <Elem> C (n, Elem) vector <Elem> C (beg,end) c.~ vector <Elem> () Create an empty vector. Create a vector that contains n data, and the data is constructed by default. destroys all data and frees up memory. &NBSP;
Operator[] Returns a reference to the specified position in the container.
  Create a vectorvector containers provide a variety of ways to create, and here are a few common ones. create an empty vector object of type widget:
Vector<widget> vwidgets;
create a vector containing data for 500 widget types:
Vector<widget> Vwidgets (500);
create a vector containing 500 widget-type data and initialize it to 0:
Vector<widget> vwidgets (0);
to create a copy of a widget:
Vector<widget> Vwidgetsfromanother (vwidgets);
  adding a data to a vectorthe default method for vectors to add data is push_back (). The push_back () function means adding data to the tail of the vector and allocating memory as needed. For example: To add 10 data to vector<widget>, you need to write code like this:
for (int i= 0;i<10; i++) Vwidgets.push_back (Widget (i));
get data for the location in the vectorThe data in the vector is dynamically allocated, and a series of allocated space using push_back () is often determined by the file or some data source. If you want to know how much data the vector has stored, you can use empty (). Gets the size of the vector, which can be used with size (). For example, if you want to get the size of a vector v, but do not know if it is empty, or if it already contains data, if you set the fantasy to 1, you can use the following code:
int nSize = V.empty ()? -1:static_cast<int> (V.size ());
  accessing data in a vectoruse two methods to access the vector. 1, Vector::at ()2, vector::operator[]operator[] is primarily intended to be compatible with the C language. It can operate like an array of C languages. But at () is our first choice because at () has a boundary check, and if access exceeds the range of the vector, an exception will be thrown. Because operator[] is prone to some errors, all of which we seldom use it, verify below:Analyze the following code:
vector<int> v; v.reserve (ten); &NBSP; for (int i=0; i<7; i++)     v.push_back (i); &NBSP; try {  int ival1 = v[7]; //not Bounds Checked-will not throw  int ival2 = v.at (7);//Bounds Checked-wi ll throw if out of range } catch (const  exception& e) {  cout << e.what ();
  delete data from a vectorvectors can be very easy to add data, but also easy to take out data, the same vector provides erase (), Pop_back (), clear () to delete data, when deleting data, you should know to delete the tail of the data, or delete all the data, or individual data. remove_if () algorithm if you want to use REMOVE_IF (), you need to include the following code in the header file:
#include <algorithm>
remove_if () has three parameters:1. Iterator _first: An iterative pointer to the first data. 2. Iterator _last: An iterative pointer to the last data. 3, predicate _pred: A conditional function that can operate on an iteration. A conditional function condition function is a result of returning a yes or no according to a user-defined condition, which is the most basic function pointer, or a function object. This function object needs to support all function call operations, overloading the Operator () () operation. Remove_if () is inherited by Unary_function, allowing data to be passed as a condition. For example, if you want to delete a matching data from a vector<cstring>, if the string contains a value, start with that value and end with this value. The first thing you should do is create a data structure to contain this, similar to the following code:
#include  <functional> enum  findmodes  {  fm_invalid = 0,  fm_is,  fm_startswith,  fm_endswith,  fm_contains }; typedefstruct tagfindstr {  uint IMode;  cstring szmatchstr; FindStr; typedef findstr* lpfindstr;
 then the processing condition is judged:
class Findmatchingstring: Public std::unary_function<cstring, Bool>{    Public :findmatchingstring (const LPFINDSTR LPFS): M_lpfs (LPFS) {}    bool Operator () (cstring& szstringtocompare) const { bool RetVal = false; switch (m_lpfs->imode)     {Case fm_is:       { RetVal = (Szstringtocompare = = m_lpfdd->szmatchstr);Break ;       }Case Fm_startswith:       { RetVal = (Szstringtocompare.left (m_lpfdd->szmatchstr.getlength ())= = M_lpfdd->szwindowtitle);Break ;       } Case Fm_endswith:       {RetVal = (Szstringtocompare.right (m_lpfdd->szmatchstr.getlength ())= = m_lpfdd->szmatchstr);Break ;       } Case Fm_contains:       {RetVal = (Szstringtocompare.find (M_LPFDD->SZMATCHSTR)! =-1);Break ;       }     }        return retVal; }        Private:lpfindstr M_lpfs;};
 with this operation you can effectively delete the data from the vector:
FINDSTR FS; fs.imode = fm_contains; fs.szmatchstr = szremove; vs.erase (std::remove_if (Vs.begin (), Vs.end (), findmatchingstring (&FS)), Vs.end ());
Remove (), remove_if (), and all of the removal operations are based on an iteration scope and cannot manipulate the data in the container. So when using remove_if (), actually manipulate the top of the data in the container.  See remove_if () is actually based on the condition of the iteration address modified, there are some residual data behind the data, those who need to delete the data. The location of the remaining data may not be the original data, but they are not aware of it. Call Erase () to delete the remaining data. Note that the result of remove_if () and the Vs.enc () range of data are removed by erase () in the example above.

Introduction to Std::vector in C + + (GO)

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.