当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ vector::empty()用法及代码示例


C++ vector::empty() 函数

vector::empty() 是 "vector" 头文件的库函数,用于检查给定的向量是否为空向量,如果向量大小为 0 则返回真,否则返回假。

注意:要使用矢量,请包括<vector>标题。

vector::empty() 函数的语法

    vector::empty();

参数: void– 它不接受任何参数。

返回值: bool– 如果向量大小为 0,则返回 true,否则返回 false。

例:

    Input:
    vector<int> vector1{ 1, 2, 3, 4, 5 };
    vector<int> vector2;

    Function call:
    cout << vector1.empty() << endl;
    cout << vector2.empty() << endl;

    Output:
    false
    true

C++程序演示vector::empty()函数的例子

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

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

int main()
{
    vector<int> v1;

    //printing the size of the vector
    cout << "Total number of elements:" << v1.size() << endl;
    //checking whether vector is empty or not
    if (v1.empty())
        cout << "vector is empty." << endl;
    else
        cout << "vector is not empty." << endl;

    //pushing elements
    v1.push_back(10);
    v1.push_back(20);
    v1.push_back(30);
    v1.push_back(40);
    v1.push_back(50);

    //printing the size of the vector
    cout << "Total number of elements:" << v1.size() << endl;
    //checking whether vector is empty or not
    if (v1.empty())
        cout << "vector is empty." << endl;
    else
        cout << "vector is not empty." << endl;

    return 0;
}

输出

Total number of elements:0
vector is empty.
Total number of elements:5
vector is not empty.

参考:C++ vector::empty()



相关用法


注:本文由纯净天空筛选整理自 vector::empty() function with example in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。