Sign in to follow this  

Weird problem with std copy

This topic is 3109 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, This code crashes on the third line. And I cannot figure out what I am doing wrong.
std::vector<float> abc,def;
abc.push_back(3);
std::copy(abc.begin(), abc.end(), def.end()); //debug assert error here
Any clues? Thanks.

Share this post


Link to post
Share on other sites
Copy assumes that the destination is a valid range, the same size as the input.

You could use std::back_inserter:

#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

int main(){
std::vector<float> abc, def;

abc.push_back(3);

std::copy(abc.begin(), abc.end(), std::back_inserter(def));

std::copy(def.begin(), def.end(), std::ostream_iterator<float>(std::cout,"\n"));
}


Or you could use resize() on def so that it has at least as many elements as abc.

Share this post


Link to post
Share on other sites
You can't use std::copy to copy directly to an empty vector. Since it doesn't contain any elements when std::copy tries to write to those non-existing elements bad things happen. In your case you might want to use def.assign(abc.begin(), abc.end()) or use std::back_inserter() for the destination for std::copy(). I recommend the former.

Share this post


Link to post
Share on other sites

This topic is 3109 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this