C++ STL : Container Recreation or Reuse after clearing?

标签 c++ stl complexity-theory

在编程中,我们会遇到各种需要使用中间 STL 容器的情况,如下例所示:

while(true)
{
    set < int > tempSet;

    for (int i = 0; i < n; i ++)
    {
        if (m.size() == min && m.size() <= max)
        {
            tempSet.insert(i);
        }
    }
    //Some condition testing code
}

或者

set < int > tempSet;

while(true)
{
    for (int i = 0; i < n; i ++)
    {
        if (m.size() == min && m.size() <= max)
        {
            tempSet.insert(i);
        }
    }
    tempSet.clear();

    //Some condition testing code
}

考虑到 C++ 编译器的现状,哪种方法在时间和空间复杂度方面更好?

最佳答案

第一个版本是正确的。它几乎在所有方面都更简单。更易于编写、更易于阅读、更易于理解、更易于维护等....

第二个版本可能更快,但也可能不会。在使用它之前,您需要证明它具有显着优势。在大多数重要情况下,我猜想两者之间不会有可衡量的性能差异。

有时在嵌入式编程中避免将东西放在堆栈上是很有用的;在这种情况下,第二个版本是正确的。

默认使用第一个版本;仅当您可以给出充分的理由时才使用第二种(如果原因是性能,那么您应该有证据表明好处是显着的)。

关于C++ STL : Container Recreation or Reuse after clearing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/217149/

相关文章:

c++ - 包含 windows.h 和 wingdi.h 时出现 "GradientFill was not declared in this scope"错误

c++ - 如果字符串参数不是字符串文字,是否可以强制编译错误?

c++ - 从 set<A*,Comparator> 获取 A 成员到 list<A>

c++ - 列表容器中的迭代器

time-complexity - 如何计算回溯算法的时间复杂度

c++ - 用C++实现fastcgi可行吗?

c++ - 游戏引擎 C++ 和 Objective-C/Xcode 编码

c++ - 为什么 unordered_set 不提供数组访问运算符

algorithm - 运行时间,复杂性,编译时间和执行时间有什么区别?

php - 如何处理我的 PHP 模型的 n-m 关系?