【发布时间】:2020-08-06 00:20:04
【问题描述】:
我来自 python,现在我正在尝试学习 c++,我正在尝试在 c++ 中打印一些看起来像 python 的 list = [1, 2, 3] 的东西。我让用户选择数组的大小并在其中插入一个数字,然后我想cout以上述方式得到结果,但我无法循环array中的值,因为变量指向pointer 不是 array 本身。有人可以解释一下解决方法吗?
int main() {
int i, n;
cout << "How many values?";
cin >> i;
int * foo;
foo = new (nothrow) int [i];
if (foo == nullptr) {
cout << " Could Not allocate so much memory";
}
else {
for (n=0; n<i; n++) {
cout << "Enter Number: " << endl;
cin >> foo[n];
}
}
cout << "[";
for (int *n: foo){
cout << n << ", ";
}
cout << "]" << endl;
return 0;
}
错误信息
error: ‘begin’ was not declared in this scope; did you mean ‘std::begin’?
31 | for (int *n: foo){
| ^~~
| std::begin
In file included from /usr/include/c++/9/string:54,
from /usr/include/c++/9/bits/locale_classes.h:40,
from /usr/include/c++/9/bits/ios_base.h:41,
from /usr/include/c++/9/ios:42,
from /usr/include/c++/9/ostream:38,
from /usr/include/c++/9/iostream:39,
from study.cpp:1:
/usr/include/c++/9/bits/range_access.h:105:37: note: ‘std::begin’ declared here
105 | template<typename _Tp> const _Tp* begin(const valarray<_Tp>&);
| ^~~~~
study.cpp:31:18: error: ‘end’ was not declared in this scope; did you mean ‘std::end’?
31 | for (int *n: foo){
| ^~~
| std::end
In file included from /usr/include/c++/9/string:54,
from /usr/include/c++/9/bits/locale_classes.h:40,
from /usr/include/c++/9/bits/ios_base.h:41,
from /usr/include/c++/9/ios:42,
from /usr/include/c++/9/ostream:38,
from /usr/include/c++/9/iostream:39,
from study.cpp:1:
/usr/include/c++/9/bits/range_access.h:107:37: note: ‘std::end’ declared here
107 | template<typename _Tp> const _Tp* end(const valarray<_Tp>&);
|
【问题讨论】:
-
谢谢,当我想使用 C 风格的数组时,这看起来最合适,但是我很难理解重载>。
-
只需使用常规的
for循环,就像填充数组时一样,例如:for (n=0; n<i; n++) { cout << foo[n] << ", "; }