矢量<string>数组发生了什么?

What is happening with vector<string> array?

本文关键字:什么 发生了 数组 string lt 矢量 gt      更新时间:2023-10-16

我正在编写一个lex扫描仪,在其中我定义了一个数组,如下所示:

// array of vector<string>
std::vector<std::string> Lexicals[5] = {
    //  [0] OPERATORS (pre-initialized with values)
    {"...", "..."},
    //  [1] PUNCTUATIVES (pre-initialized with values)
    {"...", "..."},
    //  [2] KEYWORDS (pre-initialized with values)
    {"...", "..."},
    //  [3] IDENTIFIERS  - add as found
    std::vector<std::string>(),
    //  [4] LITERALS  - add as found
    std::vector<std::string>()
};

使用以下enum,我可以评估lexType,并通过enum值(0-4)得到匹配的vector

enum LexType {
    OPERATOR, 
    PUNCTUATION, 
    KEYWORD, 
    IDENTIFIER, 
    LITERAL
};

导致问题的是IDENTIFIERLITERAL选项。以下逻辑尝试检索正确的矢量容器,并添加新值并识别位置或识别现有值的位置:

case LexType::IDENTIFIER:
case LexType::LITERAL: {
    string val(read_buffer(), m_length);
    //  Lexicals[3] || [4]
    vector<string> lex = Lexicals[m_lexType];
    vector<string>::iterator it;
    //  make sure value is not already in the vector
    if(!lex.empty()){
        it = find(lex.begin(), lex.end(), val);
        if(it == lex.end()) {                    
            lex.push_back(val);
            it = std::find(lex.begin(), lex.end(), val);
        }
    } else {                
        lex.push_back(val);
        it = find(lex.begin(), lex.end(), val);
    }
    m_lexical = it - lex.begin();
}
break;

在第一次通过之后的每次迭代中,!lex.empty()被绕过。我只是想弄清楚发生了什么。

问题很可能是这一行:

vector<string> lex = Lexicals[m_lexType];

在这里,您可以通过值获得向量,这意味着它被复制了。然后,当您稍后执行lex.push_back(val)时,您只附加到副本,而不是原始向量。

相反,lex是实际(原始)矢量的参考

vector<string>& lex = Lexicals[m_lexType];