如何将字符串迭代器指向的数据推回到字符串向量中
问题描述:
我想标记字符串并添加到向量,但现在我只能通过迭代器访问它们,如下所示。如何将字符串迭代器指向的数据推回到字符串向量中
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
标题。