简体   繁体   English

在2d向量上使用Iterator打印值

[英]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 1 2 3 4

I am making a 2d vector using shared_ptr , and my goal is to print the values 我正在使用shared_ptr创建一个二维矢量,我的目标是打印值

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; 从我看到的其他示例中,您只需要取消引用迭代器来获取值,但在我的情况下,如果我将使用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; 但是如果我将使用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. 其中px将迭代2个块,pd将不得不迭代4个块。

Why do i have to put [0] in order to print? 为什么我必须放[0]才能打印? or is that undefined? 还是那个未定义?

Since pd is of type std::vector<std::shared_ptr<int>>::iterator , *pd is of type std::shared_ptr<int> . 由于pd的类型为std::vector<std::shared_ptr<int>>::iterator ,因此*pd的类型为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 . *pd[0]相当于*(*(pd+0)) ,它相当于**pd

Why do i have to put [0] in order to print? 为什么我必须放[0]才能打印? or is that undefined? 还是那个未定义?

std::vector::iterator is a random access iterator. std::vector::iterator是一个随机访问迭代器。 That provides operator[] with the same semantics as for a raw pointer. 这为operator[]提供了与原始指针相同的语义。 So, p[0] has the effect of de-referencing the iterator , giving you a shared_ptr lvalue reference. 因此, p[0]具有取消引用迭代器的效果,为您提供shared_ptr左值引用。 You then de-reference that with * , giving you the int it "points" to. 然后你用*取消引用它,给你它“指向”的int

You could have done this too, which might have been easier to follow: 您也可以这样做,这可能更容易遵循:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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