21xrx.com
2025-06-14 03:14:51 Saturday
文章检索 我的文章 写文章
C++如何判断一个变量是否为空?
2023-07-12 07:05:00 深夜i     96     0
C++ 判断 变量 为空

在C++中,判断一个变量是否为空的方法取决于变量的类型。以下是几种常见类型的判断方法:

1. 普通指针:可以使用指针是否为NULL来判断是否为空。例如:

int* ptr = NULL;
if (ptr == NULL)
  cout << "ptr is empty" << endl;
else
  cout << "ptr is not empty" << endl;

2. 智能指针:智能指针对象会重载bool运算符,因此可以直接判断智能指针对象是否为空。例如:

shared_ptr<int> sPtr;
if (!sPtr)
  cout << "sPtr is empty" << endl;
else
  cout << "sPtr is not empty" << endl;

3. 字符串:可以使用字符串的empty()方法来判断是否为空。例如:

string str = "";
if (str.empty())
  cout << "str is empty" << endl;
else
  cout << "str is not empty" << endl;

4. 容器类:可以使用容器类对象的empty()方法来判断是否为空。例如:

vector<int> vec;
if (vec.empty())
  cout << "vec is empty" << endl;
else
  cout << "vec is not empty" << endl;

总之,在C++中判断一个变量是否为空的方法因变量类型而异,需要根据具体情况采取相应的方法。

  
  

评论区