Carlos Miguel Colanta
Carlos Miguel Colanta

Reputation: 2823

Printing values using Iterator on 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 the other examples that i have seen, you only need to dereference the iterator to get the value, but in my case if i will use std::cout<< *pd << std::endl; it will print raw addresses which isn't what i want.

But if i will use std::cout<< *pd[0] << std::endl; then it will print the right values.

i visualize it like this :

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

wherein px will iterate 2 blocks and pd will have to iterate 4 blocks in total.

Why do i have to put [0] in order to print? or is that undefined?

Upvotes: 3

Views: 422

Answers (2)

timrau
timrau

Reputation: 23058

Since pd is of type std::vector<std::shared_ptr<int>>::iterator, *pd is of type std::shared_ptr<int>. You must dereference once more to get the integer value.

*pd[0] is equivalent to *(*(pd+0)), which is in turn equivalent to **pd.

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227578

Why do i have to put [0] in order to print? or is that undefined?

std::vector::iterator is a random access iterator. That provides operator[] with the same semantics as for a raw pointer. So, p[0] has the effect of de-referencing the iterator, giving you a shared_ptr lvalue reference. You then de-reference that with *, giving you the int it "points" to.

You could have done this too, which might have been easier to follow:

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

Upvotes: 2

Related Questions