Michael Walz Michael Walz - 1 year ago 61
C++ Question

Accessing elements of a vector of ints by raw pointers

I wonder if the code below is legal.

Basically I have a

and I have a legacy function that processes an array of
s. As the elements of a
are always contiguous the code should always work (it actually works on my implementation), but it still seems bit of a hack to me.

#include <vector>
#include <iostream>

void LecagyFunction(int *data, int length)
for (int i = 0; i < length; i++)
std::cout << data[i] << std::endl;

int main()
std::vector<int> vector;
LecagyFunction(&vector[0], vector.size());

The output as expected is:


Answer Source

This is not a hack, but a 100% legal (and expected) usage of vector. In C++11 your code should be rewritten to take advantage of data() member - which is defined for empty vectors, unlike operator[].

LecagyFunction(vector.data(), vector.size());

And as a side note, above technique will not work for vector<bool>, since the later does not follow properties of regular vectors (a terrible idea, as everybody understands now).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download