c++stringfor-loopvectorrange-based-loop

How to make a spaced line of strings from a vector in C++


I want to make a line like this hello my name sounds very fancy from a vector of these words (std::vector<std::string> myvector = {"hello", "my", "name", "sounds", "very", "fancy"}).

What is the most efficient way to perform such convertion without inserting redundant spaces, as would happen if I used

for (auto element : v) {
    std::cout << word_from_vector << ' ';
}

?


Solution

  • If your compiler supports C++ 20 then you can write the range-based for loop the following way to eliminate the trailing space

    for ( bool next = false; const auto &element : myvector ) 
    {
        if ( next )
        {
            std::cout << ' ';
        }
        else
        {
            next = true;
        }
        std::cout << element;
    }
    

    Otherwise you could use the ordinary for loop like

    for ( size_t i = 0; i < myvector.size(); i++ )
    {
        if ( i != 0 ) std::cout << ' ';
        std::cout << myvector[i]
    }