CS253: Software Development with C++

Fall 2019

Vector

Show Lecture.Vector as a slide show.

CS253 Vector

Old School

int a[10];
for (int i=0; i<10; i++)
    a[i] = i*i;
for (int i=0; i<10; i++)
    cout << a[i] << ' ';
0 1 4 9 16 25 36 49 64 81 

int a[10];
for (int i=0; i<10; i++)
    a[i] = i*i;
for (auto val : a)
    cout << val << ' ';
0 1 4 9 16 25 36 49 64 81 

vector

vector<int> v;
for (int i=0; i<10; i++)
    v.push_back(i*i*i);
for (size_t i=0; i<v.size(); i++)
    cout << v[i] << ' ';
0 1 8 27 64 125 216 343 512 729 

vector<int> v(10);
for (int i=0; i<10; i++)
    v[i] = i*i*i;
for (auto val : v)
    cout << val << ' ';
0 1 8 27 64 125 216 343 512 729 

Useful vector methods

For a vector named v:

vector constructors

Vectors have several constructors, including:

// default size of zero elements
vector<float> a;

// initialize with these values
vector<float> b = {1.2, 3.4};

// resize to this many zeroes
vector<float> c(170);

if (a != b)
    cout << "unequal\n";
unequal

vector of anything

You can have a vector of nearly any type, but you have to pick one.

vector<string> some_strings;
vector<double> some_doubles(42);
vector<bool> some_bools = {true, false};

cout << some_strings.size() << '\n';
cout << some_doubles.size() << '\n';
cout << some_bools.size() << '\n';
0
42
2