Array of structs
- C++ course
- Beginner
- Lesson 97/116
- 5 min
Learn to create a vector of structs and iterate it.
Creating a vector of structs
To manage many instances of the same struct, you use a vector. The declaration vector<Point> creates a dynamic array whose elements are Point values.
vector<Point> points;
Point p;
p.x = 1;
p.y = 2;
points.push_back(p);Here points is a vector of Point; push_back adds a new element. Elements are accessed like points[0].x. The #include <vector> header is required.
Iterating with a loop
To walk through all elements of a struct vector, you use a loop. The easiest way is the range-based for loop.
for (Point p : points) {
cout << p.x << ", " << p.y << endl;
}Here the loop copies each element into p in turn. To iterate without copying, use for (const Point& p : points). The range-based loop is a short way to walk through all elements without knowing the vector's length.
Practice Add two Points and iterate
Add the #include <vector> header. Declare vector<Point> points;. Create two Points and add them with points.push_back(...); the first has x=1, y=2, the second x=3, y=4. Use a range-based for to print each element's x and y.
Starter code
#include <iostream>
#include <vector>
using namespace std;
struct Point {
int x;
int y;
};
int main() {
// declare a Point vector, add two Points, print with for
return 0;
}Sample solution
#include <iostream>
#include <vector>
using namespace std;
struct Point {
int x;
int y;
};
int main() {
vector<Point> points;
Point a; a.x = 1; a.y = 2;
Point b; b.x = 3; b.y = 4;
points.push_back(a);
points.push_back(b);
for (Point p : points) {
cout << p.x << ", " << p.y << endl;
}
return 0;
}Expected output
1, 2 3, 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: vector declaration
#include <vector>
using namespace std;
vector<Point> ____;
points.push_back(p);
#include <vector>
using namespace std;
vector<Point> points;
points.push_back(p);
Explanation: A vector<Point> named points was created.
2 Which header is required for vector<Point>?
- <string>
- <vector> Correct answer
- <array>
- <list>
Explanation: The <vector> header is required for vector.
3 Match each method with its job
| Term | Meaning |
|---|---|
push_back |
adds to the end |
size |
returns the length |
[i] |
gives the i-th element |