所以,我想知道是否可以将 C++ 适配器与库函数对象结合起来,以便对 C++ 标准库中定义的容器进行一些操作。
例如,如果我要定义一个包含一些元素的 vector
vector<int> vi={1,2,3,4,5,6,7,8,9,0};
我只想计算该 vector 中包含的大于 4 的值,例如,我对使用适配器的可能性感兴趣:
priority_queue<int, vector<int>, greater<int> > pq(vi.begin(),vi.end());
但是,在我看来,上一行只会复制 vi
的整个拷贝进入pq
,同时考虑到元素顺序是升序的。有没有办法通过 greater<int>
调节适配器仅考虑输入 vector 中的特定值?
最佳答案
Eric Niebler 的 ranges library有许多适应范围的设施,特别是过滤范围。但是,标准库容器本身不接受此类适配器。如果您对迭代器对而不是范围感到满意,并且希望避免需要 Concept 支持,那么 Boost 库有很多迭代器实用程序代码:Boost Iterator Library , 包括 boost::filter_iterator
.
话虽如此,您可以使用标准库工具(例如 std::copy_if
)通过过滤从旧容器轻松初始化新容器。 :
template< class InputIt, class OutputIt, class UnaryPredicate >
constexpr OutputIt copy_if( InputIt first, InputIt last,
OutputIt d_first,
UnaryPredicate pred );
在你的情况下,它会是这样的:
std::priority_queue<int, std::vector<int>, std::greater<int> > pq;
auto greater_than_four = [](int x) { return x > 4; };
std::copy_if(vi.begin(), vi.end(), push_insert_iterator(pq), greater_than_four);
定义了 push_insert_iterator
here . (代码未经测试。)
关于c++ - 在容器排列中使用 C++ 适配器和库函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50678651/