I need to copy std::set
to std::vector
:
std::set <double> input;
input.insert(5);
input.insert(6);
std::vector <double> output;
std::copy(input.begin(), input.end(), output.begin()); //Error: Vector iterator not dereferencable
Where is the problem?
You haven't reserved enough space in your vector object to hold the contents of your set.
std::copy
cannot be used to insert into an empty container. To do that, you need to use an insert_iterator like so:here's another alternative using
vector::assign
:Just use the constructor for the vector that takes iterators:
Assumes you just want the content of s in v, and there's nothing in v prior to copying the data to it.
You need to use a
back_inserter
:std::copy
doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly tostd::copy
, you must make sure it points to a range that is at least large enough to hold the input range.std::back_inserter
creates an output iterator that callspush_back
on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in thestd::vector
to hold the range being copied:Or, you could use the
std::vector
range constructor: