简体   繁体   English

std :: copy失败,“无法在结束后寻找向量迭代器”

[英]std::copy failure, “cannot seek vector iterator after end”

I put together this test case that reproduces the conditions and problem I'm getting in larger code. 我把这个测试用例放在一起,重现了我在更大的代码中得到的条件和问题。 I do in fact need to copy from a C array of POD structures, but I'd like the destination to be a vector so it can handle the copy deletion on its own. 我确实需要从POD结构的C数组中复制,但我希望目标是一个向量,因此它可以自己处理副本删除。

TEST_METHOD(std_copy)
{
    struct W { long a; int b; char c; char d; };
    W block[1] = { { 15, 42, 'D', 'X' } };
    std::vector<W> dest;
    dest.reserve(1);
    std::copy(block, block+1, dest.begin());
    Assert::AreEqual(42, dest[0].b);
}

The assertion "cannot seek vector iterator after end" seems to be occurring within the dest.begin() call, which makes no sense to me. 断言“无法在结束后寻找向量迭代器”似乎发生在dest.begin()调用中,这对我来说毫无意义。 I'm sure I'm just missing an obvious detail, but what is it? 我确定我只是错过了一个明显的细节,但它是什么?

As the error message said, you're getting out of the bound of the vector. 正如错误消息所说,你已经超出了向量的范围。

Given std::copy(block, block+1, dest.begin()); 给定std::copy(block, block+1, dest.begin()); , dest is supposed to contain at least the same number of elements (ie one element here), but it's empty in fact. dest应该包含至少相同数量的元素(即这里的一个元素),但实际上它是空的。

You can use resize instead of reserve , 您可以使用resize而不是reserve

std::vector<W> dest;
dest.resize(1);
std::copy(block, block+1, dest.begin());

Or just 要不就

std::vector<W> dest(1);
std::copy(block, block+1, dest.begin());

Or use std::back_inserter to get an std::back_insert_iterator . 或者使用std::back_inserter获取std::back_insert_iterator

The container's push_back() member function is called whenever the iterator (whether dereferenced or not) is assigned to. 只要分配了迭代器(无论是否取消引用),就会调用容器的push_back()成员函数。

std::vector<W> dest;
dest.reserve(1);
std::copy(block, block+1, std::back_inserter(dest));

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

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