/ Published in: C++
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
VECTOR (Variable sized array/stack with built in memory allocation) vector<int> a(10); // a[0]..a[9] are int (default size is 0) a.size(); // Number of elements (10) a.push_back(3); // Increase size to 11, a[10]=3 a.back()=4; // a[10]=4; a.pop_back(); // Decrease size by 1 a.front(); // a[0]; a[20]=1; // Crash: not bounds checked a.at(20)=1; // Like a[20] but throws out_of_range() for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p) *p=0; // Set all elements of a to 0 vector<int> b(a.begin(), a.end()); // b is copy of a vector<T> c(n, x); // c[0]..c[n-1] init to x T d[10]; vector<T> e(d, d+10); // e is initialized from d DEQUE (array/stack/queue) deque<T> is like vector<T>, but also supports: a.push_front(x); // Puts x at a[0], shifts elements toward back a.pop_front(); // Removes a[0], shifts toward front UTILITY (Pair) pair<string, int> a("hello", 3); // A 2-element struct a.first; // "hello" a.second; // 3 MAP (associative array) map<string, int> a; // Map from string to int a["hello"]=3; // Add or replace element a["hello"] for (map<string, int>::iterator p=a.begin(); p!=a.end(); ++p) cout << (*p).first << (*p).second; // Prints hello, 3 a.size(); // 1
URL: http://www.sourcepole.com/sources/programming/cpp/cppqref.html