【问题标题】:Create a struct in each iteration在每次迭代中创建一个结构
【发布时间】:2015-03-10 17:49:54
【问题描述】:

我想将队列存储在来自stl 库的队列结构中。由于某些原因,我必须在程序的每次迭代中存储一个队列,但我认为一遍又一遍地创建一个新队列太昂贵了。

我只知道两种方法可以做到这一点。第一个:

#include <iostream>
#include <deque>
using namespace std;
int main () {
    unsigned int limit, i = 0;
    deque<deque<int> > container;
    cin >> limit;
    for ( ; i < limit; i++ ) {
        deque<int> values;
        //set some values in the values structure.
        setValues(values, i);
        container.push(values);
    }
}

第二个:

#include <iostream>
#include <deque>
using namespace std;
int main () {
    unsigned int limit, i = 0;
    deque<deque<int> > container;
    deque<int> values;
    cin >> limit;
    for ( ; i < limit; i++ ) {
        //reset the structure, i.e. delete al the previous values.
        reset(values);
        //set some values in the values structure.
        setValues(values, i);
        container.push(values);
    }
}

这里的问题是我不知道任何重置队列的功能,或者我必须这样做values=NULL

我怎样才能有效地做到这一点?

谢谢! :D

【问题讨论】:

  • std::deque::clear() 怎么样?如values.clear()
  • 是最好的方法吗?
  • 您应该使用第一种方法,直到您确定程序正确但速度太慢,并且您的测量表明对象构造是主要瓶颈。

标签: c++ memory data-structures stl


【解决方案1】:

您可以在循环中推送一个空的deque,获取对它的引用,然后向其中添加项目。

#include <iostream>
#include <deque>

using namespace std;

int main () {
    unsigned int limit, i = 0;
    deque<deque<int> > container;
    cin >> limit;
    for ( ; i < limit; i++ ) {
        container.push_back(deque<int>());
        deque<int>& values = container.back();
        //set some values in the values structure.
        setValues(values, i);    }
}

【讨论】:

  • 其实push_back不是必须的,你可以直接构造container指定默认构造的元素个数这样:deque&lt;deque&lt;int&gt; &gt; container(limit);(当然获取@之后987654325@ 来自cin)。
【解决方案2】:

你应该在调试器中检查你的编译器在你复制双端队列时实际上在做什么。我已经检查了 VS2013 及其所有移动语义 - 正如预期的那样。这是一个测试代码:

std::deque<int> getValues() {
    std::deque<int> res;
    res.push_back(1);
    return res; // deque(_Myt&& _Right) called, also other compilers might use RVO
}

std::deque<int> ff;
std::deque<std::deque<int>> aff;
aff.push_back(getValues()); // void push_back(value_type&& _Val) called

起初看起来复制很多,但实际上在两个有问题的地方都使用了移动语义,并且只复制了临时对象的指针,因此速度非常快。

但也许你在 c++11 之前的世界里很僵硬?至少这个片段

  deque<deque<int> > container; 
                 ^^^

给出这样的提示。

【讨论】:

  • 是的,我使用的是旧版本的 C++,多么好的观察!
猜你喜欢
  • 2019-01-19
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
相关资源
最近更新 更多