简体   繁体   中英

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?

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 .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM