English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
in c++In it, vector is a very useful container. Below, through this article, we will introduce C++detailed description of the vector container is as follows
1. In C++detailed description
vector is a C++It is part of the Standard Template Library, which is a multifunctional library of template classes and functions that can operate on various data structures and algorithms.
The reason why vector is considered a container is that it can store various types of objects like a container. Simply put, vector is a dynamic array that can store any type of data, and it can increase and compress data.
2To use vector, you must include the following code in your header file:
#include
As vector belongs to the std namespace, it needs to be qualified with the namespace, as follows to complete your code:
using std::vector; vector vInts;
Or combine them together, using the full name:
std::vector vInts;
It is recommended to use the global namespace style:
using namespace std;
3. Initialization
vector // Create an empty vector. vector c1(c2) // Copy a vector vector c(n) // Create a vector containing n data, all data are generated by default construction. vector c(n, elem) // Create a vector containing n copies of elem. vector c(beg,end) // Create a vector containing n copies of elem.
4Destructor
c.~vector () // Destroy all data, release memory
5Member function
c.assign(beg,end)c.assign(n,elem)
Assign data in the interval [beg; end) to c. Assign copies of n elem to c.
c.at(idx)
Return the data pointed to by index idx, if idx is out of bounds, throw out_of_range.
c.back() // Return the last data without checking if the data exists.
c.begin() // Return the address of the first data in the iterator.
c.capacity() // Return the number of data in the container.
c.clear() // Remove all data in the container.
c.empty() // Determine whether the container is empty.
c.end() // Point to the next element of the end element of the iterator, pointing to a non-existent element.
c.erase(pos) // Delete the data at the position pos, return the position of the next data.
c.erase(beg,end) //Delete data in the interval [beg, end), return the position of the next data.
c.front() // Return the first data.
get_allocator // Return a copy using the constructor.
c.insert(pos,elem) // Insert a copy of elem at the position pos, return the new data position.
c.insert(pos,n,elem) // Insert n elem data at the position pos. No return value.
c.insert(pos,beg,end) // Insert data in the interval [beg, end) at the position pos. No return value.
c.max_size() // Return the number of maximum data in the container.
c.pop_back() // Delete the last data.
c.push_back(elem) // Add a data at the end.
c.rbegin() // Return the first data in the reversed queue.
c.rend() // Return the next position of the last data in the reversed queue.
c.resize(num) // Respecify the length of the queue.
c.reserve() // Reserve appropriate capacity.
c.size() // Returns the actual number of data in the container.
c1.swap(c2)
swap(c1,c2) // To c1and c2Element swapping. The operation is the same as above.
operator[] // Returns a reference to the specified position in the container.
6. Usage example:
6.1. Create a vector
The vector container provides various creation methods, and the following introduces several commonly used ones.
Create an empty vector object of type Widget:
vector vWidgets;
Create a vector containing500 a vector of Widget type data:
vector vWidgets(500);
Create a vector containing500 a vector of Widget type data, and all initialized to 0:
vector vWidgets(500, Widget(0));
Create a copy of Widget:
vector vWidgetsFromAnother(vWidgets);
Add a data to the vector
push_back() is the default method for adding data to the vector.
push_back() function indicates that the data is added to the end of the vector, and memory is allocated as needed.
For example: add to the vector10data, you need to write the code as follows:
for(int i= 0;i<10; i++) { vWidgets.push_back(Widget(i)); }
6.2 Get data at a specified position in the vector
The data in the vector is dynamically allocated, and the allocation space by the series of push_back() often depends on the file or some data source.
If you want to know how many data the vector stores, you can use empty().
You can use size() to get the size of the vector.
For example, if you want to get the size of a vector v but do not know if it is empty or already contains data, and if it is empty, you want to set it to-1, you can implement it with the following code:
int nSize = v.empty() &63; -1 : static_cast(v.size());
6.3 Accessing data in the vector
Two methods are used to access the vector.
1, vector::at()
2, vector::operator[]
operator[] is mainly used for compatibility with C language. It can operate like a C language array.
But at() is our preference because at() performs boundary checks, and if the access exceeds the range of the vector, it will throw an exception.
Since operator[] is prone to errors, we rarely use it, and let's verify it below:
Analyze the following code:
vector v; v.reserve(10); 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 from vector
Vector can easily add data, and it is also very convenient to 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, all data, or individual data.
If you want to use remove_if(), you need to include the following code in the header file:
#include
Remove_if() has three parameters:
1iterator _First: a pointer to the first data iteration.
2iterator _Last: a pointer to the last data iteration.
3predicate _Pred: a condition function that can be used for iteration operations.
6.4 Condition function
The condition function is a function pointer that returns a yes or no result according to the user-defined condition, which is the most basic function pointer or a function object.
This function object needs to support all function call operations, and overload the operator()() operation.
remove_if() is inherited from unary_function, allowing data to be passed as a condition.
For example, if you want to delete matching data from a vector, if the string contains a value, start from this value and end at this value.
Firstly, a data structure should be established to contain these data, 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 handle the condition judgment:
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->szMatchStr); break; } case FM_CONTAINS: { retVal = (szStringToCompare.Find(m_lpFDD->szMatchStr) != -1); break; } } return retVal; } private: LPFINDSTR m_lpFS; };
Through 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(), remove_if(), etc., are based on an iterator range and cannot operate on the data within the container.
Therefore, when using remove_if(), the operation is actually performed on the data above the container.
You can see that remove_if() actually modifies the iterator addresses based on the condition, and there are some residual data at the end of the data, which are the data that need to be deleted. The position of the remaining data may not be the original data, but they are not aware of it.
Use erase() to delete the residual data.
Pay attention to the example above where the erase() function is used to delete the result of remove_if() and the data within the vs.enc() range.
7Comprehensive 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 what the editor has introduced to everyone about C++Detailed instructions for using the vector container in vector, hoping it will be helpful to everyone. If you have any questions, please leave me a message, and the editor will reply to everyone in time. Here we also express our heartfelt thanks to everyone for their support of the Naihua Tutorial website!
Declaration: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, does not undergo人工 editing, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When reporting, please replace # with @ in the email and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)