迭代器到int的向量

发布于 01-23 20:14 字数 608 浏览 3 评论 0原文

我在以下代码中有一个错误,我想在每个子向量中打印第一个元素:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一身软味 2025-01-30 20:14:16

问题(上述错误的原因)是由于 操作员优先 表达式*beg [0]被分组为(或等效于):

*(beg[0])

由于beg> beg 是迭代器,没有[]操作员。这是因为操作员[]比操作员*具有更高的优先级。

解决此替换cout&lt;&lt; *beg [0]&lt;&lt; endl; with:

cout << (*beg)[0] << endl;  //or use beg->at(0)

demo

The problem(cause of the mentioned error) is that due to operator precedence, the expression *beg[0] is grouped as(or equivalent to):

*(beg[0])

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:

cout << (*beg)[0] << endl;  //or use beg->at(0)

Demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文