从数组到向量的转换 - 与 C 库的接口

Conversion from array to vector - Interface with C library

我需要使用库提供的一些低级 C 函数,将它们包装起来并提供 'more high-level layer' ;在这种情况下,我的问题是获取包含在缓冲区中的数据,并且至少要学习如何正确地做,我想知道您认为在 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;
}

在我提供的 link 中,我无法找到像 C++11 中那样继续 return 'whole' 向量是否是个好主意。

对于向量,是否有比在循环中使用方法 '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 中的新功能)。此用法与我示例中的矢量相同

EDIT2

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

data() 随 C++11 一起提供。在我看来,使用它会使代码更容易理解,显然其他人也是如此,否则就不会被添加。