Vector usage in C ++

Source: Internet
Author: User

Vector usage in C ++

Vector is part of the content in the C ++ standard template library. It is a versatile template class and function library that can operate on multiple data structures and algorithms.

Vector Chinese is occasionally translated as "container", but it is not accurate. It is a versatile template class and function library that can operate on multiple data structures and algorithms.

The simple method is as follows:

Vector <int> test; // creates a vector.

Test. push_back (1 );

Test. push_back (2); // press 1 and 2 into a vector. In this case, test [0] is 1, and test [1] is 2.

We can use an iterator:

Vector <int>: iterator iter = test. begin (); // defines an iterator iter that can iterate the int-type vector. It points to the first place of test.

For (; iter! = Test. end (); iter ++) cout <(* iter); // iter ++ refers to a Forward Iteration until iter reaches the end of The iterator, value pointed by the output iterator

 

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 store any type, data can be added and compressed.
To use vector, you must include the following code in your header file:
# Include <vector>
Vector belongs to the std naming field. Therefore, you need to complete the Code as follows:
Using std: vector;
Vector <int> vInts;
Or, use the full name:
Std: vector <int> vInts;
We recommend that you use the global namespace std with a small amount of code and a small namespace;
 

Function

Vector <int> c; // creates a vector.

Statement
C. assign (beg, end) c. assign (n, elem)
Value the data in the (beg; end) interval to c. Assign a copy of n elem values to c.
C. at (idx)
Returns the data indicated by the index idx. If idx is out of bounds, out_of_range is thrown.
C. back ()
Returns the last data and does not check whether 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 ()
Determines whether the container is empty.
C. end () // points to the next of the end Element in the iterator and to a nonexistent element.
C. erase (pos) // Delete the data at the pos location and return the next data location.
C. erase (beg, end)
Delete the data in the [beg, end) interval and return the location of the next data.
C. front ()
Returns the first data.
Get_allocator
Returns a copy using the constructor.
C. insert (pos, elem) // insert an elem copy at the pos position to return the new data location
C. insert (pos, n, elem) // insert n elem data at the pos position, no return value
C. insert (pos, beg, end) // 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 the last data.
C. push_back (elem)
Add a data entry to the end.
C. rbegin ()
Returns the first data of a reverse queue.
C. rend ()
Returns the next location of the last data in a reverse queue.
C. resize (num)
Specify the length of the queue again.
C. reserve ()
Reserve the appropriate capacity.
C. size ()
Returns the actual number of data in the container.
C1.swap (c2) // swap c1 and c2 Elements
Swap (c1, c2) // same as above.
Vector <Elem> // create an empty vector
Vector <Elem> c1 (c2) // copy a vector
Vector <Elem> c (n) // creates a vector Containing n pieces of data, which are generated by default.
Vector <Elem> c (n, elem) // create a vector Containing n elem copies
Vector <Elem> c (beg, end) // create a vector in the range of (beg; end)
C .~ Vector <Elem> () // destroys all data and releases the memory.
Operator []
Returns a reference from a specified position in the container.
Create a vector
The vector container provides multiple creation methods. The following describes several common methods.
Create an empty vector object of the Widget type:
Vector <Widget> vWidgets;
Create a vector containing 500 Widget data:
Vector <Widget> vWidgets (500 );
Create a vector containing 500 Widget data and initialize it to 0:
Vector <Widget> vWidgets (500, Widget (0 ));
Create a copy of a Widget:
Vector <Widget> vWidgetsFromAnother (vWidgets );
Add a data entry to the vector
The default method for adding data to a vector is push_back (). The push_back () function adds data to the end of the vector and allocates memory as needed.

For example, to add 10 pieces of data to vector <Widget>;, you need to write the following code: for (int I = 0; I <10; I ++) {vWidgets. push_back (Widget (I ));}

Obtains data at a specified position in a vector.
Data in a vector is dynamically allocated. A series of space allocated using push_back () is often determined by files or some data sources. If you want to know whether the vector is null, you can use empty (). If it is null, true is returned. Otherwise, false is returned. Returns the vector size. You can use size (). For example, if you want to obtain the size of a vector v, but do not know whether it is null, or if it already contains data, if you want to set it to-1, you can use the following code:
Int nSize = v. empty ()-1: static_cast <int> (v. size ());
Access data in a vector
Use two methods to access the vector.
1. vector: ()
2. vector: operator []
Operator [] is mainly used for compatibility with the C language. It can be operated like a C array. However, at () is our first choice, because at () performs a boundary check. If the access exceeds the vector range, an exception is thrown. Operator [] may cause some errors, so we seldom use it. perform the following verification:
Analyze the following code:
Vector <int> v;
V. reserve (10 );
For (int I = 0; I <7; I ++ ){
V. push_back (I); // Add seven data records to the end of V.
}
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 ();
}
Delete data in a vector
Vector can easily add and retrieve data. Similarly, vector provides erase (), pop_back (), and clear () to delete data. When deleting data, you should know whether to delete the tail data, delete all data, or some data.
To use the remove () algorithm, you must include the following code in the header file:
# Include <algorithm>
Remove has three parameters:
1. iterator _ First: iteration pointer to the First data.
2. iterator _ Last: iteration pointer pointing to the Last data.
3. predicate _ Pred: a conditional function that can operate on iterations.
Conditional Functions
A conditional function is a result that returns yes or no according to user-defined conditions. It is the most basic function pointer or a function object. This function object must support all function call operations and overload operator () operations. Remove is inherited by unary_function and data can be transmitted as a condition.
For example, if you want to delete the matched data from a vector <CString>;, if the string contains a value, the value starts and ends. First, you should establish a data structure to include the data. The Code is as follows:
# Include <functional>
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 <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 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 ());
All removal operations, such as Remove () and remove, are based on an iteration range and cannot operate the data in the container. So when you use remove, the above data in the container is actually operated.
We can see that the remove operation is actually modifying the iteration address based on the conditions. There is some residual data behind the data and the data to be deleted. The location of the remaining data may not be the original data, but they do not know.
Call erase () to delete the residual data. Note that in the preceding example, the remove result and the data in the range of vs. enc () are deleted through erase.
Common Errors:
No matching function for call to 'std: vector, which is generally caused by a mismatch between the defined type and the saved type.

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.