矢量<string>数组发生了什么?
What is happening with vector<string> array?
我正在编写一个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
};
导致问题的是IDENTIFIER
和LITERAL
选项。以下逻辑尝试检索正确的矢量容器,并添加新值并识别位置或识别现有值的位置:
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];
相关文章:
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 这C++代码中发生了什么C++(指数函数)
- 哪种方式更快?究竟发生了什么,我们没有看到什么?
- 从"LLONG_MAX 秒"构造 std::chrono::毫秒变量时发生了什么?
- 这个片段中关于 n 在 pc[i] 中的表示发生了什么
- istringstream,num1 和 num2 在这里发生了什么?
- 究竟发生了什么,我们需要在 c++ 中双重调度/访客
- 我是否能够确定在部署一个程序后发生了什么,我在数组末尾写入?
- 这个阶乘程序内部发生了什么?
- C++ - *(int**) 地址?这里发生了什么?
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 让对象知道它创建的 show 函数中发生了什么
- 这里的矢量数组发生了什么?
- 增加顶级常量指针时发生了什么
- 当另一端将其关闭时,插座发生了什么
- C :我堆栈顶部发生了什么
- 此递归中发生了什么?我需要仅使用递归/无循环来计算和备份
- 这个 std::vector 构造函数中发生了什么
- 编译器认为 int 是一个字符串.发生了什么事情
- 无法运行简单的 std::async 和 std::future 测试程序。错误:"has initializer but incomplete type."发生了什么?