I've encountered some strange behaviour when using std::copy. With
std::vector<std::string> chosenIDs{...};
for (const auto& x : chosenIDs) {
std::string strID("");
std::copy(std::begin(x), std::find(std::begin(x), std::end(x), '.'), std::begin(strID));
std::cout << strID << "\n";
}
the strID string contains characters it's not supposed to, however
std::vector<std::string> chosenIDs{...};
for (const auto& x : chosenIDs) {
std::string strID(std::begin(x), std::find(std::begin(x), std::end(x), '.'));
std::cout << strID << "\n";
}
works completely fine. It's clear to me that I should be using the second approach, but it still baffles me as to why the behaviour in the first snippet is different from the second one.
I'm using GCC 5.4.0
When using std::copy() it is necessary to make sure that neither range makes out of bounds accesses. The target range starts out empty and there isn't anything done to expand it. Thus, the result is undefined behavior.
The problem can be fixed, e.g., by using a destination iterator growing the target sequence:
std::copy(std::begin(x), std::end(x),
std::back_inserter(strID));
As @M.M said:
The copy writes out of bounds of strID (copy does not resize the destination). You could use std::back_inserter(strID) as the third argument instead.
std::back_inserter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With