gpt4 book ai didi

arrays - 从数组到向量的转换 - 与 C 库的接口(interface)

转载 作者:行者123 更新时间:2023-12-05 01:10:01 25 4
gpt4 key购买 nike

我需要使用库提供的一些低级 C 函数来包装它们并提供“更高级的层”;在这种情况下,我的问题是获取缓冲区中包含的数据,并且至少学习如何正确执行它,我想知道您认为在 C++03 和 C+ 中应该做什么+11。

仅供引用,我在 Red Hat Linux 下工作,使用 GCC 4.4.7(所以并不真正符合 C++11, https://gcc.gnu.org/gcc-4.4/cxx0x_status.html )。

这是我正在尝试做的事情的片段:

#define DATA_BLOCKS 4096 // the numbers of 16-bit words within the buffer

std::vector<uint16_t> myClass::getData()
{
uint16_t buffer[DATA_BLOCKS];
getDataBuf(fd, dma, am, buffer[]); //C-function provided by the library

// pushing buffer content into vector
std::vector <uint16_t> myData;
for(int i=0; i<DATA_BLOCKS; i++)
myData.pushback(buffer[i]);
return myData;
}

在我提供的链接中,我无法找到像 C++11 中那样返回“整个”向量是否是个好主意。

对于向量,是否有比在循环中使用“pushback()”方法更好的方法来填充“myData”?

最佳答案

你可以这么做,而且很安全:

std::vector<uint16_t> myClass::getData()
{
std::vector <uint16_t> myData(DATA_BLOCKS);
getDataBuf(fd, dma, am, myData.data()); //C-function provided by the library
// Old interface, before c++11 : getDataBuf(fd, dma, am, &myData[0]);

return myData;
}

或者如果你想填充给定的向量:

void myClass::getData(std::vector<uint16_t> &myData)
{
myData.resize(DATA_BLOCKS);
getDataBuf(fd, dma, am, myData.data()); //C-function provided by the library
// Old interface, before c++11 : getDataBuf(fd, dma, am, &myData[0]);
}

就我个人而言,我对返回向量(可能会使用移动语义)或填充给定向量没有意见

编辑

您可以使用 std::array<std::uint8_t, DATA_BLOCKS> 而不是使用向量,因为您确切地知道大小。容器(C++11 中的新功能)。这种用法与我的示例中的向量相同

编辑2

向量和数组使用连续的存储位置( reference for vector class ),因此如果您从第一个元素获取地址,则可以通过递增地址来访问第二个元素。 Vector 唯一的危险点是确保已分配内存。在这两种情况下,我都设法拥有足够的分配内存:在第一个示例中,向量使用填充构造函数进行实例化,在第二个示例中,我将向量大小调整为相应的大小。 “Effective STL - 50 Specific Ways to Improve Your Use of the Standard Template Library”[Scott Meyers] 一书中描述了此方法。对于数组来说,没问题(当然前提是声明数组有足够的内存)。

关于arrays - 从数组到向量的转换 - 与 C 库的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35605447/

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