简体   繁体   English

通过原始指针访问int向量的元素

[英]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. 基本上,我有一个std::vector<int>并且我有一个处理int数组的旧函数。 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. 由于std::vector的元素始终是连续的,因此代码应始终有效(它实际上适用于我的实现),但对我来说似乎仍然有些不足。

#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. 这不是黑客,而是对Vector的100%合法(和预期)使用。 In C++11 your code should be rewritten to take advantage of data() member - which is defined for empty vectors, unlike operator[] . 在C ++ 11中,应重写代码以利用data()成员-它是为空向量定义的,与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). 另外,上述技术不适用于vector<bool> ,因为后者不能遵循常规矢量的属性(这是一个可怕的主意,众所周知,现在大家都可以理解)。

From: http://www.cplusplus.com/reference/vector/vector/ 来自: 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 来自: 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. 是的,完全合法,并打算以此方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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