如何检查类实例向量的索引是否为空
How to Check if an Index of a Vector of Class Instances is Empty
我有一个名为Node
的类的实例向量。 我希望能够对是否填充向量的特定索引进行条件。
请参阅下面的示例代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Node {
int testVal;
public:
//Default Constructor
Node() {};
Node(int a){testVal = a;}
int getTestVal(){return testVal;}
};
int main(){
vector<Node> testVector;
testVector.resize(2);
Node testNode = Node(5);
testVector[1] = testNode;
for (int i = 0;i < 2;i++){
if (testVector[i] == NULL){
cout << "Missing Data" << endl;
}
else{
cout << testVector[i].getTestVal << endl;
}
}
}
代码在if
语句处崩溃。 如果特定索引为空,有什么好方法可以限定?
你问的是不可能的。
向量存储值而不是指针,因此您永远不会得到 null。
如果要检查"空"点,则声明一个存储节点地址的向量:
std::vector<std::shared_ptr<Node>> testVector;
要将项目存储在向量的第二个索引中,请执行以下操作:
testVector[1] = std::make_shared<Node>(5);
现在,代码的其余部分应该按预期工作(只需要修复对getTestVal()
函数的调用(。
我想你误解了C++语义。
std::vector< Node> testVector; // creates empty vector of Node objects, no Node allocations made here
testVector.resize( 2 ); // calls default constructor and instantiates 2 new Node objects here
// could be done as std::vector< Node > testVector( 2 );
该向量已经为它作为默认构造函数定义类存在的那 2 个节点分配了内存。听起来你想要更多这样的东西:
...
std::vector< Node * > testVector( 2, null_ptr );
testVector[ 1 ] = new Node( 5 );
for( const auto & ptr : testVector )
if( ptr )
std::cout << ptr->getTestVal() << std::endl;
...
delete testVector[ 1 ];
正如其他人提到的,智能指针对象也可用于为您管理内存并具有类似的行为。
相关文章:
- 在C++中调整向量中的索引
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 将转换字符键入 int 以用作向量C++的索引
- 在对向量中查找元素的索引
- 如何检查类实例向量的索引是否为空
- 如何根据排序索引的向量对 std::index 集进行排序?
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- 访问向量索引C++
- 包含全局最小值的向量索引
- C 向量由另一个向量索引
- 向量索引在C 中不会包裹吗?什么是解决方法
- 使用Armadillo库中的指数向量索引矩阵
- 将多个整数添加到一个向量索引? 'Cout'不起作用
- array:将一维数组的索引转换为多维数组的向量索引
- 将一维"flattened"索引转换为 N 维数组的 N 维向量索引
- 向量索引访问与迭代器访问的效率
- 特征矩阵支持由向量索引吗?
- 如何重写由向量索引指向的项?
- 在另一个向量中引用向量索引时出错:'std::out_of_range at memory location'
- c++帮助传递向量索引到函数