Structs with Functions and Vectors

Passing a struct to a function

Structs can be passed like any other value. Use a const& to avoid copying when you only read it:

#include <iostream>
#include <string>
using namespace std;

struct Book {
    string title;
    string author;
    int pages;
};

void printBook(const Book& b) {
    cout << b.title << " by " << b.author << " (" << b.pages << " pages)\n";
}

int main() {
    Book b = {"The Hobbit", "J.R.R. Tolkien", 310};
    printBook(b);
    return 0;
}

Output

The Hobbit by J.R.R. Tolkien (310 pages)

Returning a struct

#include <iostream>
using namespace std;

struct Point {
    int x;
    int y;
};

Point addPoints(Point a, Point b) {
    Point result = {a.x + b.x, a.y + b.y};
    return result;
}

int main() {
    Point p = addPoints({1, 2}, {10, 20});
    cout << p.x << ", " << p.y << "\n";
    return 0;
}

Output

11, 22

A vector of structs

This is where structs really shine: a whole list of records, like rows in a spreadsheet:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Product {
    string name;
    double price;
    int stock;
};

int main() {
    vector<Product> shop = {
        {"Pen", 1.50, 120},
        {"Notebook", 3.25, 40},
        {"Backpack", 24.99, 0},
    };
    shop.push_back({"Ruler", 0.99, 75});

    for (const Product& p : shop) {
        cout << p.name << ": $" << p.price;
        if (p.stock == 0) {
            cout << " (sold out)";
        }
        cout << "\n";
    }
    return 0;
}

Output

Pen: $1.5
Notebook: $3.25
Backpack: $24.99 (sold out)
Ruler: $0.99

Structs can have functions too

A struct can contain its own functions (called member functions). They can use the members directly:

#include <iostream>
using namespace std;

struct Rectangle {
    double width;
    double height;

    double area() {
        return width * height;
    }
};

int main() {
    Rectangle r = {4, 2.5};
    cout << "Area: " << r.area() << "\n";
    return 0;
}

Output

Area: 10

Tip: This is the first step towards classes, which you'll learn in the next module.

HOME LABS COMMUNITY DASHBOARD