Cpp Libs Vector Clear
[ C++ Container Class ](#)
* * *
`clear` is a function in vector used to **clear all elements**, and is the simplest and most efficient way to empty a container.
`clear` is a member function of the container class, used to **delete all elements in the container**, making the container empty. After calling, the container's `size()` will become 0.
`clear` is the standard method to reset a container, commonly used in scenarios where you need to start over or release memory.
**Word meaning**: `clear` means "to remove", i.e., delete all elements.
* * *
## Basic Syntax and Parameters
`clear` is a member function of the container class, and calling it requires no parameters.
### Syntax Format
void clear();
### Parameter Description
* **Parameters**: No parameters
* `clear` does not accept any parameters.
### Function Description
* **Return value**: `void` (no return value).
* **Effect**: Deletes all elements in the container, `size()` becomes 0. `capacity()` usually remains unchanged (depending on the specific implementation).
* **Note**: `clear` does not release underlying memory, capacity remains unchanged. If you want to release memory at the same time, you can use the `swap` technique.
* * *
## Examples
Let's thoroughly master the usage of `clear` through a series of examples.
### Example 1: Basic Usage - Clearing a Container
## Example
#include
#include
int main(){
std::vector numbers ={1, 2, 3, 4, 5};
std::cout<<"Before clear - size: "<< numbers.size()
<<", capacity: "<< numbers.capacity()<< std::endl;
// Clear all elements
numbers.clear();
std::cout<<"After clear - size: "<< numbers.size()
<<", capacity: "<< numbers.capacity()<< std::endl;
return 0;
}
**Expected Output:**
Before clear - size: 5, capacity: 5After clear - size: 0, capacity: 5
**Code Analysis:**
1. `clear()` changes `size()` to 0.
2. `capacity()` remains unchanged, memory is not released.
### Example 2: Re-adding Elements After Clearing
A cleared container can continue to be used.
## Example
#include
#include
#include
int main(){
std::vector tasks;
// Add tasks
tasks.push_back("Learn C++");
tasks.push_back("Complete homework");
tasks.push_back("Read documentation");
std::cout<<"Task list ("<< tasks.size()<<" items):"<< std::endl;
for(const auto& t : tasks){
std::cout<<"- "<< t << std::endl;
}
// Clear task list
tasks.clear();
std::cout<<"n After clear ("<< tasks.size()<<" items)"<< std::endl;
// Can continue to add new tasks
tasks.push_back("New Task A");
tasks.push_back("New Task B");
std::cout<<"n After re-adding ("<< tasks.size()<<" items):"<< std::endl;
for(const auto& t : tasks){
std::cout<<"- "<< t << std::endl;
}
return 0;
}
**Expected Output:**
Task list (3 items):- Learn C++- Complete homework- Read documentationAfter clear (0 items)After re-adding (2 items):- New Task A - New Task B
**Code Analysis:**
* After `clear()`, the container can continue to be used.
* Since capacity remains unchanged, re-adding elements does not require reallocation of memory.
### Example 3: Using empty() to Check Clear Status
After `clear()`, you can use `empty()` to check if the container is empty.
## Example
#include
#include
void processData(std::vector& data){
std::cout<<"Processing data, currently has "<< data.size()<<" elements..."<< std::endl;
// Process data...
// Clean up data
data.clear();
std::cout<<"Data cleared"<< std::endl;
}
int main(){
std::vector cache ={1, 2, 3, 4, 5};
// Simulate cache usage
for(int i =0; i <3;++i){
cache.push_back(cache.size()+1);
std::cout<<"After adding element - size: "<< cache.size()
<<", empty: "<<(cache.empty()?"true":"false")<< std::endl;
}
// Clear cache
cache.clear();
std::cout<<"After clear - empty: "<<(cache.empty()?"true":"false")<< std::endl;
return 0;
}
**Expected Output:**
After adding element - size: 6, empty: falseAfter adding element - size: 7, empty: falseAfter adding element - size: 8, empty: falseAfter clear - empty: true
**Code Analysis:**
* `empty()` returns `true` when `size() == 0`.
* After `clear()`, `empty()` returns `true`.
### Example 4: Completely Releasing Memory
If you want to release memory while clearing elements, you can use the `swap` technique.
## Example
#include
#include
int main(){
std::vector numbers;
// Add a large number of elements
for(int i =0; i <1000;++i){
numbers.push_back(i);
}
std::cout<<"Before clear - size: "<< numbers.size()
<<", capacity: "<< numbers.capacity()<< std::endl;
// Method 1: only clear (does not release memory)
numbers.clear();
std::cout<<"After clear() - size: "<< numbers.size()
<<", capacity: "<< numbers.capacity()<< std::endl;
// Method 2: using swap technique (releases memory)
std::vector().swap(numbers);
std::cout<<"After swap - size: "<< numbers.size()
<<", capacity: "<< numbers.capacity()<< std::endl;
return 0;
}
**Expected Output:**
Before clear - size: 1000, capacity: 1000 After clear() - size: 0, capacity: 1000 After swap - size: 0, capacity: 0
**Code Analysis:**
* `clear()` only clears elements, capacity remains unchanged.
* `std::vector().swap(numbers)` creates a temporary empty vector and swaps with numbers, completely releasing memory.
### Example 5: Using clear in a Loop
You can use `clear` in a loop to reset data.
## Example
#include
#include
int main(){
std::vector buffer;
buffer.reserve(100);
// Simulate multiple rounds of processing
for(int round =1; round <=3;++round){
// Fill data
for(int i =0; i <10;++i){
buffer.push_back(round *100+ i);
}
std::cout<<"Round "<< round <<" - Processing data: ";
for(int n : buffer){
std::cout<< n <<" ";
}
std::cout<< std::endl;
// Clear after processing, prepare for next round
buffer.clear();
}
std::cout<<"All rounds completed, final buffer size: "<< buffer.size()<< std::endl;
return 0;
}
**Code Analysis:**
* `clear()` can be used in a loop to reset the buffer.
* Used together with `reserve`, it can avoid frequent memory allocations.
* * C++ Container Class ](#)
YouTip