Michael Walz Michael Walz - 7 days ago 6
C++ Question

Accessing elements of a vector of ints by raw pointers

I wonder if the code below is legal.

Basically I have a

std::vector<int>
and I have a legacy function that processes an array of
int
s. As the elements of a
std::vector
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;
vector.push_back(5);
vector.push_back(4);
vector.push_back(3);
LecagyFunction(&vector[0], vector.size());
}


The output as expected is:

5
4
3

Answer

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).