So I know to print something in a loop, the code looks like this:
for(int I = 0; I < num; I)...
And to print an object vector:
for(Square sq : squares)...
(if I have a class Square and I create the object sq and squares is the name of the vector)
But how would I go about code if I want my output to look like:
square 1 area: 3 square 2 area: 6 square 3 area: 9
To be more clear: my question is, how do I incorporate "I" like in the first example in a loop where I'm printing objects?
CodePudding user response:
You can do it like this:
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).
}
The fact that sq
is a std::vector
does not mean you must traverse it using the range-based loop (Range-based for loop).
A std::vector
has a method for getting its size (std::vector::size), and operator[] to access an element (std::vector::operator[]).
Note - even if you do use the range-based loop, it is better to use a refernce (or const reference) to avoid unnecessary copies:
for(Square const & sq : squares) // without `const` if you need to modify the element
{
//...
}
CodePudding user response:
You can also combine range based for and another index variable
// with c 20 range-based for can have initializer in it
for(auto i=1; auto& s:squares){
std::cout << "square " << i << " area: " << s << '\n' ;
i;
}
https://godbolt.org/z/EfhefdoGP
pre-c 20
{
auto i=1;
for(auto& s:squares){
std::cout << "square " << i << " area: " << s << '\n' ;
i;
}
}
CodePudding user response:
Because the elements of the vector are lined up continuously... It may be possible to do something like this.
class Object
{
public:
Object( int a, int b ) : a(a),b(b) {}
int a,b;
};
int main()
{
std::vector<Object> Vec{ {1,2}, {10,20}, {100,200} };
for( const auto &obj : Vec )
{
auto index = &obj - &Vec[0]; //calculate index of element
std::cout << index << " : " << obj.a << "," << obj.b << std::endl;
}
return 0;
}