p1-stats

std::vector

A std::vector is a data structure that is part of the C++ Standard Library. Vectors are great for storing sequences of items, and we’ll store a sequence of doubles in this project.

You can use a std::vector by including the <vector> library at the the top of your program. In non-header files, you may add using std::vector; or using namespace std; to allow using the unqualified name vector (without the std:: prefix).

#include <vector>
using std::vector; // Optional, allows vector without std::
using namespace std; // Optional, allows anything without std::

Create a vector that hold doubles and fill it with 1.0, 2.0, 3.0.

vector<double> v;
v.push_back(1.0);
v.push_back(2.0);
v.push_back(3.0);

Shortcut: Create a vector that hold doubles and fill it with 1.0, 2.0, 3.0.

vector<double> v = {1.0, 2.0, 3.0};

Check the size, which is how many items live inside the vector.

cout << "There are " << v.size() << " elements in v";

Access each item in the vector and print it.

for (size_t i = 0; i < v.size(); i += 1) {
  cout << "v[" << i << "] = " << v[i] << "\n";
}

Write a function that passes a vector as input.

void print_vector(vector<double> v) {
  for (size_t i = 0; i < v.size(); i += 1) {
    cout << "v[" << i << "] = " << v[i] << "\n";
  }
}

Sort a vector using the std::sort() function from the <algorithm> library.

vector <double> v; // assume v contains some data
std::sort(v.begin(), v.end());

</div>

Further reading: http://www.cplusplus.com/reference/vector/vector/