Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 << ' ';
}

?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading