我有以下代码:
#include <vector>
#include <memory>
struct Node{
int value;
Node *left = nullptr;
Node *right = nullptr;
};
std::vector<std::unique_ptr<Node>> createListNodes(int min, int max)
{
// odered vector with i.e. {0,1,2,3,4}
std::vector<std::unique_ptr<Node>> alternative;
if (min == max)
{
alternative.emplace_back(std::make_unique<Node>(min,nullptr,nullptr)); // it is a leaf node
return alternative;
}
for (int i=min; i<=max; i++)
{
std::vector<std::unique_ptr<Node>> left = createListNodes(min,i-1); // for the left side
std::vector<std::unique_ptr<Node>> right = createListNodes(i+1,max); // for the left side
if (left.size() == 0) // if node i has just one child and it is in the right
{
for (auto elem_right : right) // ERROR
{
alternative.emplace_back(std::make_unique<Node>(i,nullptr,elem_right));
}
}
else if (right.size() == 0) // if node i has just one child and it is in the left
{
for (auto elem_left : left) // ERROR
{
alternative.emplace_back(std::make_unique<Node>(i,elem_left,nullptr));
}
}
for (auto elem_left : left) // ERROR
{
for (auto elem_right : right) // ERROR
{
alternative.emplace_back(std::make_unique<Node>(i,elem_left,elem_right));
}
}
}
return alternative;
}
int main()
{
int N = 4;
std::vector<std::unique_ptr<Node>> combinations = createListNodes(0, N);
}
遍历unique_ptr的向量时收到错误,但我无法理解真正的问题。我也尝试过将unique_ptr移至向量替代方案,但问题仍然存在。
error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<Node,
std::__1::default_delete<Node> >'
for (auto elem_left : left)
您可能会做类似的事情:
struct Node{
int value;
Node *left = nullptr;
Node *right = nullptr;
Node(int v) : value(v) {}
};
std::vector<std::unique_ptr<Node>> createListNodes(int min, int max)
{
std::vector<std::unique_ptr<Node>> res;
for (int i = min; i != max + 1; ++i) {
res.emplace_back(std::make_unique<Node>(i));
}
for (int i = 0; i + 1 < max + 1 - min; ++i) {
res[i]->right = res[i + 1].get();
res[i + 1]->left = res[i].get();
}
return res;
}