简体   繁体   English

将数组复制到std :: vector

[英]Copying an array into a std::vector

I was searching about this topic and I found many ways to convert an array[] to an std::vector, like using: 我在搜索这个主题时,发现了许多方法可以将array []转换为std :: vector,例如使用:

assign(a, a + n)

or, direct in the constructor: 或者,直接在构造函数中:

std::vector<unsigned char> v ( a, a + n );

Those solve my problem, but I am wondering if it is possible (and correct) to do: 那些解决了我的问题,但是我想知道是否有可能(并且正确)做:

myvet.resize( 10 );
memcpy( &myvet[0], buffer, 10 );

I am wondering this because I have the following code: 我想知道这是因为我有以下代码:

IDiskAccess::ERetRead nsDisks::DiskAccess::Read( std::vector< uint8_t >& bufferRead, int32_t totalToRead )
{
    uint8_t* data = new uint8_t[totalToRead];
    DWORD totalRead;
    ReadFile( mhFile, data, totalToRead, &totalRead, NULL );
    bufferRead.resize( totalRead );
    bufferRead.assign( data, data + totalRead );
    delete[] data;

    return IDiskAccess::READ_OK;
}

And I would like to do: 我想做的是:

IDiskAccess::ERetRead nsDisks::DiskAccess::Read( std::vector< uint8_t >& bufferRead, int32_t totalToRead )
{
    bufferRead.resize( totalToRead );
    DWORD totalRead;
    ReadFile( mhFile, &bufferRead[0], totalToRead, &totalRead, NULL );
    bufferRead.resize( totalRead );

    return IDiskAccess::READ_OK;
}

(I have removed the error treatment of the ReadFile function to simplify the post). (我已删除了ReadFile函数的错误处理,以简化帖子)。

It is working, but I am affraid that it is not safe. 它正在工作,但是我很不安全。 I believe it is ok, as the memory used by the vector is continuous, but I've never seen someone using vectors this way. 我相信还可以,因为矢量使用的内存是连续的,但是我从未见过有人以这种方式使用矢量。

Is it correct to use vectors like this? 使用这样的向量是否正确? Is there any other better option? 还有其他更好的选择吗?

Yes it is safe with std::vector C++ standard guarantees that the elements will be stored at contiguous memory locations. 是的,使用std::vector C ++标准是安全的,可以确保将元素存储在连续的内存位置。

C++11 Standard: C ++ 11标准:

23.3.6.1 Class templatevector overview [vector.overview] 23.3.6.1类templatevector概述[vector.overview]

A vector is a sequence container that supports random access iterators. 向量是支持随机访问迭代器的序列容器。 In addition,itsupports(amortized) constant time insert and erase operations at the end; 另外,它支持(摊销)最后的固定时间插入和擦除操作; insert and erase in the middle take linear time. 在中间插入和擦除需要线性时间。 Storage management is handled automatically, though hints can be given to improve efficiency. 存储管理是自动处理的,尽管可以提供一些提示以提高效率。 The elements of a vector are stored contiguously , meaning that ifv is avector whereT is some type other than bool, then it obeys the identity&v[n] == &v[0] + n for all0 <= n < v.size(). 向量的元素是连续存储的 ,这意味着如果v是一个向量 ,其中T是非bool的某种类型,则对于all0 <= n <v.size(),它遵循恒等式&v [n] ==&v [0] + n。

Yes, it is fine to do that. 是的,这样做很好。 You might want to do myvet.data() instead of &myvet[0] if it looks better to you, but they both have the same effect. 如果看起来更好,则可能要使用myvet.data()而不是&myvet[0] ,但它们的作用相同。 Also, if circumstances permit, you can use std::copy instead and have more type-safety and all those other C++ standard library goodies. 另外,如果情况允许,您可以改用std::copy并具有更多的类型安全性以及所有其他C ++标准库优点。

The storage that a vector uses is guaranteed to be contiguous, which makes it suitable for use as a buffer or with other functions. vector使用的存储保证是连续的,这使其适合用作缓冲区或其他功能。

Make sure that you don't modify the vector (such as calling push_back on it, etc) while you are using the pointer you get from data or &v[0] because the vector could resize its buffer on one of those operations and invalidate the pointer. 确保在使用从data&v[0]获得的指针时,不要修改vector (例如,在其上调用push_back等),因为vector可能会在这些操作之一上调整其缓冲区大小并使该参数无效指针。

That approach is correct, it only depends on the vector having contiguous memory which is required by the standard. 该方法是正确的,仅取决于标准要求的具有连续内存的向量。 I believe that in c++11 there is a new data() member function in vectors that returns a pointer to the buffer. 我相信在c ++ 11中,向量中有一个新的data()成员函数,该函数返回指向缓冲区的指针。 Also note that in the case of `memcpy you need to pass the size in bytes not e size of the array 还要注意,在`memcpy的情况下,您需要传递字节大小而不是数组大小

在存储vector是保证连续分配和unsigned char是POD,因此这是完全安全的memcpy到它(假设你没有拷贝,当然比你更已分配)。

Do your resize first , and it should work fine. 首先进行大小调整,它应该可以正常工作。

vector<int> v;
v.resize(100);
memcpy(&v[0], someArrayOfSize100, 100 * sizeof(int));

Yes, the solution using memcpy is correct; 是的,使用memcpy的解决方案是正确的; the buffer held by a vector is contiguous. vector保持的缓冲区是连续的。 But it's not quite type-safe, so prefer assign or std::copy . 但这不是很安全的类型,所以更喜欢assignstd::copy

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

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