Posted By

jimfred on 11/19/08


Tagged

template array map Vector deque


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

jpcamara
khouser


C++ template quick reference


 / Published in: C++
 

URL: http://www.sourcepole.com/sources/programming/cpp/cppqref.html

  1. VECTOR (Variable sized array/stack with built in memory allocation)
  2.  
  3. vector<int> a(10); // a[0]..a[9] are int (default size is 0)
  4. a.size(); // Number of elements (10)
  5. a.push_back(3); // Increase size to 11, a[10]=3
  6. a.back()=4; // a[10]=4;
  7. a.pop_back(); // Decrease size by 1
  8. a.front(); // a[0];
  9. a[20]=1; // Crash: not bounds checked
  10. a.at(20)=1; // Like a[20] but throws out_of_range()
  11. for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p)
  12. *p=0; // Set all elements of a to 0
  13. vector<int> b(a.begin(), a.end()); // b is copy of a
  14. vector<T> c(n, x); // c[0]..c[n-1] init to x
  15. T d[10]; vector<T> e(d, d+10); // e is initialized from d
  16.  
  17. DEQUE (array/stack/queue)
  18. deque<T> is like vector<T>, but also supports:
  19.  
  20. a.push_front(x); // Puts x at a[0], shifts elements toward back
  21. a.pop_front(); // Removes a[0], shifts toward front
  22.  
  23. UTILITY (Pair)
  24.  
  25. pair<string, int> a("hello", 3); // A 2-element struct
  26. a.first; // "hello"
  27. a.second; // 3
  28.  
  29. MAP (associative array)
  30.  
  31. map<string, int> a; // Map from string to int
  32. a["hello"]=3; // Add or replace element a["hello"]
  33. for (map<string, int>::iterator p=a.begin(); p!=a.end(); ++p)
  34. cout << (*p).first << (*p).second; // Prints hello, 3
  35. a.size(); // 1

Report this snippet  

You need to login to post a comment.