Split words with find_if

1

How is this string (i, j) assembled? the first string inserted in the vector is "Robison" and is correct, but to have this result the value of i should be 0 and j = 7, no?

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using std::string;
using std::vector;
using std::cout;
using std::endl;

// predicate (split)
bool space(char c)
    { return isspace(c); }

// preticate (split)
bool not_space(char c)
    { return !isspace(c); }

vector<string> split(const string& str)
{
    typedef string::const_iterator iter;
    vector<string> ret;

    iter i = str.begin();
    while (i != str.end())
    {
        // verifica se o caracter e espaço
        i = find_if(i, str.end(), not_space);

        // procura um novo carácter
        iter j = find_if(i, str.end(), space);

        // faz a cópia dos caracteres encontrados
        if (i != str.end())
            ret.push_back(string(i, j));
        i = j;
    }
    return ret;
}

int main ()
{
    string str = "Robison Aleixo";
    split(str);

    return 0;
}

/*
 *  Basicamente as declarações acima encontram o range de uma string
    armazena as strings em um vetor "removendo" os espaços em branco
 *
 *  Exemplo: str= "Robison Aleixo"
 *
 *  iter i = str.begin();  ::::> i  será = 0
 *  while (i != str.end()) ::::> será executado até o último caracter da string
 *  i = find_if(i, str.end(), not_space);  ::::> i = 6
 *  iter j = find_if(i, str.end(), space); ::::> j = 7
 *  if i != str.end())  ::::> Verifica se não é o último caracter
 *  ret.push_back(string(i, j));  ::::> i = 6 ; j = 7
 *
 *  R o b i s o n   A l e  i  x  o
 *  0 1 2 3 4 5 6 7 8 9 10 11 12 13
 *              ^ ^
 *              i j
 *
 */
    
asked by anonymous 26.09.2017 / 03:58

1 answer

1
  

i should be 0 and j = 7, not?

These are indeed the values. If we look at how i is obtained:

i = find_if(i, str.end(), not_space /*<--not space aqui!*/);

Watch out for not_space , as soon as you start getting the first character that is not space , and so the first letter, that of position 0 and not position 6 as it had indicated.

Next we get the following space for j with:

iter j = find_if(i, str.end(), space);

Now we use the predicate of space to catch space. If we have not yet reached the end we use the constructor of string that receives two iterators and starts string with the text between them:

string(i, j)

And given in the documentation as:

  

template <class InputIterator> string (InputIterator first, InputIterator last);

     

(7) range builder Copies the sequence of characters in the range   [first, last), in the same order.

It is important to note that the last element, last , is not included, which fits well in the algorithm because it causes the string built does not contain the space that was in j

    
26.09.2017 / 12:24