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 need to use a
back_inserter:std::copydoesn'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_insertercreates an output iterator that callspush_backon a container for each element, so each element is inserted into the container.Alternatively, you could have created a sufficient number of elements in the
std::vectorto hold the range being copied:Or, you could use the
std::vectorrange constructor: