c++ - 如何使用 c++ 中的构造函数初始化 unique_ptrs 的 2d 向量?
问题描述
我正在尝试初始化 unique_ptrs 的 2d 向量以将其大小和每个索引设置为 nullptr,或者如果我想要一些基类对象指针但它不起作用。
#include <vector>
#include <memory>
class Base
{
}
int main()
{
int m_width = 150, m_length = 13;
vector <vector <std::unique_ptr<Base>>> m_board;
m_board(m_length, vector < std::unique_ptr<Base>(m_width, nullptr));
}
也试过这个方法,还是没有:
m_board(m_length, vector < std::unique_ptr<Base>(std::move(m_width, nullptr)));
也是这样:
m_board(m_length, vector < std::unique_ptr<Base>(std::move(std::make_unique(m_width, nullptr))));
仍然没有任何工作,现在我使用一个非常丑陋的函数和两个 for 循环来做到这一点,但我确信有一种方法可以通过使用向量和 unique_ptr 的构造函数来完成这项工作。有什么想法吗?
解决方案
首先,如果std::vector
已经构建,vector
则通过使用来更改 的大小std::vector::resize
。您的代码将构造与已构造向量的大小混合在一起。
第二件事是双参数向量构造函数的第二个参数(参见 (4))现在是 C++ 14 或更高版本的分配器,而不是默认值。
因此,设置向量的最简单方法是首先resize
将外部向量,然后resize
每个内部向量单独循环:
#include <vector>
#include <memory>
#include <iostream>
class Base
{
};
int main()
{
int m_width = 150, m_length = 13;
// Create a vector with m_length size
std::vector<std::vector<std::unique_ptr<Base>>> m_board(m_length);
// individually resize the inner dimensions
for (auto& m : m_board)
m.resize(m_width);
}
推荐阅读
- python - Django:IndexError:列表索引超出范围
- java - java.net.SocketException:输入流的连接重置
- django - 如果我只有一个页面和总页数的数据,Django如何实现分页
- python - 为什么索引错误:列表超出范围即将到来?
- c - 什么是 .o 文件并在 Windows 上打开它们?
- module - 检查是否可以加载包
- smartcard - 如何从智能卡上传/写入/读取文件?有免费/付费软件吗?
- assembly - 用精灵碰撞破解 C64 游戏
- node.js - 我得到不能“'节点。' 未被识别为内部或外部命令、可运行程序或批处理文件。”
- angular - 如果数据以编码形式来自 api,是否可以将 .xls 文件保存为角度。如何?