我想(复制)将单个元素附加到某个(类似 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/