tmighty
tmighty

Reputation: 11399

C++ "copy" causes exception while brute-force works fine

I want to put some values of an int vector into a different int vector in C++ VS2010.

At first I tried the brute force way, and it worked fine:

for (int i=iStartPosInDst0based;i<=(iCountSrcItemsToCopy1based);i++)
{
    uIntegers[i]=nInts[i+iFirstItemInSrcToCopy0based];
}

Then I wanted to get a bit more sophisticated and tried using "copy".

copy(nInts.begin()+iFirstItemInSrcToCopy0based, uIntegers.begin()+iCountSrcItemsToCopy1based+iFirstItemInSrcToCopy0based, uIntegers.begin() +iStartPosInDst0based);

But "copy" crashes.

I was really sure that my "copy" version is the same as my "brute force" version, but obviously not. But I don't see where I went wrong. Could somebody help, please?

Upvotes: 0

Views: 124

Answers (4)

bash.d
bash.d

Reputation: 13207

As stated on cplusplus.com

template <class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

and

Output iterator to the initial position in the destination sequence.
This shall not point to any element in the range [first,last).

This seems to be the case here as your last parameter is similar to your second (uIntegers).

So it should be like

copy(nInts.begin()+ ..., nInts.begin()+ ..., uIntegers.begin() + );

See here for reference.

Upvotes: 0

You're giving arguments to copy in the wrong order. The prototype is

std::copy(InIt first, InIt last, OutIt result)

Try this instead:

std::copy(
  nInts.begin() + iFirstItemInSrcToCopy0based
  , nInts.begin() + iFirstItemInSrcToCopy0based + iCountSrcItemsToCopy1based
  , uIntegers.begin() + iStartPosInDst0based
);

If you have access to C++11, you should prefer std::copy_n, since you have the number of elements to copy:

std::copy_n(
  nInts.begin() + iFirstItemInSrcToCopy0based
  , iCountSrcItemsToCopy1based
  , uIntegers.begin() + iStartPosInDst0based
);

Upvotes: 2

spiritwolfform
spiritwolfform

Reputation: 2293

it's because you call

copy(nInts.begin() + ..., uIntegers.begin() + ..., uIntegers.begin() + ...);

the second iterator should be the one of nInts like so

copy(nInts.begin() + ..., nInts.begin() + ..., uIntegers.begin() + ...);

Upvotes: 2

Tushar
Tushar

Reputation: 8049

I think your forgot to add iStartPosInDst0based in the first iterator argument to copy:

copy(nInts.begin()+iStartPosInDst0based+iFirstItemInSrcToCopy0based, uIntegers.begin()+iCountSrcItemsToCopy1based+iFirstItemInSrcToCopy0based, uIntegers.begin() +iStartPosInDst0based);

Upvotes: 0

Related Questions