다음은 벡터가 참조로 전달 되더라도 노드가 값으로 전달되기 때문에 다음과 같이 작동하지 않습니다 (인쇄 2). 내가 어떻게 고칠 수 있니?해당 위치의 벡터 요소 수정
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
class Node{
public:
int value;
Node(int);
void createChildren(vector<Node> &);
};
//! constructor of a single node
Node::Node(int value)
{
this->value = value;
}
void Node::createChildren(vector<Node> &nodes)
{
for (int i = 0; i < 5; i++) {
Node n(0);
nodes.push_back(n);
if (i == 0) {
value = nodes.size();
}
}
}
int main(void) {
Node a(0);
vector<Node> asdf;
asdf.push_back(a);
asdf[0].createChildren(asdf);
cout << asdf[0].value << endl;
return 0;
}
달성하려는 목표가 내게 명확하지 않습니다. 예상되는 결과는 무엇입니까? – pmr
당신은 무엇을 기대합니까? 값은 i == 0에 대해서만 업데이트되기 때문에 출력 1은 올바른 것입니다. –
실제로 "asdf"에는 두 개의 요소가 있어야하므로 "2"여야합니다. – haavee