std::vector<unsigned int> 的初始化带有连续无符号整数的列表

Initialization of std::vectorlt;unsigned intgt; with a list of consecutive unsigned integers(std::vectorlt;unsigned intgt; 的初始化带有连续无符号整数的列表)

本文介绍了std::vector<unsigned int> 的初始化带有连续无符号整数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一种特殊的方法来初始化一个 std::vector<unsigned int> 在我用作参考的 C++ 书籍中描述(德国书籍 'Der C++ Programmer'Ulrich Breymann,以防万一).在那本书中有一节介绍了 STL 的序列类型,特别提到了 listvectordeque.在本节中,他写道,这种序列类型有两个特殊的构造函数,即,如果 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?

推荐答案

重读附近描述每个参数的段落.具体来说,应该提到 ij 不是值,而是 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&lt;unsigned int&gt; 的初始化带有连续无符号整数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:std::vector&lt;unsigned int&gt; 的初始化带有连续无符号整数的列表

基础教程推荐