Initialization of std::vectorlt;unsigned intgt; with a list of consecutive unsigned integers(std::vectorlt;unsigned intgt; 的初始化带有连续无符号整数的列表)
问题描述
我想使用一种特殊的方法来初始化一个 std::vector<unsigned int>
在我用作参考的 C++ 书籍中描述(德国书籍 'Der C++ Programmer'Ulrich Breymann,以防万一).在那本书中有一节介绍了 STL 的序列类型,特别提到了 list
、vector
和 deque
.在本节中,他写道,这种序列类型有两个特殊的构造函数,即,如果 X
引用了这种类型,
I want to use a special method to initialize a std::vector<unsigned int>
which is described in a C++ book I use as a reference (the German book 'Der C++ Programmer' by Ulrich Breymann, in case that matters). In that book is a section on sequence types of the STL, referring in particular to list
, vector
and deque
. In this section he writes that there are two special constructors of such sequence types, namely, if X
refers to such a type,
X(n, t) // creates a sequence with n copies of t
X(i, j) // creates a sequence from the elements of the interval [i, j)
我想将第二个用于unsigned int
的区间,即
I want to use the second one for an interval of unsigned int
, that is
std::vector<unsigned int> l(1U, 10U);
获取使用 {1,2,...,9}
初始化的列表.然而,我得到的是一个带有一个 unsigned int
值为 10 的向量:-|是否存在第二个变体,如果存在,我该如何强制调用它?
to get a list initialized with {1,2,...,9}
. What I get, however, is a vector with one unsigned int
with value 10 :-| Does the second variant exist, and if yes, how do I force that it is called?
推荐答案
重读附近描述每个参数的段落.具体来说,应该提到 i
和 j
不是值,而是 iterators.此构造函数非常常用于制作其他类型容器的副本.如果你想得到一个值序列,Boost 库提供了一个 计数迭代器,这正是你想要的.
Reread the paragraphs near there describing what each of the parameters are. Specifically, it should mention that i
and j
are not values, but iterators. This constructor is very commonly used to make copies of other types of containers. If you want to get a sequence of values, the Boost library provides a counting iterator, that does exactly what you want.
std::vector<unsigned int> numbers(
boost::counting_iterator<unsigned int>(0U),
boost::counting_iterator<unsigned int>(10U));
这篇关于std::vector<unsigned int> 的初始化带有连续无符号整数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::vector<unsigned int> 的初始化带有连续无符号整数的列表
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01