简体   繁体   中英

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

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

From: http://www.cplusplus.com/reference/vector/vector/

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

From: http://en.cppreference.com/w/cpp/container/vector

The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets on regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array.

So yes, perfectly legal and intended to work in this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM