File I/O

Use fstream like iostream.

vector<double> read_data(string filename) {
  ifstream ifs{filename};
  vector<double> data;

  // Make sure the file was opened successfully
  if (!ifs.is_open()) // or if(!ifs)
    throw illegal_argument("Couldn't open file");

  // Read data until we hit EOF
  while (ifs.good()) { // or while(ifs)
    double v;
    ifs >> v;
    data.push_back(v);
  }
  return data;
}

Streams can be used in conditional expressions. (Check the comment above.)

ifstream destructor will automatically close the file when the ifs object goes out of scope. If it need to be closed, there is a member function close().

Variable Scope

A variable's scope is the part of the program where the variable is accessible.

Function Arguments

Arguments are pased by value as a default. The function receives a copy of the arguments, not the original.

Passing arguments by references will be preferred when the data is too big to copy it.

// use `&`
double compare_something_heavy(vector<double> &values) {
  //...

The function can change the original value when it passed by reference.

It is able to specify that argument's value cannot change by using const modifier.

double compute_average(const vector<double> &values) {
  // Function signature need to be matched declaration and definition
  //...

Guidelines

const and user-defined classes

Define const on member functions when the member functions are not mutating any data.

class Point {
  // ...
  double get_x() const; // Accessors
  double get_y() const;
  // ...
}

double Point::get_x() const {
  // ...
}
// ...

Coming up next

Website Setting

Select a website color

Darkreader plugin could override color setting here.