Vector container use in C + + detailed description _c language

Source: Internet
Author: User
Tags data structures

Vector is a very useful container in C + +, and here is a detailed description of vector container usage in C + +, as described below

1. Detailed instructions in C + +

Vector is part of the C + + Standard Template Library, a versatile template class and function library that can manipulate a variety of data structures and algorithms.

Vector is considered a container because it can hold various types of objects like a container, simply put, vector is a dynamic array of any type that can be stored to add and compress data.

2. Using vectors, you must include the following code in your header file:

#include

Vectors belong to the STD-named domain, so you need to have a naming qualification to complete your code as follows:

Using Std::vector;
Vector vints;

Or even together, using the full name:

Std::vector vints;

It is recommended that you use the global named Domain method:

using namespace Std;

3. Initialize

Vector//Create an empty vector.
Vector C1 (c2)//replication of a vector
C (n)///create a vector containing n data, all data are constructed by default to generate
vector c (n, elem)// Create a vector C (beg,end) with n elem copies and/
/create a vector containing n copies of Elem

4. destructor

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

5. member functions

C.assign (beg,end) c.assign (N,elem)
Assign the data in the [Beg end] interval to C. Assign a copy of n elem to C.
c.at (IDX)
Returns the data that the index IDX refers to, and throws the Out_of_range if the IDX crosses over.
C.back ()//returns the last data and does not check if the data exists.
C.begin ()//returns the first data address in the iterator.
C.capacity ()//Returns the number of data in the container.
C.clear ()//Remove all data from the container.
C.empty ()//To determine whether the container is empty.
C.end ()//points to the next end element in the iterator, pointing to a nonexistent element.
C.erase (POS)//delete POS position data and return the location of the next data.
C.erase (beg,end)//delete data from the [beg,end) interval and return the location of the next data.
C.front ()//returns the first data.
Get_allocator//Use constructors to return a copy.
C.insert (Pos,elem)//Inserts a elem copy at the POS position and returns the new data location.
C.insert (Pos,n,elem)//insert n elem data at POS position. no return value.
C.insert (Pos,beg,end)//To insert data in the [Beg,end] interval at the POS position. no return value.
C.max_size ()//returns the maximum number of data in the container.
C.pop_back ()///delete last data.
C.push_back (Elem)//Add a data to the tail.
C.rbegin ()//returns the first data of 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. Ditto 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.

To create an empty vector object of the widget type:

Vector vwidgets;

Create a vector that contains 500 widget type data:

Vector Vwidgets (500);

Creates a vector that contains 500 widget type data and is initialized to 0:

Vector vwidgets, Widget (0));

Create a copy of the widget:

Vector Vwidgetsfromanother (vwidgets);

Add a data to the vector

The vector's default method for adding data is push_back ().

The Push_back () function represents adding data to the tail of the vector and allocating memory as needed.

For example, to add 10 data to a vector, you need to write the following code:

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 spaces using push_back () is often determined by the file or some data source.

If you want to know how much data the vector holds, you can use empty ().

Gets the size of the vector, you can use size ().

For example, if you want to get the size of a vector v, but you don't know if it's empty, or if you've already included the data, if you set it 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 preferred option because at () has a boundary check and if the access exceeds the vector range, an exception will be thrown.

Because operator[] is prone to making some errors, all of us rarely use it, and the following is validated:

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 Delete data in a vector

Vectors can be very easy to add data, but also easy to extract data, the same vector provides erase (), Pop_back (), clear () to delete data, when deleting data, should know to delete the tail of the data, or delete all 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 first 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 Piece function

A conditional function is a result that returns Yes or no according to a user-defined condition, is the most basic function pointer, or a function object.

This function object needs to support all function invocation operations, overloading the Operator () () operation.

Remove_if () is inherited through unary_function, allowing data to be passed as a condition.

For example, if you want to remove a matching data from a vector, if the string contains a value, starting from this value, end from this value.

First, you should create a data structure to contain these, 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 conditions are 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_l   Pfdd->szwindowtitle);
break;
Case
Fm_endswith: {
retVal = (Szstringtocompare.right (m_lpfdd->szmatchstr.getlength ())
= = M_lp  FDD->SZMATCHSTR);
break;
Case
fm_contains: {
retVal = (Szstringtocompare.find (m_lpfdd->szmatchstr)!=-1);
break;
}
return
retVal;
}
Private:
lpfindstr M_lpfs;

In this way you can effectively delete data from vectors:

FINDSTR FS;
Fs.imode = Fm_contains;
Fs.szmatchstr = Szremove;
Vs.erase (Std::remove_if (Vs.begin (), Vs.end (), findmatchingstring (&FS)), Vs.end ());

All the removal operations, such as remove (), remove_if (), are built on an iterative scale and cannot manipulate the data in the container.

So when using remove_if (), the actual operation of the data in the container is above.

See Remove_if () actually modifies the iteration address according to the condition, and there are some residual data behind the data, the data that needs to be deleted. The rest of the data may not be in the original data, but they don't know it.

Call Erase () to delete the remaining data.

Note that the result of remove_if () and the Vs.enc () range of data are deleted by erase () in the above example.

7. Integrated Examples:

---------------------------------------------------------------------------#include #pragma hdrstop #include " Unit1.h "//---------------------------------------------------------------------------#pragma package (smart_init
) #pragma resource "*.DFM" TForm1 *form1;
#include #include using 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);//----------------------------------------- ----------------------------------

The above is described in the small series of C + + vector containers used in detailed instructions, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.