C ++: get start address of std :: vector?

It is sometimes useful to use the starting address std::vector and temporarily treat this address as the address of a regularly allocated buffer.
For example, replace this:

  char* buf = new char[size]; fillTheBuffer(buf, size); useTheBuffer(buf, size); delete[] buf; 

With the help of this:

  vector<char> buf(size); fillTheBuffer(&buf[0], size); useTheBuffer(&buf[0], size); 

The advantage of this, of course, is that the buffer is freed automatically, and I don't need to worry about delete[] .

The problem with this is related to size == 0. In this case, the first version works fine. An empty buffer is "allocated", and subsequent functions do nothing by size, they get size == 0.
The second version, however, does not work if size == 0, since a call to buf[0] can rightfully contain the statement that 0 < size .

So, is there an alternative to idiom &buf[0] that returns the address of the start of the vector, even if the vector is empty?

I also considered using buf.begin() , but according to the standard it is not even guaranteed to return a pointer.

+6
c ++ pointers vector
source share
4 answers

I think you just need to check.

Perhaps a utility function:

 template <class T, class Alloc> T* data(std::vector<T, Alloc>& vec) { return vec.empty() ? 0 : &vec[0]; } template <class T, class Alloc> const T* data(const std::vector<T, Alloc>& vec) { return vec.empty() ? 0 : &vec[0]; } 
+8
source share

There is no function for this, even if std::basic_string has data() , which does exactly what you need.

Will you need to use something like buf.size()?&buf[0]:0;

+1
source share

I think you should be safe anyway. I believe that the differences between vector :: operator [int] and vector :: at (int) are that overloading the operator [] does not specifically perform bounds checking. Using buf [0] should be free from statements!

+1
source share

If you can change fillTheBuffer and useTheBuffer to take a couple of iterators, then you will solve the problem the same way the standard library solved it.

+1
source share

All Articles