Step 8
Structs and references
Group values into your own types with struct, and pass them to functions without copying.
Your own types
A struct groups related values into a new type. Each value is a member with its own type and name:
struct Point {
double x;
double y;
}; // note the semicolon after the closing brace
Create one by listing its members in order, in braces, and reach a member with a dot:
Point p{0.3, 0.1};
std::cout << p.x << "\n"; // 0.3
p.y = 0.2;
A member can be a struct too, and vectors can hold structs:
struct Target {
std::string color;
Point position;
};
std::vector<Target> targets = {{"red", {0.3, 0.1}}, {"green", {0.05, 0.2}}};
std::cout << targets[1].position.y << "\n"; // 0.2
The robot lessons work the same way. In Pick & Place, world.ball("red") gives you a Ball struct, and ball.position is where it is. Those names are taken, so call your own structs something else.
References
Passing a value to a function copies it, so the function can't change the caller's variable. An & after the type makes the parameter a reference instead: another name for the caller's own variable.
void move_right(Point& p, double dx) {
p.x += dx; // changes the caller's point
}
Copying a big vector every call is wasteful, so functions that only read a struct or a vector take a const reference: no copy, and the compiler stops the function from changing it. You'll see this all over the robot lessons:
double width(const std::vector<Point>& points);
Loops can do the same: for (const Target& t : targets) visits each target without copying it.
Your task
- Write
distance_between(a, b)so it returns the straight-line distance between two points: . - Write
closest(targets, gripper)so it returns the target nearest the gripper. If two are equally near, return the one that comes first.
Next up
That's the C++ you need to start. Next is Pick & Place, where your programs drive the arm itself, and later loop over every ball on the table to clear it. Choose C++ in the language menu above its editor: C++ there is part of Pro, and the Python version is free.
Its code uses a few things this lesson didn't cover. Here's what they mean:
#include "robot.hpp"brings in the robot:arm,gripper,world,simand their types.Vec3andVec4hold 3 and 4 numbers, for positions and joint angles. They come from the Eigen maths library.Vec4 READY(0.0, 0.5, 1.5, 1.14);makes one, andREADY[1]reads an item, as with a vector.- A
Vec3calledcupgives its coordinates through calls,cup.x()andcup.y(), rather than members like yourPoint'sp.x. PIis π, ready to use without#include <numbers>.