Title
Suggestion for new member functions in standard containers
Status
cd1
Section
[vector][map]
Submitter
Thorsten Ottosen

Created on 2004-05-12.00:00:00 last changed 149 months ago

Messages

Date: 2010-10-21.18:28:33

Rationale:

Neither of these additions provides any new functionality but the LWG agreed that they are convenient, especially for novices. The exception type chosen for at, std::out_of_range, was chosen to match vector::at.

Date: 2010-10-21.18:28:33

Proposed resolution:

In [vector], add the following to the vector synopsis after "element access" and before "modifiers":

  // [lib.vector.data] data access
  pointer       data();
  const_pointer data() const;

Add a new subsection of [vector]:

23.2.4.x vector data access

   pointer       data();
   const_pointer data() const;

Returns: A pointer such that [data(), data() + size()) is a valid range. For a non-empty vector, data() == &front().

Complexity: Constant time.

Throws: Nothing.

In [map], add the following to the map synopsis immediately after the line for operator[]:

  T&       at(const key_type& x);
  const T& at(const key_type& x) const;

Add the following to [map.access]:

  T&       at(const key_type& x);
  const T& at(const key_type& x) const;

Returns: A reference to the element whose key is equivalent to x, if such an element is present in the map.

Throws: out_of_range if no such element is present.

Date: 2004-05-12.00:00:00

To add slightly more convenience to vector<T> and map<Key,T> we should consider to add

  1. add vector<T>::data() member (const and non-const version) semantics: if( empty() ) return 0; else return buffer_;
  2. add map<Key,T>::at( const Key& k ) member (const and non-const version) semantics: iterator i = find( k ); if( i != end() ) return *i; else throw range_error();

Rationale:

  • To obtain a pointer to the vector's buffer, one must use either operator[]() (which can give undefined behavior for empty vectors) or at() (which will then throw if the vector is empty).
  • tr1::array<T,sz> already has a data() member
  • e cannot use operator[]() when T is not DefaultDonstructible
  • Neither when the map is const.
  • when we want to make sure we don't add an element accidently
  • when it should be considered an error if a key is not in the map
History
Date User Action Args
2010-10-21 18:28:33adminsetmessages: + msg2735
2010-10-21 18:28:33adminsetmessages: + msg2734
2004-05-12 00:00:00admincreate