码迷,mamicode.com
首页 > 其他好文 > 详细

其他容器

时间:2017-11-04 00:08:15      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:either   cat   empty   hang   sign   scalar   rand   defaults   exception   

<deque>

A deque (double ended queue) is just like a vector, but optimized for adding and removing elements at either end in O(1) time. It lacks reserve() and capacity() and adds
  v.push_front(x)        // v.insert(v.begin(), x)
  v.pop_front()          // v.erase(v.begin())
<list>

A list is like a deque but optimized for insert and erase at any point at the cost of random access. It lacks [] (indexing), and its iterators are bidirectional, not supporting [], +, -, <, >, <=, or >=. list adds
  v.splice(d, v2, b);  // Move *b from list v2 to in front of d in v
  v.splice(d, v2);     // Move all elements of list v2 to in front of d in v
  v.splice(d, v2, b, e); // Move [b,e) in v2 to in front of d at v
  v.remove(x);         // Remove all elements equal to x
  v.remove_if(f);      // Remove elements x where f(x) is true
  v.sort();            // Sort list
  v.sort(f);           // Sort list using function bool f(x,y) instead of x < y
  v.merge(v2);         // Merge sorted list v2 into sorted list v
  v.merge(v2, f);      // Merge using f(x,y) instead of x < y to sort v
  v.unique();          // Remove duplicates from sorted list
  v.unique(f);         // Use f(x,y) instead of x == y
  v.reverse();         // Reverse order of elements
Iterators can only be moved one element at a time using ++ or --, and compared using == or !=.
  char* cp="ABCDE";
  list<char> v(cp, cp+5);  // v.size() is 5
  for (list<char>::const_iterator p=v.begin(); p!=v.end(); ++p)  // Print ABCDE
    cout << *p;
<map>

A map<K,V> m is a set of key-value pairs with unique, sorted keys of type K and values of type V. m[k] efficiently (O(log n) time) returns the value associated with k (as an lvalue), or creates a default value (0 if V is numeric) if k is used for the first time. A map iterator points to a pair<const K, V>, which has members first of type const K and second of type V.
  pair<K,V> x(k,v);    // Create a pair x containing copies of k and v
  x.first              // k
  x.second             // v
  x=make_pair(k,v)     // x.first=k; x.second=v;

  map<K,V> m;          // map sorted by < on K
  map<K,V,f>()         // map sorted by f(x,y) instead of x<y on K
  m[k]=v;              // Associate v (type V) with unique key k of type K
  m[k]                 // Retrieve v, or associate V() with k if new
  m.size()             // Number of unique keys
  m.empty()            // true if m.size() == 0
  map<K,V>::iterator   // bidirectional, points to a pair<const K, V>
  map<K,V>::const_iterator   // points to a pair<const K, const V>
  m.begin()            // Points to first pair (lowest k)
  m.end()              // Points 1 past last pair
  m.find(k)            // Points to pair containing k or m.end() if not found
  m.erase(k)           // Remove key K and its associated value
  m.erase(b)           // Remove pair pointed to by iterator b
  m.erase(b, e)        // Remove sequence [b, e)
  m.clear()            // Make empty: m.erase(m.begin(), m.end())
  m==m2                // Compare maps, also !=, <, <=, >, >=
We use m.find(k) rather than m[k] when we wish to look up k without increasing the size of m if k is not found.
  // Read words, print an alphabetical index of words with their counts
  string s;
  map<string, int> m;
  while (cin >> s)
    ++m[s];
  for (map<string, int>::const_iterator p=m.begin(); p!=m.end(); ++p)
    cout << p->first << " " << p->second << endl;
A multimap is a map that allows duplicate keys. It support all map operations except []. Elements are added by inserting a pair<K,V> and retrieved by m.equal_range(k) which returns a pair of iterators defining the sequence of pairs matching k.
  multimap<K,V,f> m;   // f defaults to < on K
  m.insert(make_pair(k,v))  // Insert a pair
  pair<multimap<K,V,f>::iterator, multimap<K,V,f>::iterator> p
    = m.equal_range(k) // Sequence with key k is [p->first, p->second)
f (when used as a template argument) is a functoid (or function object), a class that looks like a function by overloading (). For example:

  template <class T> class GreaterThan {
  public:
    bool operator()(const T& a, const T& b) const {return b < a;}
  };

  map<string, int, GreaterThan<T> > m;  // keys sorted in reverse order
Some function objects can be found in <functional>.
<set>

A set<K> and multiset<K> are like a map and multimap, but without values. Iterators point to a K rather than a pair. There is no [] operator.
  set<K> m;            // Elements are sorted by < on K
  m.insert(k)          // Add an element
  m.erase(k)           // Remove an element
  m.find(k)!=m.end()   // Test if k is in m
<queue>

A queue is a container in which elements are inserted at the back and removed from the front. This could also be done with a deque or list, so no new capabilities are provided. A queue does not support iterators or indexing.
  queue<T> q;          // Queue of type T
  q.size()             // Number of items in q
  q.empty()            // true if q.size() == 0
  q.push(x)            // Put x in the back
  x=q.back()           // The item last pushed, may be assigned to
  x=q.front()          // The next item to pop, may be assigned to
  q.pop()              // Remove the front item
A priority_queue is more useful. It sorts the items as they are pushed so that the largest is on top and removed first.
  priority_queue<T> q; // Element type is T
  priority_queue<T, vector<T>, f> q;  // Use functoid f(x,y) instead of x < y to sort
  q.size(), q.empty()  // As before
  q.push(x)            // Insert x
  x=q.top()            // Largest item in q, cannot be assigned to
  q.pop()              // Remove top item
<stack>

Items are popped from the top of a stack in the reverse order in which they were pushed. It does not provide any new functionality beyond a vector, deque, or list, and does not support iterators or indexing.
  stack<T> s;          // Stack with elements of type T
  s.size(), s.empty()  // As with queue
  s.push(x);           // Put x on top
  x=s.top();           // Last item pushed, may be assigned to
  s.pop();             // Remove the top item
<bitset>

A bitset<N> is like a vector<bool> with fixed size N, but without iterators, and supporting logical operators like an N-bit int. Its elements have the values 0 or 1. It is implemented efficiently, with 8 elements per byte.
  bitset<N> b;         // N-bit bitset, N must be a compile time constant
  bitset<N> b=x;       // Initialize b[0]..b[31] from bits of long x
  b[i]                 // i‘th bit, 0 <= i < N or throw out_of_range()
  b.size()             // N, cannot be changed
  b.set(i)             // b[i] = 1
  b.reset(i)           // b[i] = 0
  b.flip(i)            // b[i] = 1 - b[i]
  b.test(i)            // true if b[i] == 1
  b.set()              // Set all bits, also b.reset(), b.flip()
  b & b2               // Bitwise AND, also | ^ ~ << >> &= |= ^= <<= >>= == !=
  b.count()            // Number of bits set to 1
  b.any()              // true if b.count() > 0
  b.none()             // true if b.count() == 0
  cin >> b             // Read bits as ‘0‘ and ‘1‘ e.g. "10101"
  cout << b            // Write bits as ‘0‘ and ‘1‘
  bitset<N> b(s);      // Initialize from string s of ‘0‘ and ‘1‘ or throw invalid_argument()
  s=b.template to_string<char>()  // Convert to string
  x=b.to_ulong()       // Convert to unsigned long, throw overflow_error() if bits > 31 set
<valarray>

A valarray is like a fixed sized array or vector that supports arithmetic operations on all the elements at once. For instance, if x and y are valarrays of the same size, then x+y is a valarray containing the sums of the corresponding elements. Likewise, y=sqrt(x) assigns y[i]=sqrt(x[i]) to each element of y. In mixed type expressions, a scalar (element of type T) is promoted to a valarray of the same size by duplicating it, e.g. x+1 adds 1 to all elements of x.
  valarray<T> v(n);    // n elements of type T, initially T() or 0
  valarray<T> v(x, n); // n copies of x (note arguments are backwards)
  valarray<T> v(a, n); // Initialize from array a[0]..a[n-1]
  valarray<T> v;       // size is 0
  v.size()             // Number of elements, n
  v[i]                 // i‘th element, 0 <= i < n, not checked
  v+=x, v+=v           // Add x or v[i] to all v[i], also = -= *= /= %= ^= &= |= <<= >>=
  v+v, v+x, x+v        // Also - * / % ^ & | << >> and unary + - ~ !
  sqrt(v)              // Also all functions in cmath
  x=v.sum()            // Sum of all elements
  v.shift(n)           // Move all v[i] to v[i+n], shift in 0
  v.cshift(n)          // Move v[i] to v[(i+n) % v.size()]
  v.resize(n)          // Change size to n, but reset all elements to 0
  v.resize(n, x)       // Change size to n, set all elements to x
<complex>

A complex supports complex arithmetic. It has real and imaginary parts of type T. Mixed type expressions promote real to complex (e.g. double to complex<double> and lower precision to higher precision (e.g. complex<int> to complex<double>).
  complex<T> x;        // (0,0), T is a numeric type
  complex<T> x=r;      // (r,0), convert real r to complex
  complex<T> x(r, i);  // (r,i)
  x=polar<T>(rho, theta); // Polar notation: radius, angle in radians
  x.real()             // r
  x.imag()             // i
  abs(x)               // rho = sqrt(r*r+i*i)
  arg(x)               // tan(theta) = i/r
  norm(x)              // abs(x)*abs(x)
  conj(x)              // (r,-i)
  x+y                  // Also - * / == != = += -= *= /= and unary + -
  sin(x)               // Also sinh, sqrt, tan, tanh, cos, cosh, exp, log, log10, pow(x,y)
  cout << x            // Prints in format "(r,i)"
  cin >> x             // Expects "r", "(r)", or "(r,i)"
<stdexcept>, <exception>

The standard library provides a hierarchy of exception types. Not all of them are used by the library, but any may be thrown.

  Type                   Header                   Thrown by
  exception              stdexcept, exception
    logic_error          stdexcept
      length_error       stdexcept
      domain_error       stdexcept
      out_of_range       stdexcept                .at(i) (vector/string/deque index out of bounds)
      invalid_argument   stdexcept, bitset        bitset("xxx") (not ‘0‘ or ‘1‘)
    runtime_error        stdexcept
      range_error        stdexcept    
      overflow_error     stdexcept
      underflow_error    stdexcept
    bad_alloc            new                      new, new[] (out of memory)
    bad_cast             typeinfo                 dynamic_cast<T&> (can‘t convert to derived)
    bad_typeid           typeinfo                 typeid(*p) when p==0
    bad_exception        exception
    ios_base::failure    ios, iostream, fstream   istream::clear(), ostream::clear()
Catching a base class catches all derived classes, thus catch(exception e) catches all of the above types. However, C++ allows throwing exceptions not derived from exception, so this may not catch everything. All exceptions provide the following interface:
  throw exception(msg)   // Throw exception with char* or string msg
  throw exception();     // Default msg
  catch(exception e) {e.what();}  // msg as a char*
New exceptions may be derived from existing types to maintain this interface (see inheritance).

  class MyError: public exception {
  public:
    MyError(const string& msg=""): exception(msg) {}
  }

 

其他容器

标签:either   cat   empty   hang   sign   scalar   rand   defaults   exception   

原文地址:http://www.cnblogs.com/enyala/p/7780527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!