4 ms·
Looks like a great list of handy things from the latest versions of C++. I think it might have been a non-standard addition before C++11, but I really like the
by tdicola 12y ago
Looks like a great list of handy things from the latest versions of C++. I think it might have been a non-standard addition before C++11, but I really like the data() function on vector. It just gives you a pointer to the first element of the array of data in the vector. Obviously you can shoot yourself in the foot pretty badly with this, but it's great for interfacing with legacy C code, etc. that expects to get a pointer of things and length.
- GFK_of_xmaspast 12y agoI think you could also have done something like "&(v[0])" to get the same thing.
- DerekL 12y agoWatch out! "&(v[0])" has undefined behavior if v is empty. "v.data()" always works, besides being more readable.
- robotresearcher 12y agoI looked this up: "Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty." Can someone explain the semantics? If the range is valid for an empty vector, what does that say about the validity of tge pointer returned? What value will it have for an empty vector?
- SamReidHughes 12y agoThe pointer will have a non-trap representation, if that is even a thing in C++. I wouldn't even assume it's non-null or not a value shared between different vectors. You can also add or subtract 0 to the pointer, or subtract the pointer from itself.
- DerekL 12y agoOn an empty vector, data() can either return a null pointer, or a pointer to some allocated memory with suitable alignment for that type, but there doesn't have to be a existing object. What is the range [ data(), data() + size() ) anyway? It consists of n + 1 iterators. All but the last one can be dereferenced. You can take one iterator in the range and add or subtract to get another one, as long as you stay in the range. You can subtract iterators to get a signed integer. You can compare iterators with all six operators ==, !=, <, >, <= and >=. For any valid pointer p, null or not, [p, p) is a valid range of length 0. It has one iterator, p, but you can't dereference it. You can add or subtract 0. You can subtract p from itself, getting 0. And you can compare it with itself.
- gurkendoktor 12y agoThis was not guaranteed to work in C++98, but has been fixed in C++03 by stating that std::vector has to use a contiguous block of memory. &v[0] (without the parens) is even shorter :)