我有一个名为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 ];
正如其他人提到的,智能指针对象也可用于为您管理内存并具有类似的行为。