i ran across something similar to the below code snippet, which throws a compiler error because its using a const_iterator. is there a reason why vec.end() in std::copy does not implicitly get a const cast ?
int main(int argc, char* argv[]) {
vector<int> vec;
vec.push_back(20);
vec.push_back(30);
vector<int> copy_vec;
vector<int>::const_iterator i = vec.begin();
std::copy(i,vec.end(),back_inserter(copy_vec));
cerr<<copy_vec.size()<<endl;
return 0;
}
No need of
std::copy, neither you need a pair of iterators.Just do this:
And you’re done!
As for your code why it is giving error, is because the first iterator to
std::copyis aconst_iterator, but the second iterator is justiterator. Both has to be same type, but they are not, and because of that the template argument deduction fails forstd::copywhich is a function template.To understand this with an example, consider this simple code:
It is giving error (see ideone):
It doesn’t compile because we’re relying on template argument deduction. Since the type of the first parameter and second parameter is exactly same in the function template but we call this function passing
a(which isint) as first argument andb(which ischar) as second argument, it cannot deduceTuniquely from arguments of different types! Please note that conversion is not considered during template argument deduction.However, if we do not rely on template argument deduction, and instead provide the template argument explicitly, then it would work (see ideone):
It works as there is no need to deduce
Tfrom function arguments!Similarly, if you provide the template argument for
std::copy, then even your code would work (see ideone):It works because
iteratorcan convert intoconst_iterator, butconst_iteratorcannot convert intoiteratorwhich means the following would give error (see ideone):