如何将字符串迭代器指向的数据推回到字符串的向量中

时间:2017-05-05 01:28:58

标签: c++ string vector iterator

我想标记一个字符串并添加到一个向量,但我现在所能做的只是通过迭代器访问它们,如下所示。

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

这就是我想要的,但我怎样才能将它们实际添加到矢量?

2 个答案:

答案 0 :(得分:1)

请注意,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

或改为使用@GET("poll/session/{sessionId}/details") Observable getSessionDetails(@Path("sessionId") String sessionId); @GET("poll/session/{sessionId}/details") @Streaming Observable getSessionDetails(@Path("sessionId") String sessionId); @Override public Observable getSessionDetails(String sessionId) { return sessionAPI.getSessionDetails(sessionId) .flatMap(responseBody -> events(responseBody.source())); } public static Observable<String> events(BufferedSource source) { return Observable.create(subscriber -> { try { while (!source.exhausted()) { subscriber.onNext(source.readUtf8Line()); } } catch (IOException e) { e.printStackTrace(); subscriber.onError(e); } subscriber.onCompleted(); }); }

public Galaga() throws IOException
{
    //set the background
    setBackground(Color.BLACK);

    //create a controller
    c = new Controller();
    addKeyListener(c);
    setFocusable(true);

    //create a player
    player = new Ship(40,50);
    running = true;

}


public void paint(Graphics g)
{
    super.paint(g);
}

//game loop
public void run()
{
    while(running)
    {
        draw(getGraphics());
        if(c.right())
            player.move(1, 0);
    }
}

//update logic
public void update()
{

}

//renders all objects
public void draw(Graphics g)
{
    player.draw(g);
}

答案 1 :(得分:0)

如果我没有弄错的话,你不会推动这个空间,是吗? 我创建了一个名为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标题。