简体   繁体   中英

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.

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. 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()); , dest is supposed to contain at least the same number of elements (ie one element here), but it's empty in fact.

You can use resize instead of 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 .

The container's push_back() member function is called whenever the iterator (whether dereferenced or not) is assigned to.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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