[cpp,c++] Using std::copy: copy string, copy memory, copy container
Copy String Using std::copy (std::copy_n)
Copy std::string <=> std::string
#include <algorithm> // std::copy, std::copy_n #include <utxcpp/core.hpp> int main() { std::string str = "Hello, c++!"; std::string str2(str.size(), '\0'); std::copy_n(str.data(), str.size(), str2.data()); // OK too: // std::copy(str.begin(), str.end(), str2.begin()); utx::print(str2); // Hello, c++! std::string str3; str3.assign(str.data()); utx::print(str3); }
Copy std::string <=> char array <=> std::array<char, size>
#include <array> // std::array #include <algorithm> // std::copy, std::copy_n #include <string> #include <iostream> int main() { char str[] = "Hello c++!"; constexpr std::size_t size = sizeof str; std::string str2(size, '\0'); std::copy_n(str, size, str2.data()); std::cout << str2 << '\n'; char str3[size]; std::copy(str2.begin(), str2.end(), str3); std::cout << str3 << '\n'; std::array<char, size> str4; std::copy_n(str3, size, str4.begin()); std::cout.write(str4.begin(), str4.size()); std::cout << '\n'; }
Copy Memory Using std::copy (std::copy_n)
#include <utxcpp/core.hpp> class fizz_t { private: float x{}; std::uint64_t y{}; public: fizz_t() = default; fizz_t(const float & x, const std::uint64_t & y): x{x}, y{y} {} void print() const { utx::print(x, y); } }; int main() { fizz_t f1{2.678f, 99}; std::size_t size = sizeof f1; f1.print(); // 2.678000 99 utx::print(size); // 16 std::uint8_t buffer[size]; // Copy Memory using std::copy_n (or std::copy) std::copy_n((std::uint8_t *)&f1, size, buffer); fizz_t f2; f2.print(); // 0.000000 0 // Copy Memory using std::copy_n (or std::copy) std::copy_n(buffer, size, (std::uint8_t *)&f2); f2.print(); // 2.678000 99 }
Copy Container Using std::copy (std::copy_n)
#include <utxcpp/core.hpp> #include <list> #include <vector> int main() { std::vector<std::int32_t> vector{2,3,5,7,9,11}; std::list<std::int32_t> list(vector.size()); utx::print(list.size()); // 6 std::copy(vector.begin(), vector.end(), list.begin()); utx::print_all(list); // 2 3 5 7 9 11 }
Comments
Display comments as Linear | Threaded