是否可以使用索引迭代器访问另一个数组的索引?
Is it possible to use an indexed iterator to access the index of another array?
我正在尝试在循环中使用构造为 std::vector<std::array<int,3>>::iterator
数据类型的迭代器来访问 std::array 的索引,但是每当我取消引用迭代器并为其编制索引时,我都会得到错误“没有运算符“*”匹配这些操作数”。我该怎么做才能解决这个问题?
std::vector<std::array<int,3>> x = {{0,1,2},{5,1,6}};
std::vector<std::array<int,3>>::iterator it;
std::array<int, 1000> y;
for (it = x.begin(); it != x.end(); it++) {
if (y[*it[0]] == 0){
do something;
}
[]
的优先级高于*
(https://en.cppreference.com/w/cpp/language/operator_precedence)
你需要写(*it)[0]
.
作为旁注,使用 range-for loop 或
<algorithm>
(std::for_each()
,
std::transform()
, std::find_if()
...) 小于 error-prone
而不是明确地处理迭代器(或索引)
在循环中。
确实,正如@prog-fh 和@Borgleader 所建议的,您需要使用括号来阐明哪个运算符适用于什么。
我会注意到,如果您可以使用 C++20,则可以这样编写代码:
using triplet = std::array<int,3>;
std::vector<triplet> x = {{0,1,2},{5,1,6}};
std::array<int, 1000> y;
// initialize y somehow...
auto filter_by_y = [&y](const triplet& tr) { return y[tr[0]] == 0; }
for (const auto& triplet : x | std::views::filter(filter_by_y) ) {
do_something(triplet);
}
现在您的代码中 没有 if
并且没有原始循环。您可以在此处阅读有关 filter-views 的更多信息。
我正在尝试在循环中使用构造为 std::vector<std::array<int,3>>::iterator
数据类型的迭代器来访问 std::array 的索引,但是每当我取消引用迭代器并为其编制索引时,我都会得到错误“没有运算符“*”匹配这些操作数”。我该怎么做才能解决这个问题?
std::vector<std::array<int,3>> x = {{0,1,2},{5,1,6}};
std::vector<std::array<int,3>>::iterator it;
std::array<int, 1000> y;
for (it = x.begin(); it != x.end(); it++) {
if (y[*it[0]] == 0){
do something;
}
[]
的优先级高于*
(https://en.cppreference.com/w/cpp/language/operator_precedence)
你需要写(*it)[0]
.
作为旁注,使用 range-for loop 或
<algorithm>
(std::for_each()
,
std::transform()
, std::find_if()
...) 小于 error-prone
而不是明确地处理迭代器(或索引)
在循环中。
确实,正如@prog-fh 和@Borgleader 所建议的,您需要使用括号来阐明哪个运算符适用于什么。
我会注意到,如果您可以使用 C++20,则可以这样编写代码:
using triplet = std::array<int,3>;
std::vector<triplet> x = {{0,1,2},{5,1,6}};
std::array<int, 1000> y;
// initialize y somehow...
auto filter_by_y = [&y](const triplet& tr) { return y[tr[0]] == 0; }
for (const auto& triplet : x | std::views::filter(filter_by_y) ) {
do_something(triplet);
}
现在您的代码中 没有 if
并且没有原始循环。您可以在此处阅读有关 filter-views 的更多信息。