我可以打印对象向量中元素的索引吗?

1 c++ loops vector

所以我知道要循环打印一些东西,代码如下所示:

for(int I = 0; I < num; ++I)...
Run Code Online (Sandbox Code Playgroud)

并打印对象向量:

for(Square sq : squares)...
Run Code Online (Sandbox Code Playgroud)

(如果我有一个类 Square 并且我创建了对象 sq 并且 squares 是向量的名称)

但是,如果我希望输出如下所示,我该如何编写代码:

方格1面积:3 方格2面积:6 方格3面积:9

更清楚地说:我的问题是,如何将第一个示例中的“I”合并到打印对象的循环中?

woh*_*tad 5

你可以这样做:

for (size_t idx=0; idx<squares.size(); ++idx)
{
    Square const & sq = squares[idx];

    // Here you can use both:
    //      idx (which is the index in the vector), 
    //      and sq (reference to the element).
}
Run Code Online (Sandbox Code Playgroud)

事实上sq, astd::vector并不意味着您必须使用基于范围的循环(基于范围的 for 循环)来遍历它。

Astd::vector有一个获取其大小的方法(std::vector::size),以及用于访问元素的 operator[] (std::vector::operator[])。

注意- 即使您确实使用基于范围的循环,最好使用引用(或 const 引用)以避免不必要的复制:

for(Square const & sq : squares)   // without `const` if you need to modify the element
{
   //...
}
Run Code Online (Sandbox Code Playgroud)