在unique_ptr中动态分配的数组上应用std::begin()
Apply std::begin() on an dynamically allocated array in a unique_ptr?
在动态分配的数组上有一个唯一的指针:
const int quantity = 6;
unique_ptr<int[]> numbers(new int[quantity]);
到目前为止,这应该是正确的(我认为,模板参数中的[]
很重要,对吗?)顺便说一下:有可能像int some_array[quantity] = {};
一样初始化元素吗?现在我试着像这样遍历数组:
for (auto it = begin(numbers); it != end(numbers); ++it)
cout << *it << endl;
但我不明白,语法是如何正确的。有办法吗?或者,我可以使用如下索引:
for (int i = 0; i < quantity; ++i)
cout << numbers[i] << endl;
是首选的吗?
(与标题不直接相关:作为下一步,我想将其减少到基于范围的for循环,但我现在只有VS2010,无法尝试。但是有什么我必须处理的吗?)
谢谢!Gerrit
编译器应该将此原型应用于std::begin
:
template< class T, size_t N >
T* begin( T (&array)[N] );
表示参数类型为int(&)[N]
,既不是std::unique_ptr
,也不是int *
。如果这是可能的,std::end
如何计算最后一个?
但为什么不直接使用原始指针或STL容器?
const int quantity = 6;
std::unique_ptr<int[]> numbers{new int[quantity]};
// assignment
std::copy_n(numbers.get(), quantity,
std::ostream_iterator<int>(std::cout, "n"));
const int quantity = 6;
std::vector<int> numbers(quantity, 0);
// assignment
std::copy(cbegin(numbers), cend(numbers),
std::ostream_iterator<int>(std::cout, "n"));
c++中动态分配的数组(即:new []
的结果)没有大小信息。因此,您无法获得数组的大小。
你可以这样实现std::begin
:
namespace std
{
template<typename T> T* begin(const std::unique_ptr<T[]> ptr) {return ptr.get();}
}
但是没有办法实现end
。
你考虑过使用std::vector
吗?有了移动支持,它应该不会比一个unique_ptr
到一个数组更昂贵。
相关文章:
- 我们应该在使用 std::bind 应用之前检查一个不为空的函数吗?
- 由于调用 std::condition_variable 后参数无效而导致应用程序崩溃
- 将 std::bind 应用于带有参数 <boost::asio::ip::tcp::socket> 时出错?
- 从函数应用程序创建 std::vector
- 应用于整型类型的编译时优化 'std::isfinite()'
- 将函数标识符作为右值引用传递并对其应用 std::move()
- OMNeT++ cPacket as std::bitset 以应用 Reed-Solomon 编码
- 对 QMainWindow 使用 std::unique_ptr 时退出时出现 QT 应用程序分段错误
- STD ::在模板函数中应用于构造函数
- 如何在std :: tuple中的每个元素上应用constexpr函数
- 使用STD ::应用实验
- STD :: cin和Scanf()应用于字符串之间的区别
- 复制 std::vector,但将 lambda 应用于每个元素
- 防御性地应用 std::move 到平凡可复制的类型是否不可取
- 在GLFW应用程序中,std::cin的行为很奇怪
- "std::swap"应用于这些对象时会做什么?
- 开发C++应用程序,目标服务器有不同的std lib版本,最佳实践是什么
- 使用 std::variant 作为类成员并应用访问者
- 是否可以将std ::函数应用于特征矩阵的每个元素
- 使用 std::应用于可变参数包