要判断 presentNIC
向量是否为空并在非空的情况下清除数据,可以使用 std::vector
的 empty()
方法和 clear()
方法。下面是一个示例代码:
#include <iostream>
#include <vector>
static std::vector<int> presentNIC;
int main() {
// 示例:添加一些数据到 presentNIC 中
presentNIC.push_back(1);
presentNIC.push_back(2);
// 判断向量是否为空,如果不是空的,清除数据
if (!presentNIC.empty()) {
std::cout << "presentNIC is not empty. Clearing data..." << std::endl;
presentNIC.clear(); // 清除数据
} else {
std::cout << "presentNIC is empty." << std::endl;
}
// 检查清除后的状态
if (presentNIC.empty()) {
std::cout << "presentNIC has been cleared." << std::endl;
}
return 0;
}
代码说明
#include <iostream>
和#include <vector>
:包含必要的头文件。static std::vector<int> presentNIC;
:声明一个静态整数向量。push_back()
:用于向向量中添加元素(这里只是为了演示,实际使用时可能不需要这一步)。empty()
:检查向量是否为空,返回 true 如果为空。clear()
:如果不为空,则调用此方法来清空向量中的所有元素。
输出结果
如果运行上述程序,输出将会是:
presentNIC is not empty. Clearing data...
presentNIC has been cleared.
这个过程确保了在每次检查前,不论何时对 presentNIC
的内容都能正确地处理。如果有任何其他问题,请随时问我!
内容由零声教学AI助手提供,问题来源于学员提问