// Examples of working with the Standard Template Library (the STL) // // Here is a comparison of C++ structures and corresponding Java structures: // C++ structure Java structure // -------------------------------- // vector ArrayList // list LinkedList // set TreeSet // multiset no equivalent // map TreeMap // pair Map.Entry // // Basic operations on the structure: // function/operator vector list set multiset // --------------------------------------------------------- // push_back(value) x x - - // push_front(value) - x - - // insert(value) - - x x // back() x x - - // front() x x - - // pop_back() x x - - // pop_front() - x - - // x[index] x - - - // size() x x x x // empty() x x x x // clear() x x x x // ==, !=, <, >, <=, >= x x x x // // Use of iterators on the structure: // function/operator vector list set multiset // --------------------------------------------------------- // begin() x x x x // end() x x x x // *iterator (const) x x x x // *iterator (reference) x x - - // iterator+n and +=n x - - - // iterator-n and -=n x - - - // erase(iterator) x x x x // insert(iterator, value) x x x x #include #include #include #include #include using namespace std; // returns a string version of the given vector as a comma-separated, // bracketed, list string vector_to_string(const vector & v) { ostringstream out; out << "["; if (v.size() > 0) { out << v[0]; for (int i = 1; i < v.size(); i++) { out << ", " << v[i]; } } out << "]"; return out.str(); } int main() { vector v {8, 13, 9, 6, 12, 42, 17, -8, 200}; auto itr = v.begin(); itr++; *itr = -2; cout << vector_to_string(v) << endl; cout << endl; itr = v.end(); cout << *(itr - 1) << endl; cout << endl; itr = v.begin(); itr += 5; *itr = -333; cout << vector_to_string(v) << endl; cout << endl; cout << "vector size = " << v.size() << endl; cout << "end - begin = " << (v.end() - v.begin()) << endl; cout << endl; // middle itr = v.begin() + (v.size()) / 2; *itr = -32; cout << vector_to_string(v) << endl; cout << endl; itr = v.begin() + (v.end() - v.begin()) / 2; *itr = -23; cout << vector_to_string(v) << endl; cout << endl; // inserts a -1 in front of every even # for (auto itr3 = v.begin(); itr3 != v.end(); itr3++) { if (*itr3 % 2 == 0) { itr3 = v.insert(itr3, -1); itr3++; } } cout << vector_to_string(v) << endl; cout << endl; for (auto itr3 = v.end() - 1; itr3 >= v.begin(); itr3--) { cout << *itr3 << " "; } cout << endl; cout << endl; // add some multiple of 3 and then loop to remove all multiples of 3 v.push_back(30); v.push_back(42); v.push_back(6); v.push_back(19); cout << vector_to_string(v) << endl; for (auto itr3 = v.begin(); itr3 != v.end(); itr3++) { if (*itr3 % 3 == 0) { itr3 = v.erase(itr3); itr3--; } } cout << vector_to_string(v) << endl; cout << endl; return 0; }