Printing values ​​using an Iterator on a 2d vector

Here is my code:

std::vector< std::vector<std::shared_ptr<int>> > om(2, std::vector<std::shared_ptr<int>>(2));
om[0][0] = std::shared_ptr<int>(std::make_shared<int>(1));
om[0][1] = std::shared_ptr<int>(std::make_shared<int>(2));
om[1][0] = std::shared_ptr<int>(std::make_shared<int>(3));       //init values
om[1][1] = std::shared_ptr<int>(std::make_shared<int>(4));

std::vector<std::shared_ptr<int>>::iterator pd;                  //inner iterator
std::vector< std::vector<std::shared_ptr<int>> >::iterator px;   //outer iterator


for(px = om.begin(); px != om.end(); px++){                    
    for(pd = (*px).begin(); pd !=  (*px).end(); pd++){

    std::cout<< *pd[0] << std::endl;
    }

}

      

Output:

1 2 3 4

I am making a 2d vector using shared_ptr

and my goal is to print the values

My questions:

From other examples I've seen, you only need to dereference the iterator to get the value, but in my case, if I use it std::cout<< *pd << std::endl;

, it will print raw addresses, which is not what I want.

But if I use std::cout<< *pd[0] << std::endl;

then it will print the correct values.

i render it like this:

[ [1][2], [3][4] ]

      

where px will iterate over 2 blocks and pd will iterate over 4 blocks in total.

Why do I need to [0]

print? or what is undefined?

+3


source to share


2 answers


Since it pd

has a type std::vector<std::shared_ptr<int>>::iterator

, it *pd

has a type std::shared_ptr<int>

. You have to dereference again to get an integer value.



*pd[0]

is equivalent *(*(pd+0))

, which in turn is equivalent **pd

.

+3


source


Why do I need to put [0] for printing? or what is undefined?

std::vector::iterator

is a random access iterator. This gives operator[]

the same semantics as for a raw pointer. So p[0]

has the effect of de-referencing the iterator, giving you an shared_ptr

lvalue reference . You then remove the link using *

, giving you int

it "points" to.



You could do this too, which would be easier:

std::cout<< **pd << std::endl;

      

+2


source







All Articles