Задать вопрос
@alikhan_hero

Почему не работает оператор for each в C++?

int main() {
	const int rows = 3, columns = 2;
	int numbers[rows][columns] = { {1, 2}, {5, 4}, {9, 7} };

	for (int subnumbers : numbers)
	{
                std::cout << subnumbers[0] << " " << subnumbers[1] << std::endl;
		for (auto num : subnumbers) {
			std::cout << num << std::endl;
		}
	}
}



est.cpp: In function ‘int main()’:
test.cpp:16:14: error: declaration of ‘subnums’ as array of references
16 | int& subnums[] = numbers[0];
| ^~~~~~~
test.cpp:18:43: error: ‘subnums’ was not declared in this scope
18 | std::cout << numbers[0] << " " << subnums << std::endl;
| ^~~~~~~
alikhan@alikhan:~/Рабочий стол/test$ g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:14:14: error: declaration of ‘subnums’ as array of references
14 | int& subnums[] = numbers[0];
| ^~~~~~~
test.cpp:14:26: error: ‘numbers’ was not declared in this scope
14 | int& subnums[] = numbers[0];
| ^~~~~~~
test.cpp:16:43: error: ‘subnums’ was not declared in this scope
16 | std::cout << numbers[0] << " " << subnums << std::endl;
| ^~~~~~~
test.cpp:25:33: error: ‘begin’ was not declared in this scope; did you mean ‘std::begin’?
25 | for (auto num : subnumbers) {
| ^~~~~~~~~~
| std::begin
In file included from /usr/include/c++/11/string:54,
from /usr/include/c++/11/bits/locale_classes.h:40,
from /usr/include/c++/11/bits/ios_base.h:41,
from /usr/include/c++/11/ios:42,
from /usr/include/c++/11/ostream:38,
from /usr/include/c++/11/iostream:39,
from test.cpp:1:
/usr/include/c++/11/bits/range_access.h:108:37: note: ‘std::begin’ declared here
108 | template const _Tp* begin(const valarray<_Tp>&) noexcept;
| ^~~~~
test.cpp:25:33: error: ‘end’ was not declared in this scope; did you mean ‘std::end’?
25 | for (auto num : subnumbers) {
| ^~~~~~~~~~
| std::end
In file included from /usr/include/c++/11/string:54,
from /usr/include/c++/11/bits/locale_classes.h:40,
from /usr/include/c++/11/bits/ios_base.h:41,
from /usr/include/c++/11/ios:42,
from /usr/include/c++/11/ostream:38,
from /usr/include/c++/11/iostream:39,
from test.cpp:1:
/usr/include/c++/11/bits/range_access.h:110:37: note: ‘std::end’ declared here
110 | template const _Tp* end(const valarray<_Tp>&) noexcept;
|


В первом цикле я могу обращаться к subnumbers по индексам, но при использовании оператора for each для перебора самих элементво subnumbers происходит ошибка. Мне нужно не решение этой проблемы. Я бы хотел знать почему эта ошибка происходит. Буду очень благодарен за объяснение.
  • Вопрос задан
  • 44 просмотра
Подписаться 1 Простой 5 комментариев
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы