I came from python and I'm trying to learn c++ now, and I'm trying to print something that looks like python's list
= [1, 2, 3]
in c++. I let user to chose a size of array and insert a numbers inside and after that I would like to cout
the result in above fashion, but I'm not able to loop over values in array
because the variable pointing to a pointer
not the array
itself. Could me please somebody explain a workaround?
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 MSG
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>&);
|