Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse this vector through its 0th postition reference

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?

like image 249
Ashish M Avatar asked Sep 14 '26 09:09

Ashish M


1 Answers

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;
}
like image 72
Vlad from Moscow Avatar answered Sep 16 '26 06:09

Vlad from Moscow