Click to See Complete Forum and Search --> : Getting an array from a std::vector's contents


Bob Davis
June 19th, 2002, 03:09 PM
I'm writing a program now in which I need to keep an array of HANDLE objects, to pass to a Win32 API function that I'm using. The HANDLE's refer to threads that I'm creating in a for loop. Having paid much attention to the comments of posters here, I'm placing each one into a std::vector container as I create it. Is there any good way to get the contents of a vector as an array?

If I remember my introductory C++ class correctly, we talked about <vector>, and I think it held the data internally in an array of increasing size as was needed. If this is correct, could I use vector::front() to get the first element, and vector::size() to get the size of the "array?" It sounds like it will work for me, but I'm not sure that this is good practice. Is this a case where I should just dynamically allocate an array instead of using std::vector? Thanks for any input on this.

Graham
June 19th, 2002, 03:22 PM
If you want to pass the vector as an array, just take the address of the 0'th element:

#incude <vector>

void legacyfunction(int arr[], int num);

int main()
{
std::vector<int> vi;

// fill vi

legacyfunction(&vi[0], vi.size());
}

Paul McKenzie
June 19th, 2002, 04:30 PM
Originally posted by Bob Davis
...If I remember my introductory C++ class correctly, we talked about <vector>, and I think it held the data internally in an array of increasing size as was needed. If this is correct, could I use vector::front() to get the first element, and vector::size() to get the size of the "array?" It sounds like it will work for me, but I'm not sure that this is good practice. Is this a case where I should just dynamically allocate an array instead of using std::vector? Thanks for any input on this. The vector is guaranteed to store its data in contiguous memory. The solution that Graham gave is correct. You can even pass a vector to a function that modifies the array, given that the vector has enough room already allocated.

To read up more on this, you can get Scott Meyers "Effective STL". There is a whole section on this topic alone (passing vectors to legacy functions).

Regards,

Paul McKenzie

Zeeshan
June 19th, 2002, 11:24 PM
Just want to add one more thing, which i notice a lots of ppls do wrong when using vector first time.

Be sure to check vector is not empty before using index operator.


vector<int> a;

// do something

if (!a.empty())
fun(&a[0], a.size());


Personaly i like to use at() function to get the value, because this function throw exception when index is out of range and index operator doesnt.


try
{
fun(&a.at(0), a.size());
}
catch(exception& e)
{
cout << e.what() << endl;
}


Hope it helps.

Graham
June 20th, 2002, 09:05 AM
Good point and worth making.

Not sure I agree about using at(), but that's just an opinion - if it works for you, and it's maintainable, what the hey?