Skip to content

[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.size(),;
        // OK too: 
        // std::copy(str.begin(), str.end(), str2.begin());

        utx::print(str2); // Hello, c++!

        std::string 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,;
        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
        float x{};
        std::uint64_t y{};
        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





No Trackbacks


Display comments as Linear | Threaded

No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.

Form options

Submitted comments will be subject to moderation before being displayed.