C++ 如何将向量转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2923272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:30:47  来源:igfitidea点击:

How to convert vector to array

c++arraysvector

提问by ganuke

How do I convert a std::vector<double>to a double array[]?

如何将 a 转换std::vector<double>为 a double array[]

回答by Michael Mrozek

There's a fairly simple trick to do so, since the spec now guaranteesvectors store their elements contiguously:

有一个相当简单的技巧可以做到这一点,因为规范现在保证向量连续存储它们的元素:

std::vector<double> v;
double* a = &v[0];

回答by GManNickG

What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?

做什么的?您需要澄清:您需要一个指向数组或数组第一个元素的指针吗?

If you're calling an API function that expects the former, you can do do_something(&v[0], v.size()), where vis a vector of doubles. The elements of a vector are contiguous.

如果您正在调用需要前者的 API 函数,您可以这样做do_something(&v[0], v.size()),其中vdoubles的向量。向量的元素是连续的。

Otherwise, you just have to copy each element:

否则,您只需复制每个元素:

double arr[100];
std::copy(v.begin(), v.end(), arr);

Ensure not only thar arris big enough, but that arrgets filled up, or you have uninitialized values.

确保不仅 thararr足够大,而且会arr被填满,或者您有未初始化的值。

回答by gzbwb

For C++11, vector.data()will do the trick.

对于C++11vector.data()可以解决问题。

回答by user168715

vector<double> thevector;
//...
double *thearray = &thevector[0];

This is guaranteed to work by the standard, however there are some caveats: in particular take care to only use thearraywhile thevectoris in scope.

这是保证该标准的工作,但也有一些注意事项:特别注意只使用thearray,而thevector在范围内。

回答by user168715

Vectors effectively are arrays under the skin. If you have a function:

向量实际上是皮肤下的数组。如果你有一个功能:

void f( double a[]);

you can call it like this:

你可以这样称呼它:

vector <double> v;
v.push_back( 1.23 )
f( &v[0] );

You should not ever need to convert a vector into an actual array instance.

您永远不需要将向量转换为实际的数组实例。

回答by Jayhello

As to std::vector<int> vec, vec to get int*, you can use two method:

至于std::vector<int> vec, vec 要 get int*,您可以使用两种方法:

  1. int* arr = &vec[0];

  2. int* arr = vec.data();

  1. int* arr = &vec[0];

  2. int* arr = vec.data();

If you want to convert any type Tvector to T* array, just replace the above intto T.

如果要将任何类型的T向量转换为T* array,只需将上面的替换intT

I will show you why does the above two works, for good understanding?

我将向您展示为什么上述两个有效,以便更好地理解?

std::vectoris a dynamic array essentially.

std::vector本质上是一个动态数组。

Main data member as below:

主要数据成员如下:

template <class T, class Alloc = allocator<T>>
class vector{
    public:
        typedef T          value_type;
        typedef T*         iterator;
        typedef T*         pointer;
        //.......
    private:
        pointer start_;
        pointer finish_;
        pointer end_of_storage_;

    public:
        vector():start_(0), finish_(0), end_of_storage_(0){}
    //......
}

The range (start_, end_of_storage_)is all the array memory the vector allocate;

range (start_, end_of_storage_)是所有阵列存储器中的向量分配;

The range(start_, finish_)is all the array memory the vector used;

range(start_, finish_)是所有的阵列中的存储器使用的载体;

The range(finish_, end_of_storage_)is the backup array memory.

range(finish_, end_of_storage_)是备份阵列存储器。

For example, as to a vector vec. which has {9, 9, 1, 2, 3, 4} is pointer may like the below.

例如,对于向量 vec。其中有 {9, 9, 1, 2, 3, 4} 的指针可能如下所示。

enter image description here

在此处输入图片说明

So &vec[0]= start_ (address.) (start_ is equivalent to int* array head)

So &vec[0]= start_ (address.) (start_ 相当于 int* 数组头)

In c++11the data()member function just return start_

c++11data()成员函数只返回start_

pointer data()
{ 
     return start_; //(equivalent to `value_type*`, array head)
}

回答by rashedcs

We can do this using data() method. C++11 provides this method.

我们可以使用 data() 方法来做到这一点。C++11 提供了这种方法。

Code Snippet

代码片段

#include<bits/stdc++.h>
using namespace std;


int main()
{
  ios::sync_with_stdio(false);

  vector<int>v = {7, 8, 9, 10, 11};
  int *arr = v.data();

  for(int i=0; i<v.size(); i++)
  {
    cout<<arr[i]<<" ";
  }

  return 0;
}

回答by Toby

std::vector<double> vec;
double* arr = vec.data();

回答by Toby

If you have a function, then you probably need this:foo(&array[0], array.size());. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.

如果你有一个功能,那么你可能需要这样的:foo(&array[0], array.size());。如果您设法进入需要数组的情况,那么您需要重构,向量基本上是扩展数组,您应该始终使用它们。

回答by Sakthi Vignesh

You can do some what like this

你可以做一些这样的

vector <int> id;
vector <double> v;

if(id.size() > 0)
{
    for(int i = 0; i < id.size(); i++)
    {
        for(int j = 0; j < id.size(); j++)
        {
            double x = v[i][j];
            cout << x << endl;
        }
    }
}