gpt4 book ai didi

c++ - 为什么队列接受 vector 作为其底层容器?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:48:09 30 4
gpt4 key购买 nike

考虑以下代码:

std::queue<int, std::vector<int>> Q;
Q.push(1);
Q.push(2);

Live Demo

除了使用具有连续内存的容器作为 std::queue 的底层容器这一事实之外会显着降低排队操作的性能,上面的代码完全可以接受并编译。但是,如果我们调用 std::queue::pop成员函数(例如 Q.pop();)程序无法编译,编译器会正确地提示 std::vector没有成员函数 pop_front .

Live Demo

问题:

  1. 为什么是std::vector可接受作为 std::queue 的基础容器因为它不满足 std::queue的标准?
  2. 是不是缺少一些元编程魔法来检查std::queue 的底层容器?满足队列定义行中的必要条件(例如 std::queue<int, std::vector<int>> Q; )?
  3. 能否降临concepts-lite , 可能在 C++17 中,解决这个问题?

最佳答案

Why is std::vector acceptable as an underlying container for std::queue since it doesn't satisfy std::queue's criteria?

不是。

Isn't some short of meta-programming magic to check whether the underlying container of std::queue fulfils the necessary criteria in the line of queue's definition (e.g., std::queue<int, std::vector<int>> Q;)?

这句话没有意义,但如果你问是否有可能在实例化时诊断这一点,答案是肯定的。不过,这在很大程度上是浪费时间。为了比较,请注意如何越界 std::vector::operator[]也是的责任,不会导致诊断。

Could the advent of concepts-lite, probably in C++17, solve this problem?

既然这根本就是一个“问题”,是的。

关于c++ - 为什么队列接受 vector 作为其底层容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24596064/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com