p1-stats
STL Vector
A vector
is a data structure that is part of the Standard Template Library (STL). Vectors are great for storing sequences of items, and we’ll store a sequence of doubles in this project.
You can use a vector by including the library at the the top of your program.
#include <vector>
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";
}
}
Store values in a vector-of-pair. This is useful for the summarize()
function.
vector<pair<double, int>> vp;
vp.push_back({1.2, 300});
vp.push_back({4.5, 600});
Access each item in the vector-of-pair and print it.
for (size_t i=0; i < vp.size(); ++i) {
cout << "vp[" << i << "] = {" << vp[i].first << ", " << vp[i].second << "}\n";
}
Further reading: http://www.cplusplus.com/reference/vector/vector/