C++ Intermediate Introduction
C++ Intermediate is the course that follows the beginner course. It takes the classes, vectors, and functions from before and puts them to harder work.
A vector summed by a function
The sumScores function takes a vector and adds its values. Main prints the total the function returns.
#include <iostream>
#include <vector>
int sumScores(std::vector<int> scores) {
int total = 0;
for (int score : scores) {
total += score;
}
return total;
}
int main() {
std::vector<int> scores = {85, 90, 78};
std::cout << "Total: " << sumScores(scores) << std::endl;
return 0;
}A small class with a constructor
The Book class holds a title and a page count. Its constructor fills both members when an object is made.
#include <iostream>
#include <string>
class Book {
public:
std::string title;
int pages;
Book(std::string t, int p) {
title = t;
pages = p;
}
void describe() {
std::cout << title << " has " << pages << " pages" << std::endl;
}
};
int main() {
Book b("Dune", 412);
b.describe();
return 0;
}Example
#include <iostream>
#include <string>
#include <vector>
int sumScores(std::vector<int> scores) {
int total = 0;
for (int score : scores) {
total += score;
}
return total;
}
class Book {
public:
std::string title;
int pages;
Book(std::string t, int p) {
title = t;
pages = p;
}
void describe() {
std::cout << title << " has " << pages << " pages" << std::endl;
}
};
int main() {
std::vector<int> scores = {70, 80, 90};
std::cout << "Total: " << sumScores(scores) << std::endl;
Book b("Dune", 412);
b.describe();
return 0;
}Key points
- This course starts with classes that clean up after themselves.
- It shows how objects are copied and how objects are moved.
- It covers smart pointers that own objects and free them on their own.
- It goes deeper into containers and the algorithms that work on them.
- It adds templates that write one piece of code for many types.
- It adds lambdas, small unnamed functions written where they are used.
- It ends with files, streams, and a small project that joins the pieces.
In this example, sumScores adds the three scores and returns 240. The Book constructor fills the title and the page count. The describe method prints both members in one line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does sumScores return for the vector {85, 90, 78}?