简体   繁体   English

C ++ std :: vector迭代器构造函数,第一个== last

[英]c++ std::vector iterator constructor with first == last

I have a function which needs to divide a vector up into n sub-vectors. 我有一个功能,需要将一个向量划分为n个子向量。 For example, it might look something like this: 例如,它可能看起来像这样:

void foo(std::vector<uint8_t> vec, int numSubVectors){
    size_t size = vec.size() / numSubVectors;
    auto iter = vec.begin();
    for (int i = 0; i < numSubVectors; ++i) {
        auto sub_vec = std::vector<uint8_t>(iter, iter + size);
        // do something with sub_vec
        // ...

        iter += size;
    }
}

I need this to work when called with foo({}, 1) , where sub_vec gets assigned an empty vector on the first (and only) iteration of the loop. 当用foo({}, 1)调用时,我需要它来工作,其中sub_vec在循环的第一个(也是唯一的)迭代中被分配了一个空向量。 I'm concerned about the std::vector<uint8_t>(iter, iter + size) . 我担心std::vector<uint8_t>(iter, iter + size) Does the c++ standard allow a vector to be constructed using its range constructor when first == last? 当第一个== last时,c ++标准是否允许使用其范围构造函数构造向量?

According to cplusplus.com , "The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last", but that statement doesn't make any sense when first == last? 根据cplusplus.com的说法 ,“使用的范围是[first,last),其中包括first和last之间的所有元素,包括first所指向的元素,而不是last所指向的元素”,但是该语句没有任何作用。何时第一个==最后一个感觉?

I tried running it on an online IDE and it seems to work ( https://ideone.com/V9hylA ), so it's clearly not prohibited, but is it undefined behaviour? 我尝试在在线IDE上运行它,并且似乎可以正常工作( https://ideone.com/V9hylA ),因此显然不禁止使用它,但是它的行为不确定吗?

From iterator.requirements.general of the standard: 来自标准的iterator.requirements.general

An iterator and a sentinel denoting a range are comparable. 表示范围的迭代器和标记是可比较的。 A range [i, s) is empty if i == s; 如果i == s,则范围[i,s)为空; otherwise [...] 除此以外 [...]

So when first == last, the standard explicitly defines this as an empty range. 因此,当first == last时,标准将其明确定义为空范围。

The iterator pair [first, last) where first == last is how we define an empty range. first == last的迭代器对[first, last)是我们定义一个空范围的方式。 It's syntactically and logically valid. 在语法和逻辑上都是有效的。 Constructing a std::vector from that iterator pair will do the correct thing and create an empty container. 从该迭代器对构造一个std::vector会做正确的事情,并创建一个空容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM