Insert Element in Vector for Every certain element

I want to add a element such as a space "" inside a vector<string> myvector. For example:

1
2
3
4
5
  myvector[0]+myvector.insert("")+myvector[1]+...+myvector.insert("")+myvector[i]
//I cannot do this individually because myvector.size() will not be constant.

//I want a loop it so it stops once it reaches the last string and then prints out the result


If there is way to do this in vector please let me know! Also, is it easier to do it if I convert the elements to a string and then add spaces. I tried both but I just couldn't write it in a code.
Last edited on
Do you need to put after each string element a space? Like this?
1
2
3
vector[0] = "Hello";
vector[1] = " ";
vector[2] = "World";

and then print its elements?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> insert_separator( std::vector<std::string> seq, std::string separator ) {

    std::vector<std::string> result ;
    for( const auto& str : seq ) { result.push_back(str) ; result.push_back(separator) ; }
    if( !result.empty() ) result.pop_back() ;
    return result ;
}

int main()
{
    std::vector<std::string> seq { "Die", "schärfsten", "Kritiker", "der", "Elche",
                                   "\nwaren", "früher", "selber", "welche\n" } ;

    seq = insert_separator( seq, " " ) ;
    for( auto str : seq ) std::cout << str ;
}

http://coliru.stacked-crooked.com/a/f6e790ebcd9b0b35
I don't know that building a string is necessary, but:

1
2
3
4
5
6
    // assumes: myvector.empty() is false.
    auto s = myvector.front();
    for (auto i = std::size_t {1}; i < myvector.size(); ++i)
        s += ' ' + myvector[i];

    std::cout << s << '\n' ; 





Last edited on
I was wondering if there is something like this
 
for(size_t i= 1; i<display_word.size(); ++i) word_changing.insert(display_word.end()-1, " ");


So, I add spaces from last second last vector until i get to the the very beginning.
Topic archived. No new replies allowed.