C++ : STL Container adapters

标签 c++ stl containers

在下面的代码中,'Second' 通过使用底层容器初始化为双端队列和'fourth' 的拷贝。如果有人能向我解释,何时初始化容器的拷贝以及何时使用底层容器,我会感到很高兴。

#include <iostream>       // std::cout
#include <deque>          // std::deque
#include <list>           // std::list
#include <queue>          // std::queue

int main ()
{
  std::deque<int> mydeck (3,100);        // deque with 3 elements
  std::list<int> mylist (2,200);         // list with 2 elements

  std::queue<int> first;                 // empty queue
  std::queue<int> second (mydeck);       // queue initialized to copy of deque

  std::queue<int,std::list<int> > third; 
  std::queue<int,std::list<int> > fourth (mylist);

  std::cout << "size of first: " << first.size() << '\n';
  std::cout << "size of second: " << second.size() << '\n';
  std::cout << "size of third: " << third.size() << '\n';
  std::cout << "size of fourth: " << fourth.size() << '\n';

  return 0;
}

最佳答案

When to initialize to the copy of a container and when to use an underlying container?

这两个...

std::queue<int> second(mydeck);
std::queue<int,std::list<int> > fourth(mylist);

...通过从指定为构造函数参数的容器中复制元素来构造和初始化队列(即分别为 mydeckmylist)。

如果你想问为什么第二个指定第二个模板参数 std::list<int> ,那是因为 std::queue可以将数据存储在任何提供它期望的 API 功能的容器中。来自 cppreference ,第二个模板参数是:

Container - The type of the underlying container to use to store the elements. The container must satisfy the requirements of SequenceContainer. Additionally, it must provide the following functions with the usual semantics:

    back()
    front()
    push_back()
    pop_front() 

The standard containers std::deque and std::list satisfy these requirements.

其中,我猜 std::list对于一个或极少数元素通常会更有效(截断的确切位置取决于对象大小、内存库性能特征、CPU 缓存大小、系统负载等 - 它变得复杂),然后 std::deque对于更多的元素(更少但更大的动态内存分配/释放),将具有更好的平均性能和内存使用。但是,对于某些特定用例,即使是有根据的猜测也可能会出现严重错误 - 如果您足够关心考虑调整这一点,您应该衡量每个候选容器的性能,以及您的实际数据和使用情况,以告知您的决定。将容器作为模板参数允许程序员选择最适合他们需要的内容。

参数也有默认...

template <class T, class Container = std::deque<T>> class queue;

...因此,如果您不高兴让它使用 std::deque,您只需要明确指定一个容器即可。 .

关于C++ : STL Container adapters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23751335/

相关文章:

C++ 拆分字符串反馈

c++ - PartialOrdering、StrictWeakOrdering、TotalOrdering,在应用上的主要区别是什么

c++ - 闪烁(后台缓冲区?)

c++ - 将结构写入和读取文件

c++ - 在使用 std::stod 之前初始化 QApplication 的奇怪错误

c++ - 检查 std::vector 的大小是否为零

c# - 我可以进一步减少对由docker容器上的asp.net Web API应用程序运行的docker镜像的依赖性

containers - 访问英国数据中心的 IBM Containers 时出现问题

file - Docker:如何使用本地文件?

c# - Windows 哈希密码