What the std::copy
algorithm does is to copy one source element after the other, and advance the destination iterator after each element.
This assumes that
- either the size of the destination container has been set large enough to fit all the elements you copy,
- or you use an iterator type that increases the size of the destination container each time you make an assignment to it.
Therefore, if you want to use the std::copy
algorithm, there are two ways of solving this:
Resize the string before making the copies:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
char source[] = "hello world";
std::string dest;
dest.resize(5);
std::copy(source,source+5,begin(dest));
std::cout << dest << std::endl;
return 0;
}
Using a back-insert iterator instead of the standard one:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
char source[] = "hello world";
std::string dest;
std::copy(source,source+5,std::back_inserter(dest));
std::cout << dest << std::endl;
return 0;
}
However, as pointed out by others, if the goal is simply to copy the first 5 characters into the string at initialization time, using the appropriate constructor is clearly the best option:
std::string dest(source,source+5);