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 Xrefers 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> 的初始化带有连续无符号整数的列表
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
