// // Very simple program demonstrating use of C++ library class "vector". // // Briefly, a C++ vector is an expandable array with a type parameter. // It also allows insertions and deletions, though not very efficiently. // (So if your application needs that functionality, you probably should // use another class such as list -- but to keep things simple for now // you can use vector.) // // Notice use of size_type for loop counters. Integers would (probably!) // work too, but size_type is specifically designed to represent values // that are indices or sizes of vectors. // #include #include #include using std::vector; void printvector(vector v) { for (vector::size_type i = 0; i < v.size(); ++i) { printf("%d\n", v[i]); } } int main(void) { vector items; // vector of ints // append values to vector items.push_back(1); items.push_back(2); items.push_back(3); items.push_back(4); // print printf("initial vector\n"); printvector(items); // change items for (vector::size_type i = 0; i < items.size(); ++i) { items[i] *= 2; } printf("vector after changes\n"); printvector(items); // delete items // (parameter to erase must be an iterator, and begin() supplies one // that points to the first element) items.erase(items.begin()+3); items.erase(items.begin()+1); printf("vector after deletions\n"); printvector(items); // insert items items.insert(items.begin(),10); items.insert(items.begin()+2,20); printf("vector after insertions\n"); printvector(items); return 0; }