简体   繁体   English

std :: deque <std::string> 有效地计算内存中的大小

[英]std::deque<std::string> count size in memory efficiently

I've been working on a basic log file class which truncates by 20% once it reaches as set size limit (eg 10Mb), I decided to store the file into a stringstream buffer and then store it log by log into a std::deque (used a std::deque instead of std::vector so I could easily pop from the top of the structure and not have to sort etc) the loading and storing is shown below: 我一直在研究一个基本的日志文件类,一旦达到设置的大小限制(例如10Mb),它将被截断20%,我决定将文件存储到stringstream缓冲区中,然后逐个日志地将其存储到std ::中: deque(使用std :: deque代替std :: vector,因此我可以轻松地从结构顶部弹出,而不必进行排序等)加载和存储如下所示:

    std::deque<std::string> vLogs;
    std::stringstream ssBuffer;
    std::string sLog;

    ssBuffer << in.rdbuf();
    in.close();

    while(getline(ssBuffer,sLog))
        vLogs.push_back(sLog);

the log file is designed so it truncates when it reaches a set size (eg 10Mb) so what I really want to do is check how large the std::string's are within vLogs - which I can do in the following way: 日志文件的设计使其在达到设定大小(例如10Mb)时会被截断,因此我真正想做的是检查vLogs中std :: string的大小-我可以通过以下方式进行操作:

    int nSize = 0;
    for(auto it = vLogs.begin(); it != vLogs.end(); ++it)
        nSize += it->size();

    do{
        nSize -= vLogs.front().size();
        vLogs.pop_front();
    }while(nSize > (MAX_SIZE * 0.8));

The question I'm asking is whether there is a more efficient way on getting the actual size taken up by the std::strings instead of doing it manually like I am now. 我要问的问题是,是否有一种更有效的方法来获取std :: strings占用的实际大小,而不是像现在这样手动进行操作。

thanks - any more information just ask. 谢谢-任何更多的信息,只是问。

自己做一个具有std::deque内存大小计数器的类,并监视插入(例如,增加插入到计数器中的内存大小)和提取(例如,减去从计数器中提取的内存大小)。

Right now, you're adding up the sizes many many times. 现在,您要多次累加大小。 This isn't necessary. 没必要

You can either 你可以

  • add up all the sizes, then adjust the total down each time you remove an item 将所有尺寸相加,然后在每次删除项目时向下调整总计

or 要么

  • add up the sizes in reverse starting from the tail, and once you reach the threshold, remove all items from that point to the beginning 从尾部开始以相反的顺序添加大小,一旦达到阈值,则从该点开始删除所有项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM