Jump to content
  • Advertisement
Sign in to follow this  
andrew111

Weird problem with std copy

This topic is 3327 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
Advertisement
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
Oh I see, I thought I'd used it similarly to my problem code before. I should've of checked the docs first :)

Thanks guys.





Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!