簡體   English   中英

如何將字符串迭代器指向的數據推回到字符串的向量中

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

我想標記一個字符串並添加到一個向量,但我現在所能做的只是通過迭代器訪問它們,如下所示。

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++;
    }

當我把(10 + 10) * 5輸出時

( 
1
0 
+ 
1
0
) 
*
5

這是我想要的,但我怎么能將它們實際添加到矢量?

注意, std::string的迭代器指向一個char ,所以*it不是一個std::string ,而是一個char ,它不能直接push_backstd::vector<std::string>

你可以把它改成

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

或者使用emplace_back代替:

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

如果我沒有弄錯的話,你不會推動空間,是嗎? 我創建了一個名為tokenise的函數,如下所示,需要text和字符串容器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));
    }
  }
}

只需按照您的意願調用此功能即可。 實現應該是這樣的:

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

輸出將與您想要的相同。 此代碼需要cctype標頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM