c++ - 使用迭代器范围将单个元素附加到容器

标签 c++ stl iterator containers

我想(复制)将单个元素附加到某个(类似 STL 的)容器,但我只能使用 basic_string & append(InputIt first,InputIt last)-like interface 来初始化或将元素附加到容器。

这样做错了吗:

#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) 构造是否有效(假设一元 operator & 未重载)?

最佳答案

是的,这是完全正确的。来自 [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 只是指向该对象末尾后的一个,为此目的,它是该类型大小的数组末尾后的一个,这是完全合法的事情引用,根据[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.


作为旁注,您的 append() 函数是您的 init() 函数的一个非常糟糕的实现。

关于c++ - 使用迭代器范围将单个元素附加到容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37033682/

相关文章:

java - For-Each 循环替代方案 - 说明

c++ - FFMPEG H264 编码每个单图像

c++ - c++ STL 中的增量 begin()(列表的)不起作用

c++ - MFC 容器 CObList 的 STL 迭代器

c++ - 我应该使用什么 STL 容器来行走一棵树?

python - 为什么Python在循环后不删除iterate变量?

c++ - cpp-静态成员和函数

c++ - 如何将 int 转换为 const int 以在堆栈上分配数组大小?

c++ - vector 超出特定机器的范围?

c++ - 如何在STL中使用unordered_set?