C++ <vector> clear function

C++ container class <vector>


clearis used in vector toClear all elementsThe function is the simplest and most efficient way to clear a container.

clearis a member function of the container class, used toremove all elements from the container, making the container empty. After the call, the container'ssize()will become 0.

clearis the standard method for resetting a container, often used in scenarios where you need to start over or release memory.

Word Definitions: clearmeans "clear", that is, deleting all elements.


Basic syntax and parameters

clearis a member function of container classes; calling it requires no parameters.

Syntax format

void clear();

Parameter description

  • Parameter: No parameters
    • cleardoes not accept any parameters.

Function description

  • Return Value: void(no return value).
  • Effect: removes all elements from the container,size()becomes 0.capacity()usually remains unchanged (depending on the specific implementation).
  • Note: cleardoes not release the underlying memory, and the capacity remains unchanged. To release memory at the same time, you can useswapTechnology.

Example

Let's thoroughly master through a series of examples.clearUsage.

Example 1: Basic usage - clearing a container

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    std::cout << "Before clearing - size: " << numbers.size()
              << ", capacity: " << numbers.capacity() << std::endl;

    // Clear all elements
    numbers.clear();

    std::cout << "After clearing - size: " << numbers.size()
              << ", capacity: " << numbers.capacity() << std::endl;

    return 0;
}

Expected output:

清空前 - size: 5, capacity: 5
清空后 - size: 0, capacity: 5

Code analysis:

  1. clear()willsize()becomes 0.
  2. capacity()remains unchanged, and the memory is not released.

Example 2: re-adding elements after clearing

The cleared container can continue to be used.

Example

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> tasks;

    // Add a task
    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 the task list
    tasks.clear();

    std::cout << "\nAfter clearing ( << tasks.size() << items) << std::endl;

    // Can continue adding new tasks
    tasks.push_back(New task A);
    tasks.push_back(New task B);

    std::cout << "\nAfter re-adding ( << tasks.size() << " items):" << std::endl;
    for(const auto& t : tasks) {
        std::cout << "- " << t << std::endl;
    }

    return 0;
}

Expected output:

任务列表 (3 项):
- 学习 C++
- 完成作业
- 阅读文档

清空后 (0 项)

重新添加后 (2 项):
- 新任务 A
- 新任务 B

Code analysis:

  • clear()After clearing, the container can continue to be used.
  • Since the capacity remains unchanged, adding elements again does not require reallocating memory.

Example 3: Using empty() to check the cleared state

clear()Afterwards, you can useempty()Checks whether the container is empty.

Example

#include <iostream>
#include <vector>

void processData(std::vector<int>& data) {
    std::cout << Processing data, currently there are << data.size() << elements... << std::endl;

    // Process data...

    // Clean up data
    data.clear();
    std::cout << Data cleared << std::endl;
}

int main() {
    std::vector<int> 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 elements - size: << cache.size()
                  << ", empty: " << (cache.empty() ? "true" : "false") << std::endl;
    }

    // Clear cache
    cache.clear();
    std::cout << After clearing - empty: << (cache.empty() ? "true" : "false") << std::endl;

    return 0;
}

Expected output:

添加元素后 - size: 6, empty: false
添加元素后 - size: 7, empty: false
添加元素后 - size: 8, empty: false
清空后 - empty: true

Code analysis:

  • empty()returntrueWhensize() == 0When.
  • clear()After,empty()returntrue。

Example 4: completely releasing memory

To release memory while clearing the elements, you can useswapTechnology.

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;

    // Add a large number of elements
    for(int i = 0; i < 1000; ++i) {
        numbers.push_back(i);
    }

    std::cout << "Before clearing - size: " << numbers.size()
              << ", capacity: " << numbers.capacity() << std::endl;

    // Method 1: Only clear (without releasing memory)
    numbers.clear();
    std::cout << "After clear() - size: " << numbers.size()
              << ", capacity: " << numbers.capacity() << std::endl;

    // Method 2: Use the swap trick (to release memory)
    std::vector<int>().swap(numbers);
    std::cout << "After swap - size: " << numbers.size()
              << ", capacity: " << numbers.capacity() << std::endl;

    return 0;
}

Expected output:

清空前 - size: 1000, capacity: 1000
clear() 后 - size: 0, capacity: 1000
swap 后 - size: 0, capacity: 0

Code analysis:

  • clear()Only clears the elements, while the capacity remains unchanged.
  • std::vector().swap(numbers)Create a temporary empty vector and swap it with numbers to completely release the memory.

Example 5: Using clear in a loop

Can be used in a loopclearto reset the data.

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> 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;

        // After processing, clear to prepare for the 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.
  • CoordinationreserveUsing it can avoid frequent memory allocations.

C++ container class <vector>

other extensions