Append single element to container using iterator ranges

风流意气都作罢 提交于 2019-12-20 03:17:23

问题


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;
}

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


回答1:


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

For purposes of pointer arithmetic (5.7) and comparison (5.9, 5.10), an object that is not an array element whose address is taken in this way is considered to belong to an array with one element of type T.

&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]:

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.


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



来源:https://stackoverflow.com/questions/37033682/append-single-element-to-container-using-iterator-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!