![](/img/trans.png)
[英]C++ : push_back a map<string, int> into a vector<map<string, int> > via an iterator?
[英]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_back
到std::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.