13.vector and string precedence over dynamically allocated arrays
- The effort to manage memory is reduced by using vectors and string and array.
- Functions such as begin,end,size can be used
- Vector and string have type definitions such as Iterator,value_type.
- Precautions:
- String may use reference counting, and synchronizing in a multithreaded environment may result in poor performance.
14. Use reserve to avoid unnecessary memory allocations
when the vector exceeds the capacity, it causes the object of the original container to be deleted, the destructor is reconstructed, and the original data object is copied and constructed to reduce performance.
15. Note the diversity of string implementations
16. Learn how to pass vector and string data to the old API
- Vector:&v[0],&*v.begin (). V.begin is an error method, the implementation of a vector iterator may be a class, not a pointer.
- The problem of direct use of &v[0]: v Possible space-time, the correct method is as follows:
if (!v.empty ()) { dosomething (&v[0], v.size ()) }
- &s[0] is not necessarily reliable because the data in a string is not necessarily stored in contiguous space, and the internal representation of a string does not necessarily end with a null character.
- S.c_str () will put the first null character inside the string as the null character at the end.
- The pointer generated by S.C_STR () does not necessarily point to the internal representation of the string data, and may return a non-modifiable copy of the internal data.
17. Remove excess capacity using Swap tips
vector<contestant> (constestants). Swap (contestants);
Vector<contestant> (constestants) Create temporary vector
String (s). Swap (s);
Empty container:
Vector<contestant> (). Swap (v)
String (). Swap (s);
18. Avoid using vector<bool>
vector<bool> is a fake container, it does not really store bool, instead in order to save space, it stores the compact representation of bool.
Vector<bool>::operator[] Returns an object that behaves like a reference to a single bit, the so-called proxy object.
Workaround
- Using deque<bool>,deque<bool> memory is not contiguous.
- Inserting and deleting elements is not supported using Bitset. Iterators are not supported.
Effective STL--vector and string