[英]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 当我把(10 + 10) * 5
输出时
(
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. 注意, std::string
的迭代器指向一个char
,所以*it
不是一个std::string
,而是一个char
,它不能直接push_back
到std::vector<std::string>
。
You can change it to 你可以把它改成
vec.push_back({*it}); // construct a temporary string (which contains *it) to be added
or use emplace_back
instead: 或者使用emplace_back
代替:
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
. 我创建了一个名为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));
}
}
}
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. 此代码需要cctype
标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.