简体   繁体   中英

How to push back a data that the string iterator is pointing to into the vector of string

I want to tokenize a string and add to a vector, but all I can do now is just accessing them via iterator, shown 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 (10 + 10) * 5 the output is

( 
1
0 
+ 
1
0
) 
*
5

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

Note that the iterator of std::string points to a char , so *it is not a std::string , but a char , which can't be push_back ed into the 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

If I don't be mistaken, you won't push the space, do you? I create a function called tokenise as follow which needs the text and string container 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 as you wish. 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 would require cctype header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM