0
string s1 = "bob"; 
string s2 = "hey";
string s3 = "joe";
string s4 = "doe";

vector<string> myVec;

myVec.push_back(s1);
myVec.push_back(s2);
myVec.push_back(s3);
myVec.push_back(s4);

How do I output "bob hey" "bob hey joe" "bob hey joe doe" using an iterator on myVec?

Any help hints or help would be appreciated

user3239138
  • 143
  • 4
  • 17

5 Answers5

4

The following should work:

for (auto it = myVec.begin(), end = myVec.end(); it != end; ++it)
{
    for (auto it2 = myVec.begin(); it2 != (it + 1); ++it2)
    {  
        std::cout << *it2 << " ";
    }
    std::cout << "\n";
}

Example output:

bob 
bob hey 
bob hey joe 
bob hey joe doe

Live Example

2
using namespace std;

auto it_first = begin(myVec);
auto it_last = begin(myVec) + 2;
while (it_last != end(myVec)) 
    for_each(it_first, it_last++, [](string const & str) { cout << str << " "; });
    cout << endl;
}

This should do it. EDIT: Corrected bug :) that should give you the correct output please confirm. There was an extra next.

Germán Diago
  • 7,473
  • 1
  • 36
  • 59
  • 1
    Why `next`? I think he wants to include the first element. Also, this might fail if the vector contains less than 2 elements. – Excelcius Mar 02 '14 at 07:43
2

Something like this, if you can use boost:

 std::vector<std::string> s { "bob", "hey", "joe", "doe" };
 std::vector<std::string> d;

 for (auto i = std::begin(s); i != std::end(s); ++i) {
     d.push_back(boost::algorithm::join(
         boost::make_iterator_range(std::begin(s), i + 1), 
         std::string(" ")
     ));
 }

The output vector d will contain the following:

bob
bob hey
bob hey joe
bob hey joe doe

But more efficient solution is using temporary string:

 std::vector<std::string> s { "bob", "hey", "joe", "doe" };
 std::vector<std::string> d;

 std::string t;
 std::for_each(std::begin(s), std::end(s), [&](const std::string &i) {
     d.push_back(t += (i + " "));
 });
fasked
  • 3,555
  • 1
  • 19
  • 36
1

you can use a stringstream the exact same way as cout. Rather than printing to the screen, they will be saved in a string. The string can be accessed with .str().

See this: How to use C++ String Streams to append int?

Your code would look something like this:

vector <int> myVec;
std::stringstream ss;

for(int i=0; i<10; i++)  
    myVec.push_back(i);  //vector holding 0-9

vector<int>::iterator it;
for(it=myVec.begin(); it!=myVec.end(); ++it) {
    ss<<*it<<endl;
    cout << ss.str() << " ";   // prints 1 12 123 1234 ...
}

// ss.str() == "123456789";
Community
  • 1
  • 1
Avi Tevet
  • 778
  • 1
  • 7
  • 13
1

You can try to concatinate as below using std::string + operator and iterator

std::string myCompleteString;
vector<std::string>::iterator it;
for(it=myVec.begin(); it!=myVec.end(); ++it)
        myCompleteString  += *it +  " ";

cout << myCompleteString;
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31