#include <iostream>
#include <vector>
#include <cctype>
using std::string;
using std::vector;
using std::cin;
using std::cout;
using std::endl;
vector<string> split(const string& s)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i = 0;
//invariant: we have processed characters [original value of i, i)
while (i != s.size()){
// ignore leading blanks
// invariant: characters in range [original i, current i)
while (i != s.size() && isspace(s[i]))
++i;
// find end of next word
string_size j = i;
// invariant: none of the characters in range [original j, current j)
while (j != s.size() && !isspace(s[j]))
j++;
// if we found some nonwhitespace characters
if(i != j){
//copy from s starting at i and taking j-i chars
ret.push_back(s.substr(i, j - i));
i = j;
}
}
return ret;
}
int main(){
string s;
//read and split each line of input
while(getline(cin, s)){
vector<string> v = split(s);
//write each word in v
for(vector<string>::size_type i = 0; i != v.size(); ++i)
cout << v[i] << endl;
}
return 0;
}
Why does it work when you do vector<string> v = split(s); what I mean is,
why doesn't the first index of the vector v get overwritten by the next ret.
Also, I thought that the function split would only get the first word of the sentence but apparently all words are returned.
I hope my questions make a bit of sense, I'm aware that I'm probably just having some misconceptions but I cannot figure out what those are.
split creates and returns an entire vector (called ret in split) which is assigned to v and contains all the words. That's how split functions usually work. If it was returning a word at a time it would be more of a tokenizing function.
And why would the "first index" of v get the return? The first index is v[0], not v. v is the entire vector.