How to discard data that a string iterator points to a string vector

I want to tokenize a string and add to a vector, but all I can do is just access them through an iterator like below.

vector<string> ExprTree::tokenise(string expression){

    vector<string> vec;
    std::string::iterator it = expression.begin();

    while ( it != expression.end()) {

        cout << "it test " << (*it) << endl;
        vec.push_back(*it); // wrong!
        it++;
    }

      

when i put the (10 + 10) * 5

exit

( 
1
0 
+ 
1
0
) 
*
5

      

what I want, but how can I actually add them to the vector?

+3


source to share


2 answers


Note that the iterator std::string

points to a char

, so *it

it is not std::string

, but a char

, which cannot be push_back

ed std::vector<std::string>

directly.

You can change it to

vec.push_back({*it});     // construct a temporary string (which contains *it) to be added

      



or use emplace_back

instead:

vec.emplace_back(1, *it); // add a string contains 1 char with value *it

      

+1


source


If I'm not mistaken, you won't push space, will you? I am creating a function called tokenise

that matches the text

container as well vec

.

void tokenize(const std::string text, std::vector<std::string>& vec) {
  for(auto &it : text) {
    if(isspace(it) == false) {
      vec.push_back(std::string(1,it));
    }
  }
}

      

Just call this function of your choice. The implementation should be like this:



std::vector<std::string> vec;
std::string text = "10 + 10) * 5";
tokenize(text, vec);
for(auto &it : vec){
  std::cout << it << std::endl;
}

      

The output will be the same as you want. This code will require a header cctype

.

0


source







All Articles