Show Lecture.Vector as a slide show.
CS253 Vector
Old School
- Old-style C arrays still work just fine.
- They have no methods.
- They are NOT stretchy.
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<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
:
v.size()
: returns the current length, as a size_t
v.push_back()
: add an element to the end
v.pop_back()
: remove an element from the end
v.erase()
: remove an element from anywhere
v[i]
: indexing
- and many more methods
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
vector oops;
c.cc:1: error: class template argument deduction failed: