使用迭代器范围将单个元素附加到容器 [英] Append single element to container using iterator ranges

查看:106
本文介绍了使用迭代器范围将单个元素附加到容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想(复制)将单个元素附加到某些(类似STL的)容器,但我可以使用的是 basic_string& append(InputIt first,InputIt last) -like用于初始化或将元素追加到容器的接口。

I want to (copy) append single element to some (STL-like) container, but all I can use is basic_string & append(InputIt first, InputIt last)-like interface to initialize or to append elements to the container.

执行以下操作是否错误:

Is it wrong to do the following:

#include <vector>

struct container
{

    template< typename input_iterator >
    void init(input_iterator const beg, input_iterator const end)
    {
        v.insert(v.cend(), beg, end);
    }

    template< typename input_iterator >
    void append(input_iterator beg, input_iterator const end)
    {
        while (beg != end) {
            v.push_back(*beg);
            ++beg;
        }
    }

private:
    std::vector< int > v;
};

#include <cstdlib>

int main()
{
    int i = 123;
    container c;
    c.init(&i, &i + 1);
    int j = 555;
    c.init(&j, &j + 1);
    return EXIT_SUCCESS;
}

具体来说,我关心的是 f( & i,& i + 1)构造是否有效(假设一元运算符& 未过载)?

Specifically, I am concerned with whether the f(&i, &i + 1) construction is valid (assume unary operator & is not overloaded) or not?

推荐答案

是的,它完全有效。从[expr.unary.op]:

Yes, it's perfectly valid. From [expr.unary.op]:


出于指针算术(5.7)和比较(5.9,5.10)的目的,不是一个数组元素,其地址以这种方式被认为属于一个数组 T 的数组。

& i + 1 只是指向该对象结束的一个,为此目的是一个结束的对象根据[expr.add],这个类型的大小一个数组,这是一个完全合法的参考:

&i + 1 simply points to one past the end of that object, which for this purpose is one past the end of an array of size one of that type, which is a perfectly legal thing to refer to, according to [expr.add]:


如果指针操作数和结果都指向同一个数组对象的元素,或者数组对象的最后一个元素超过
,那么评估不会产生溢出;否则,行为是
undefined。

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.






作为旁注, append()函数是 init()函数的严格执行。


As a side note, your append() function is a strictly worse implementation of your init() function.

这篇关于使用迭代器范围将单个元素附加到容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆