vendredi 19 mars 2021

C++ Initialize Each Character in array of std::string of Fixed Width

Is there a way to initialize each character of each string within an array (either plain-old or std::array) of std::string using value initialization instead of std::transform() or looping assigning a literal or temporary object? Take for example an array of 20 std::string of 20 characters each where we want to initialize every character to 'x'.

Essentially, what I would like to do is initialize every string as std::string(WIDTH, char). Initializing the first is straight-forward, e.g.

#define NSTR  20
#define NCHR  20
...
std::string strarr[NSTR] { std::string(NCHR,'x') };

But there is only a single initializer provided in the initializer list for the first string and the remaining string are initialized empty as expected due to fewer values than all being provided. Going through the value, direct, copy or list Initialization doesn't seem to provide a way through initialization. (I am trying to avoid providing either an express literal or temporary for every string in the array)

After the object is created/constructed, then either a loop and assigning a temporary (or literal) or std::transform provide a simple way, e.g.

    std::string strarr[NSTR] {};
    
    for (auto& s : strarr) {
        s = std::string(NCHR,'x');
    }

or

    std::transform (strarr, strarr + NSTR, strarr, 
                    [](std::string s) { return s = std::string(NCHR,'x'); } );

or using a container for the std::string, e.g.

    std::array<std::string,NSTR> strarr{};
    
    std::transform (strarr.begin(), strarr.end(), strarr.begin(), 
                    [](std::string s) {return s = std::string(NCHR,'x');});

Is there some direct way to initialize each char in an array of std::string, or is setting them after the array is defined the way to go?

Aucun commentaire:

Enregistrer un commentaire