If I reserve some space for the vector and then copy some values in it with std::copy_n(), I will get the values copied correctly and available, but the size of the vector is still zero. Is this expected behavior? Should I resize the vector instead, even if it is not so efficient?
std::copy_n()
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<double> src, dest; for(double x = 0.0; x < 100.0; ++x) src.push_back(x); dest.reserve(src.size()); std::copy_n(src.cbegin(), src.size(), dest.begin()); std::cout << "src.size() = " << src.size() << std::endl; std::cout << "dest.size() = " << dest.size() << std::endl; for(size_t i = 0; i < src.size(); ++i) std::cout << dest[i] << " "; }
Compiled Compilers: clang, gcc, Visual C ++
but the size of the vector is still zero
std::copy_n , ; . , undefined, , .
std::copy_n
, ?
, std::vector::resize std::vector::reserve . , , resize, copy_n.
std::vector::resize
std::vector::reserve
resize
copy_n
std:: back_inserter, , - push_back() (.. ), . .
push_back()
dest.reserve(src.size()); std::copy_n(src.cbegin(), src.size(), std::back_inserter(dest));
, , , , . , . , , , ; , .
, std::copy_n, , . dest.resize(src.size());, dest.reserve(std.size());.
dest.resize(src.size());
dest.reserve(std.size());
, , , , std::back_inserter(dest) dest.begin().
std::back_inserter(dest)
dest.begin()
A std::vector . , , . , .
dest reserve, , UB. resize, , .
dest
reserve
dest.resize(src.size()); std::copy_n(src.cbegin(), src.size(), dest.begin()); std::cout << "src.size() = " << src.size() << std::endl; std::cout << "dest.size() = " << dest.size() << std::endl; for(size_t i = 0; i < src.size(); ++i) std::cout << dest[i] << " ";
Source: https://habr.com/ru/post/1668819/More articles:ошибка TS5053: опция 'sourceMap' не может быть указана с опцией 'inlineSourceMap' - nativescriptHow can I detect objects in Amazon Rekognition AWS with Android Studio? - javaПример специализации аргумента шаблона из cpprefference.com не работает - c++Throttling HTTP requests before they are created - angularbase class derived class functioning as an abstract class - c ++Implementing alignment feedback in a tensor stream - pythonFailed to load default credentials? (Node.js Google Compute Engine) - javascriptStunning iterator + segfault behavior with unordered_set - c ++There is no corresponding function std :: forward with lambdas - c ++Lambda immutable function: copied captured variables allowed as const? - c ++All Articles