Thank you: http://topic.csdn.net/t/20050429/20/3976956.html
Thank you: http://yzyanchao.blogbus.com/logs/47796444.html
But over there is reproduced from the "effective STL".
Std::vector is very convenient, but sometimes called the function of the parameters specified is an array, need to convert the vector into an array, in addition to open a space, the vector of an item copy past costs too much, the following method can be used.
Given a
Vector<int> v;
Expression V[0] produces a reference to the first element in the vector, so &v[0] is a pointer to that first element. The elements in the vector are limited by the C + + standard to stored in contiguous memory, like an array, so if we want to pass V to such a C-style API:
void dosomething (const int* pints, size_t numints);
We can do this:
DoSomething (&v[0], v.size ());
Well, maybe. It's possible. The only problem is that if V is empty. If so, V.size () is 0, and &v[0] tries to produce a pointer to something that does not exist at all. It's not a good thing. The result is undefined. A more secure approach is this:
if (!v.empty ()) {
DoSomething (&v[0], v.size ());
}
If you are in a bad environment, you may encounter some dabbler people who will tell you that you can use V.begin () instead of &v[0], because (these nasty guys will tell you) begin returns an iterator to the inside of the vector, and for vectors, Its iterator is actually a pointer. That's often true, but as clause 50 says, not always, you shouldn't rely on it. The return type of begin is iterator, not a pointer, and you should never use begin when you need a pointer to the data inside the vector. If you decide to type V.begin () for some reason, you should type &*v.begin (), as this will produce the same pointer as &v[0], which gives you more typing opportunities and makes other people feel more obscure about your code. Frankly, if you're dealing with someone who tells you to use V.begin () instead of &v[0, you should reconsider your social circle. (In VC6, if you use V.begin () instead of &v[0], the compiler won't say anything, but if you do so in VC7 and g++, it will throw a compilation error)
Go Vector to array in STL (actually pointer to array)