c++ std::vector
时间: 2023-10-27 22:43:38 浏览: 52
std::vector is a container in C++ STL (Standard Template Library) that is used to store a dynamic array of elements. It is similar to an array, but it can automatically resize itself when new elements are added or removed. The elements in a std::vector are stored in contiguous memory locations, making it easy to access them using iterators or indices.
The syntax for declaring a std::vector is:
std::vector<DataType> vectorName;
Where DataType is the type of elements that are going to be stored in the vector and vectorName is the name of the vector.
Some of the commonly used functions of std::vector are:
- push_back(): Adds an element to the end of the vector
- pop_back(): Removes the last element from the vector
- size(): Returns the number of elements in the vector
- empty(): Returns true if the vector is empty, false otherwise
- clear(): Removes all the elements from the vector
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector;
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
for (int i = 0; i < myVector.size(); i++) {
std::cout << myVector[i] << " ";
}
std::cout << std::endl;
myVector.pop_back();
for (auto it = myVector.begin(); it != myVector.end(); it++) {
std::cout << *it << " ";
}
std::cout << std::endl;
myVector.clear();
std::cout << "Vector size after clear(): " << myVector.size() << std::endl;
return 0;
}
Output:
10 20 30
10 20
Vector size after clear(): 0
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)