简体   繁体   English

字符串迭代器不兼容boost :: tokenizer

[英]string iterators incompatible boost::tokenizer

I have a simple code sample of a class that wraps boost::tokenizer. 我有一个包装boost :: tokenizer的类的简单代码示例。

MyTokenizer.h MyTokenizer.h

#pragma once

#include <iostream>
#include <boost/tokenizer.hpp>

class MyTokenizer
{
public:
    typedef boost::tokenizer< boost::escaped_list_separator<char> > TokType;

    MyTokenizer(std::string);
    ~MyTokenizer() {};
    void printTok();

private:
    const TokType tok_;

};

MyTokenizer.cpp MyTokenizer.cpp

#include "MyTokenizer.h"


MyTokenizer::MyTokenizer(std::string input) :
tok_(input)
{
    std::cout << "Created tokenizer from: " << input << std::endl;
    for (TokType::iterator it = tok_.begin(); it != tok_.end(); ++it){
        std::cout << *it << std::endl;
    }
}

void MyTokenizer::printTok(){
    std::cout << "printing tokens" << std::endl;
    for (TokType::iterator it = tok_.begin(); it != tok_.end(); ++it){
        std::cout << *it << std::endl;
    }
}

main.cpp main.cpp中

#include "MyTokenizer.h"

int main(void){
    std::string input("a,b,c");
    MyTokenizer tok(input);
    tok.printTok();
}

When I run this example it makes it through the constructor fine, printing the expected tokens in the loop but on the call to printTok() it gives this error 当我运行此示例时,它可以很好地通过构造函数,在循环中打印期望的标记,但是在调用printTok()时出现此错误

在此处输入图片说明

It seems like I cant create an iterator of MyTokenizer outside of the constructor. 看来我无法在构造函数之外创建MyTokenizer的迭代器。

Edit 编辑

I changed the printTok() method to be even simpler while still throwing the same error it now looks like this. 我将printTok()方法更改为更简单,同时仍然抛出现在看起来像这样的错误。

void MyTokenizer::printTok(){
    TokType::iterator it = tok_.begin();
}

Ok I fixed this myself. 好吧,我自己修好了。 The problem was that the string I built my tokenizer from was being de-allocated at the end of the constructor. 问题在于,我从中构建令牌生成器的字符串在构造函数的末尾被取消了分配。 I fixed it by storing a copy of the input string in my class and building my tokenizer from this string. 我通过在类中存储输入字符串的副本并从该字符串构建我的标记生成器来修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM