gpt4 book ai didi

c++ - 将数组复制到 std::vector

转载 作者:可可西里 更新时间:2023-11-01 17:09:14 26 4
gpt4 key购买 nike

我在搜索这个主题时发现了很多将数组 [] 转换为 std::vector 的方法,比如使用:

assign(a, a + n)

或者,直接在构造函数中:

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

那些解决了我的问题,但我想知道是否有可能(并且正确)这样做:

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

我想知道这一点,因为我有以下代码:

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;
}

我想做的是:

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;
}

(我删除了 ReadFile 函数的错误处理以简化帖子)。

它正在工作,但我担心它不安全。我相信没关系,因为 vector 使用的内存是连续的,但我从未见过有人以这种方式使用 vector 。

这样使用 vector 是否正确?还有其他更好的选择吗?

最佳答案

是的,std::vector 是安全的 C++ 标准保证元素将存储在连续的内存位置。

C++11 标准:

23.3.6.1 类模板 vector 概述[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().

关于c++ - 将数组复制到 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8871607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com