初始化std :: vector< unsigned int>带有连续无符号整数的列表 [英] Initialization of std::vector<unsigned int> with a list of consecutive unsigned integers
问题描述
我想使用一种特殊的方法来初始化 std :: vector< unsigned int>
,在我用作参考的C ++书中对此进行了描述(德语书Ulrich Breymann的 Der C ++程序员,以防万一。该书中有一个有关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
不是值,而是迭代器。此构造函数非常常用于复制其他类型的容器。如果要获取值序列,则 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>带有连续无符号整数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!