Cpp Libs Vector
## Introduction
The C++ Standard Library (Standard Template Library, STL) is an important component of C++ that provides a set of generic template classes and functions for handling data collections. `` is a container class in STL used to store dynamically sized arrays.
`` is a sequence container that allows users to quickly add or remove elements at the end of the container. Compared to arrays, `` provides more features such as automatic resizing and random access.
### Syntax
In C++, using `` requires including the header file ``. Here are some basic syntax:
* Declare a `vector`:
std::vector myVector;
* Add an element:
myVector.push_back(10);
* Access an element:
int firstElement = myVector;
* Get the number of elements:
size_t size = myVector.size();
* Clear the `vector`:
myVector.clear();
### Declaration and Initialization
`` requires specifying the element type and can be initialized in various ways:
#include #include int main() { std::vector vec1; // Empty vector std::vector vec2(5); // Vector with length 5, elements default initialized std::vector vec3(5, 10); // Vector with length 5, element values are 10 std::vector vec4 = {1, 2, 3, 4}; // Initialize using initializer list return 0;}
## Example
Below is a simple example using ``, including the output.
## Example
#include
#include
int main(){
// Declare a vector to store integers
std::vector numbers;
// Add elements
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
// Output elements in the vector
std::cout<<"Vector contains: ";
for(int i =0; i < numbers.size();++i){
std::cout<< numbers<<" ";
}
std::cout<< std::endl;
// Add more elements
numbers.push_back(40);
numbers.push_back(50);
// Output elements in the vector again
std::cout<<"After adding more elements, vector contains: ";
for(int i =0; i < numbers.size();++i){
std::cout<< numbers<<" ";
}
std::cout<< std::endl;
// Access specific element
std::cout<<"The first element is: "<< numbers<< std::endl;
// Clear the vector
numbers.clear();
// Check if vector is empty
if(numbers.empty()){
std::cout<<"The vector is now empty."<< std::endl;
}
return 0;
}
Output:
Vector contains: 10 20 30 After adding more elements, vector contains: 10 20 30 40 50 The first element is: 10 The vector is now empty.
* * *
## Common Member Functions
Here are some commonly used member functions in ``:
| Function | Description |
| --- | --- |
| `push_back(const T& val)` | Add element at the end |
| `pop_back()` | Remove element at the end |
| `at(size_t pos)` | Return element at specified position, with bounds checking |
| `operator[]` | Return element at specified position, without bounds checking |
| `front()` | Return the first element |
| `back()` | Return the last element |
| `data()` | Return pointer to underlying array |
| `size()` | Return current number of elements |
| `capacity()` | Return currently allocated capacity |
| `reserve(size_t n)` | Reserve storage for at least `n` elements |
| `resize(size_t n)` | Adjust number of elements to `n` |
| `clear()` | Remove all elements |
| `insert(iterator pos, val)` | Insert element at specified position |
| `erase(iterator pos)` | Remove element at specified position |
| `begin()`[/ `end()`](#) | Return beginning/ending iterator |
### Examples
**1γBasic Operations**
## Example
#include
#include
int main(){
std::vector vec ={1, 2, 3, 4, 5};
// Output all elements
std::cout<<"Vector elements: ";
for(int i =0; i < vec.size();++i){
std::cout<< vec<<" ";
}
std::cout<< std::endl;
// Get first and last elements
std::cout<<"First element: "<< vec.front()<< std::endl;
std::cout<<"Last element: "<< vec.back()<< std::endl;
return 0;
}
**2γDynamically Add and Remove Elements**
## Example
#include
#include
int main(){
std::vector vec;
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
std::cout<<"Vector size: "<< vec.size()<< std::endl;
std::cout<<"Vector capacity: "<< vec.capacity()<< std::endl;
// Remove last element
vec.pop_back();
std::cout<<"After pop_back, size: "<< vec.size()<< std::endl;
return 0;
}
**3γBounds Checking and Safe Access**
## Example
#include
#include
int main(){
std::vector vec ={1, 2, 3};
try{
std::cout<< vec.at(2)<< std::endl;// Normal output
std::cout<< vec.at(5)<< std::endl;// Out of range, throws exception
}catch(const std::out_of_range& e){
std::cout<<"Exception: "<< e.what()<< std::endl;
}
return 0;
}
**4γPre-allocate Capacity**
## Example
#include
#include
int main(){
std::vector vec;
vec.reserve(10);// Reserve capacity, avoid frequent memory allocation
for(int i =0; i <10;++i){
vec.push_back(i);
std::cout<<"Capacity after push_back("<< i <<"): "<< vec.capacity()<< std::endl;
}
return 0;
}
### Comparison with Other Containers
| Feature | `std::vector` | `std::array` | `std::list` |
| --- | --- | --- | --- |
| **Size** | Dynamically variable | Fixed at compile time | Dynamically variable |
| **Storage Location** | Contiguous memory | Contiguous memory | Non-contiguous memory |
| **Access Performance** | Fast random access | Fast random access | Slow random access, suitable for sequential access |
| **Insert and Delete Performance** | High performance for end operations, slower for other positions | Not supported | Faster insertion and deletion at any position |
| **Memory Growth** | Grows exponentially when capacity is insufficient | N/A | N/A |
`` is a very useful container in C++ STL that provides dynamic array functionality, making element addition and deletion more flexible and convenient. Through the above examples, beginners can quickly understand the basic usage and operations of ``. As you delve deeper into learning, you will discover the powerful functionality and wide applications of `` in practical programming.
YouTip