AlgoDaily

Data Structures in C++

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Why Structure Data

From objects to organized data

Now that we've covered Introduction to C++ and Object-Oriented Programming in C++, you can write programs with functions, loops, classes, constructors, and encapsulated state.

The next question is: where should your data live while the program runs?

Data structures are containers and patterns for organizing values so your program can:

  • remember many items, not just one variable
  • find values again later
  • preserve order when order matters
  • model real systems like portfolios, message queues, game inventories, or AI training records

In C++, most everyday data structures come from the Standard Library, especially containers like vector, map, set, stack, and queue.

Why Structure Data

Vector Basics

std::vector: the everyday list

If you come from web development, think of std::vector as C++'s common growable array-like container.

Use a vector when you want:

  • items in a specific order
  • fast access by index, like prices[2]
  • a collection that can grow as you add items

Unlike a raw array, a vector manages its own storage. You still choose the element type, so vector<int> stores integers and vector<string> stores strings.

```cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<double> prices = {101.25, 103.80, 99.50};

    prices.push_back(105.10); // add to the end

    cout << "Tracked prices:\n";
    for (int i = 0; i < prices.size(); i++) {
        cout << "Day " << i + 1 << ": $" << prices[i] << "\n";
    }

    cout << "Latest price: $" << prices.back() << "\n";
    return 0;
}
```

Choose A Container

You are storing a sequence of daily closing prices. You care about the order and want to access values by index, such as the third day.

Which C++ Standard Library container is the best starting choice?

Restricted Access

Stacks and queues

Some data structures are useful because they limit how data is accessed.

std::stack

A stack is last in, first out.

push A, push B, push C
pop -> C

Good mental models:

  • browser history
  • undo actions
  • nested function calls
std::queue

A queue is first in, first out.

enqueue A, enqueue B, enqueue C
dequeue -> A

Good mental models:

  • customer support tickets
  • print jobs
  • incoming tasks for a server

These containers are less flexible than vectors on purpose. The restriction makes your intent clearer.

Restricted Access

Queue Access

A std::queue is designed so you can directly inspect and remove any item from the middle whenever you want.

Keys And Values

Maps and sets

When you do not just want a sequence, you may want a container based on identity.

std::map

A map stores key-value pairs:

  • ticker symbol -> price
  • username -> profile
  • product id -> inventory count
std::set

A set stores unique values:

  • unique tags
  • visited pages
  • distinct user IDs

A map answers: what value belongs to this key?

A set answers: have I seen this value before?

```cpp
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;

int main() {
    map<string, double> prices;
    prices["AAPL"] = 189.40;
    prices["MSFT"] = 421.90;
    prices["NVDA"] = 875.30;

    set<string> watchlist;
    watchlist.insert("AAPL");
    watchlist.insert("NVDA");
    watchlist.insert("AAPL"); // duplicate ignored

    cout << "MSFT price: $" << prices["MSFT"] << "\n";
    cout << "Watchlist size: " << watchlist.size() << "\n";

    if (watchlist.count("AAPL") > 0) {
        cout << "AAPL is on the watchlist.\n";
    }

    return 0;
}
```

Name The Type

In C++, the Standard Library growable array-like container is std::____.

Choosing Containers

Start with the question

Do not pick a data structure because it sounds advanced. Pick it because it matches how the program needs to use data.

Need Good starting choice Ordered list with index access std::vector Last item added should come out first std::stack First item added should come out first std::queue Key-value lookup std::map Unique values only std::set

A useful habit: describe the operations in plain English first.

For example: "I need to add tasks as they arrive and process the oldest task first." That sentence points naturally to a queue.

Next lesson, Algorithms in C++, will build on this by showing how we transform and search through these containers.

Choosing Containers

Objects Hold Containers

Data structures inside classes

From Object-Oriented Programming in C++, you learned that classes can protect and organize state. Containers make that state scalable.

Instead of storing one transaction, an object can store many transactions in a vector.

Notice the design idea: outside code asks the object to do something meaningful, while the object manages its own internal container.

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

class Portfolio {
private:
    vector<string> holdings;

public:
    void addHolding(string ticker) {
        holdings.push_back(ticker);
    }

    void printHoldings() const {
        cout << "Portfolio holdings:\n";
        for (string ticker : holdings) {
            cout << "- " << ticker << "\n";
        }
    }
};

int main() {
    Portfolio myPortfolio;
    myPortfolio.addHolding("AAPL");
    myPortfolio.addHolding("MSFT");
    myPortfolio.addHolding("NVDA");

    myPortfolio.printHoldings();
    return 0;
}
```

Best Match

You are building a simple AI experiment tracker. Each experiment has a unique name, and you want to quickly associate that name with its accuracy score.

Which container best matches that need?

Open interactive view →