C++ 迭代器做奇怪的事情

问题描述 投票:0回答:1

我可能完全愚蠢,但是:

class Lexer {
    private:
        std::string::iterator start;
        std::string::iterator current;
        std::string source;
        int line;
        std::unordered_map<std::string, TokenType> keyword_table;

    public:
        Lexer(std::string program){
            this->source = program;
            this->start = program.begin();
            this->current = program.begin();
            
            this->line = 1;

            std::cout << std::distance(this->start, this->source.begin()) << std::endl;             
        }
        
        Token scan();      
};

当我打印 this->start 和 this->source.begin() 之间的距离时,我得到一些野数。根据我在课堂上输入的字符串,我得到了 40 甚至 448。我很困惑为什么会这样。

我尝试过更改变量名称,在 const_iterator 和 iterator 之间切换,以及打印 this->source、program、this->start 等。我很困惑为什么会出现这个问题。顺便说一句,语言是c++。我使用 std::distance 是否错误?

c++ iterator stdstring
1个回答
0
投票

这行代码:

this->source = program;

使变量

source
包含变量program
数据副本
。两个变量之后包含相同的字符串这一事实并不意味着它们的迭代器根本相关。您的代码可以简化如下:

std::string s1 = "abc";
std::string s2 = s1;
std::cout << std::difference( s1.begin(), s2.begin() ) << "\n";

这是无效的并导致 UB。 (尽管事实上你在 ctor 终止后将悬挂迭代器存储在

start
current
中,这是一个不同的问题)

© www.soinside.com 2019 - 2024. All rights reserved.