c++ - 为什么std::deque的效率这么差?

标签 c++ memory vector stl deque

<分区>

我想用std::deque,但是消耗的内存开销似乎太大了。我做错了什么吗?

#include "windows.h"
#include "psapi.h"

#include <iostream>
#include <vector>
#include <queue>

int main (int, char* [])
{
    PROCESS_MEMORY_COUNTERS pm;
    GetProcessMemoryInfo(GetCurrentProcess(), &pm, sizeof(pm));
    size_t mem1 = pm.WorkingSetSize;

    std::vector<int> v( 10000000 );

    GetProcessMemoryInfo(GetCurrentProcess(), &pm, sizeof(pm));
    size_t mem2 = pm.WorkingSetSize;

    std::deque<int> q( 10000000 );
    GetProcessMemoryInfo(GetCurrentProcess(), &pm, sizeof(pm));
    size_t mem3 = pm.WorkingSetSize;

    std::cout << mem2 - mem1 << std::endl;
    std::cout << mem3 - mem2 << std::endl;

    return 0;
}

输出(在 32 位 Windows 系统上):

40087552
72564736

额外的问题:为什么 mem2 - mem1 不正好是 40000000?

最佳答案

我不认为双端队列是在连续的内存块中分配的。 来自 ( http://www.cplusplus.com/reference/deque/deque/ ):

Both vectors and deques provide a very similar interface and can be used for similar purposes, but internally both work in quite different ways: While vectors use a single array that needs to be occasionally reallocated for growth, the elements of a deque can be scattered in different chunks of storage, with the container keeping the necessary information internally to provide direct access to any of its elements in constant time and with a uniform sequential interface. Therefore, deques are a little more complex internally than vectors, but this allows them to grow more efficiently under certain circumstances, especially with very long sequences, where reallocations become more expensive.

关于c++ - 为什么std::deque的效率这么差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16743199/

相关文章:

c++ - 预分配和 vector

c++ - 二维 vector 图

c++ - 如何实现尺寸有限的 map

c++ - 进程的内存分析

c++ - 在同一端口上发送和接收 UDP

c++ - 引用自身的 typedef

memory - 分配全局内存

c++ - 寻找 vector 的中值

C++ 多次掷骰子

C++ 成员函数指针,boost::signals