Why is std::vector contiguous?

后端 未结 5 2120
遥遥无期
遥遥无期 2021-01-03 20:47

Besides the fact that the standard defines it to be contiguous, why is std::vector contiguous?

If it runs out of space, it needs to reallocate a new block and copy t

5条回答
  •  Happy的楠姐
    2021-01-03 21:24

    By making std::vector contiguous, it can be treated much like an array. However, it's also resizable. Its size is definable at runtime, rather than compile time. Also, a vector can be used to allocate memory for functions that require a buffer. The advantage of this is the memory will be free'd by the vector when it goes out of scope. For example, when using ReadFile a vector can be used to create a buffer.:

    unsigned int bytesRead = 0;
    std::vector buffer(fileSize);
    // open file, etc.
    ReadFile(hFileIn, buffer.data(), buffer.size(), &bytesRead, nullptr);
    

    Note that data is new in C++11. In older code you will probably seen an equivalent &(buffer.at(0)) or &(buffer[0]) which returns the address of the first element.

    A std::deque would be a better fit for what you're describing.

提交回复
热议问题