/* Sequence Containers: vector, list, string (vector) extra list operations: front(), push_front(val), pop_front(), reverse() */ #include #include #include #include #include // for rand using namespace std; void print(const vector & v) { vector::size_type size = v.size(); cout << "size is " << size << endl; vector::const_iterator cvi; // read-only access for (cvi = v.begin(); cvi != v.end(); cvi++) cout << *cvi << " "; cout << endl; } void print(list l) // bad: will make copy, should declare as above { list::const_iterator cvi; // read-only access for (cvi = l.begin(); cvi != l.end(); cvi++) cout << *cvi << " "; cout << endl; } int main() { vector v; // empty vector v.push_back(13); v.push_back(20); v.push_back(3); vector::size_type vsize; vsize = v.size(); // actual # of elements cout << "v size is " << vsize << endl; cout << "v capacity is " << v.capacity() << endl; // cout << "printing v " << v << endl; // << not defined for vectors print(v); const int SIZE = 10; int a[SIZE] = {2, 3, 4, 5}; vector vec(a, a+4); // vec is copy of {2, 3, 4, 5} cout << "vec is: " << flush; print(vec); cout << "vec[0] is : " << vec[0] << endl; cout << "vec.at(3) is " << vec.at(3) << endl; vector v2(10); // starting capacity 10, init to 0 vector v3(10, 5); // 10 values, all 5 if (v.empty()) v.assign(10,2); // create cap 10, init to 2 v.assign(v3.begin() + 1, v3.end() - 1); v.resize(25, 2); // change capacity to 25, new values are 2 v.reserve(25); vector::iterator vi; vi = v3.begin(); v3.insert(vi+3, 20); cout << "v3 new size " << v3.size() << endl; print(v3); cout << "vi points to: " << *vi << endl; vi = v3.begin(); v3.insert(vi+5, vec.begin(), vec.end()); cout << "v3 new size " << v3.size() << endl; print(v3); // v3.sort(); // not right syntax for vectors!!! sort(v3.begin(), v3.end()); // assumes < defined for base type cout << "v3 sorted: " << flush; print(v3); cout << "v3 capacity: " << v3.capacity() << endl; list l(v3.begin(), v3.end()); // makes copy cout << "copied list size: " << l.size() << endl; l.clear(); cout << "cleared list size: " << l.size() << endl; for (int i=0; i < 20; i++) l.push_front(rand()%20); cout << "random list: " << flush; print(l); l.sort(); cout << "list sorted: " << flush; print(l); // cout << "list capacity: " << l.capacity() << endl; // no such method for lists } /* OUTPUT: v size is 3 v capacity is 4 size is 3 13 20 3 vec is: size is 4 2 3 4 5 v3 new size 11 size is 11 5 5 5 20 5 5 5 5 5 5 5 v3 new size 15 size is 15 5 5 5 20 5 2 3 4 5 5 5 5 5 5 5 v3 sorted: size is 15 2 3 4 5 5 5 5 5 5 5 5 5 5 5 20 v3 capacity: 20 copied list size: 15 cleared list size: 0 random list: 16 12 6 0 6 3 19 10 7 2 1 9 12 6 15 13 15 17 6 3 list sorted: 0 1 2 3 3 6 6 6 6 7 9 10 12 12 13 15 15 16 17 19 */