std::vector::clear()方法真的会清除元素吗?

发布时间 2023-03-22 21:16:01作者: azureology

测试

编译这样一段代码

int main()
{
    std::vector<size_t> vec{1,2,3};
    std::cout << vec.data() << std::endl;
    std::cout << *vec.data() << std::endl;
    std::cout << vec.size() << std::endl;
    vec.clear();
    std::cout << vec.data() << std::endl;
    std::cout << *vec.data() << std::endl;
    std::cout << vec.size() << std::endl;
    return 0;
}

输出结果为

Program returned: 0
0x1b57eb0
1
3
0x1b57eb0
1
0

可以发现clear()发生后首地址和所指元素值并为发生改变,仅size()归零。

解释

Clear content
Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function.

规避

使用swap方法则可以确保reallocation发生。

vector<T>().swap(x);   // clear x reallocating 

参考

https://cplusplus.com/reference/vector/vector/clear/#