當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ vector::clear()用法及代碼示例


C++ vector::clear() 函數

vector::clear() 是 "vector" 頭文件的庫函數,用於移除/清除向量的所有元素,在移除所有元素後生成 0 大小的向量。

注意:要使用矢量,請包括<vector>標題。

vector::clear() 函數的語法

    vector::clear();

參數: none——它什麽都不接受。

返回值: void——它什麽都不返回。

例:

    Input:
    vector<int> v1{ 10, 20, 30, 40, 50 };
    
    //clearing content of the vectors
    v1.clear();
    cout <> v1.size();

    Output:
    0

C++程序演示vector::clear()函數的例子

//C++ STL program to demonstrate example of
//vector::clear() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing elements
    cout << "before clearing the elements..." << endl;
    cout << "size of v1:" << v1.size() << endl;
    cout << "v1:";
    for (int x:v1)
        cout << x << " ";
    cout << endl;

    //clearing all elements
    v1.clear();

    //printing elements
    cout << "after clearing the elements..." << endl;
    cout << "size of v1:" << v1.size() << endl;
    cout << "v1:";
    for (int x:v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

輸出

before clearing the elements...
size of v1:5
v1:10 20 30 40 50
after clearing the elements...
size of v1:0
v1:

參考:C++ vector::clear()



相關用法


注:本文由純淨天空篩選整理自 vector::clear() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。