Vector usage in C + +

Source: Internet
Author: User

(1) vector< type > identifier;
(2) vector< type > identifier (maximum capacity);
(3) vector< type > identifier (maximum capacity, initial all values);
(4) int i[4] = {12,3,4,5};
vector< type > VI (i, i+2);//Get the value of I index value after 3;

(5) vector< vector >//vi define 2-dimensional containers; Remember to have a space, or you will get an error.

1. Detailed instructions in C + +

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 a container because it can store various types of objects like a container,
Simply put, vector is a dynamic array that can hold any type, adding and compressing data.

2. Using vectors

You must include the following code in your header file:
  #include <vector>
vector belongs to the STD named domain, so you need to pass a name qualification to complete your code as follows:
using Std::vector;
vector vints;
or even together , using full name:  
    std::vector vints;

    using namespace std;

3. Initialize

Vector//Create an empty vector.
Vector C1 (c2)//Copy a vector
Vector c (n)//create a vector containing n data, the data is constructed by default
Vector c (n, elem)//create a vector containing n elem copies
Vector C (beg,end)//create a vector containing n elem copies

4. Destructors

C.~vector ()//Destroy all data, free memory

5. member functions

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 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 ()//Determine if the container is empty.
c.end ()//points to the next end element in the iterator, pointing to a nonexistent element.
c.erase (POS)//Deletes the POS location data and returns the location of the next data.
c.erase (beg,end)//delete the data from the [Beg,end] interval, passing back the position of the next data.
C.front ()//returns the first data.

Get_allocator//Use the constructor to return a copy.

C.insert (Pos,elem)//Insert a elem copy at the POS location and return to the new data location.
C.insert (Pos,n,elem)//insert n elem data at POS location. no return value.
C.insert (pos,beg,end)//The data in the [Beg,end] interval is inserted at the POS location. no return value.   
c.max_size ()//returns the maximum number of data in the container.
c.pop_back ()//delete the last data.
C.push_back (Elem)//Add a data at the tail.
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 ()//reserve the appropriate capacity.
c.size ()//returns the number of actual data in the container.
c1.swap (C2)
Swap (C1,C2)//swap c1 and C2 elements. Above operation.

operator[]//Returns a reference to the specified position in the container.

6. Usage Examples:6.1. Create a vector

vector containers provide a variety of ways to create, and here are a few common ones.
create an empty vector object of type widget:
vector vwidgets;
  
create a vector containing data for 500 widget types:
Vector vwidgets (+);
  
create a vector containing 500 widget-type data and initialize it to 0:
Vector vwidgets (+, Widget (0));
  
to create a copy of a widget:
Vector Vwidgetsfromanother (vwidgets);
  
adding a data to a vector
the 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: adding 10 data to a vector requires writing code like this:
for (int i= 0;i<10; i++) {
Vwidgets.push_back (Widget (i));
}

6.2 Getting the data at the specified position in the vector

The 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 the fantasy is set to-1,
You can use the following code to implement:
int nSize = V.empty ()? -1:static_cast (V.size ());  

6.3 Accessing data in a vector

use 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 v;
V.reserve (ten);
  
for (int i=0; i<7; i++) {
V.push_back (i);
}
  
try {int iVal1 = v[7];
//Not bounds Checked-will not throw
int iVal2 = v.at (7);
//Bounds Checked-will throw if out of range
}
    
catch (const exception& e) {
cout << e.what ();
}

6.3 Deleting data from a vector

vector very easy to add data , it is also easy to take out the data,
the same vector provides erase (), Pop_back (), Clear () To delete data,
When you delete data, you should know whether to delete the trailing data, or whether to 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

remove_if () has three parameters:
1, iterator _ First: An iterative pointer to the data.
2, iterator _last: An iterative pointer to the last data.
3, predicate _pred: A conditional function that can operate on an iteration.

6.4 Bar Functions

A conditional 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, 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
enum Findmodes {
fm_invalid = 0,
Fm_is,
Fm_startswith,
Fm_endswith,
Fm_contains
};

typedef struct TAGFINDSTR {
UINT IMode;
CString szmatchstr;
} FindStr;


typedef findstr* LPFINDSTR;
  
then the processing condition is judged:

Class Findmatchingstring:public Std::unary_function {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->s  ZMATCHSTR);  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,
the data that needs to be deleted. 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.

7. General Examples:

---------------------------------------------------------------------------#include #pragma hdrstop#include " Unit1.h "//---------------------------------------------------------------------------#pragma package (smart_init ) #pragma resource "*.DFM" TForm1 *form1; #include #includeusing namespace std;struct stresult{    double time;    Double Xp;    Double Yp;    int id;};/ /---------------------------------------------------------------------------__fastcall Tform1::tform1 ( tcomponent* owner)    : Tform (owner) {}vector resultvector;void __fastcall Test () {    //test    //vector Resultvector;    Stresult stritem;    Stritem. Time =. 1;    Stritem. Xp =. 1;    Stritem. Yp =. 1;    Stritem.id = 1;    Resultvector.push_back (stritem);} ---------------------------------------------------------------------------void __fastcall TForm1:: Button1Click (TObject *sender) {    test ();    ASSERT (Resultvector[0].id = = 1);}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Vector usage in C + +

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.