迭代器到int的向量
我在以下代码中有一个错误,我想在每个子向量中打印第一个元素:
vector<vector<int>> logs{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
for (auto beg = logs.begin(); beg != logs.end(); beg++) {
cout << *beg[0] << endl;
}
错误来自cout&lt;&lt; *beg [0] ...
:
Indirection requires pointer operand ('std::vector<int, std::allocator<int>>' invalid)
所以我的问题是:迭代器的Dreference应该在向量“日志”中的子向量,因此我使用下标访问其第一个元素。为什么有一个std :: vector&lt; int,std ::分配器&lt; int&gt;&gt;
对象? std ::分配器&lt; int
来自哪里?如何访问子向量中的元素?
I have an error in the following code where I want to print the first element in each sub-vector:
vector<vector<int>> logs{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
for (auto beg = logs.begin(); beg != logs.end(); beg++) {
cout << *beg[0] << endl;
}
the error is from cout << *beg[0]...
:
Indirection requires pointer operand ('std::vector<int, std::allocator<int>>' invalid)
So my question is: the dreference of the iterator should a sub-vector in the vector "logs", so I use subscript to access the first element of it. Why there's a std::vector<int, std::allocator<int>>
object? Where does the std::allocator<int>
come from? How can I access the elements in the sub-vectors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题(上述错误的原因)是由于 操作员优先 表达式
*beg [0]
被分组为(或等效于):由于
beg> beg 是迭代器,没有
[]
操作员。这是因为操作员[]
比操作员*
具有更高的优先级。解决此替换
cout&lt;&lt; *beg [0]&lt;&lt; endl;
with:demo
The problem(cause of the mentioned error) is that due to operator precedence, the expression
*beg[0]
is grouped as(or equivalent to):which can't work because
beg
is an iterator and has no[]
operator. This is because the operator[]
has higher precedence than operator*
.To solve this replace
cout << *beg[0] << endl;
with:Demo