I am trying to parse this simple array from the reference of its first element.
Here is my code:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
vector<int> vec3 { 1,2,3,4,5};
for( vector<int>::iterator ptr = &vec3[0]; ptr != vec3.end(); ++ptr )
{
cout << *ptr << " ";
}
}
But I am getting this error:
[Error] conversion from '__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type* {aka int*}' to non-scalar type 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' requested
What's the problem?
Iterators of the class std::vector are not necessary pointers (though they can be defined such a way and indeed some old implementations of the class std::vector defined its iterators as pointers.). They usually are defined as classes.
And the compiler error says that there is no implicit conversion from the type value_type * to the type of the iterator.
So in general you have to write
vector<int> vec3 { 1,2,3,4,5};
for( vector<int>::iterator ptr = vec3.begin(); ptr != vec3.end(); ++ptr )
{
cout << *ptr << " ";
}
However in this particular case you could use the range-based for statement.
vector<int> vec3 { 1,2,3,4,5};
for ( const auto &item : vec3 )
{
cout << item << " ";
}
If you indeed want to deal with pointers then the loop can look for example the following way
#include <iostream>
#include <vector>
int main()
{
std::vector<int> vec3 { 1, 2, 3, 4, 5 };
for( auto ptr = vec3.data(); ptr != vec3.data() + vec3.size(); ++ptr )
{
std::cout << *ptr << ' ';
}
std::cout << '\n';
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With