gpt4 book ai didi

c++ - 如何检查容器是否稳定

转载 作者:IT老高 更新时间:2023-10-28 22:30:23 25 4
gpt4 key购买 nike

std::vector 是一个不稳定的容器,即通过调整 vector 的大小,迭代器可能会失效。相比之下,std::listboost::container::stable_vector 是稳定的容器,它们保持迭代器有效,直到删除相应的元素。

有没有办法检查给定容器是否稳定?例如,如果我有类似的东西

template<template <typename A, typename B=std::allocator<A> > class T=std::list>
class Foo
{
}

是否可以只允许稳定的容器而禁止不稳定的容器?

最佳答案

我认为没有任何东西可以提供此类信息,但您可以编写自己的特征。但是,您需要为每个可能使用的稳定容器专门化它,这可能不是一个选择。

#include <boost/container/vector.hpp>

#include <iostream>
#include <type_traits>
#include <list>
#include <vector>

template <template <typename...> class Container>
struct is_stable
: std::false_type
{};

template <>
struct is_stable<std::list>
: std::true_type
{};

template <>
struct is_stable<boost::container::stable_vector>
: std::true_type
{};

template<template <typename...> class Container = std::list>
class Foo
{
static_assert(is_stable<Container>::value, "Container must be stable");
};

int main()
{
Foo<std::list> f1; // ok
Foo<std::vector> f2; // compiler error
}

我认为没有一种方法可以自动检测容器是否稳定,而无需借助手动专门化。


只是为了好玩,我尝试编写稳定性的概念/公理(conceptsaxioms 是对 considered for inclusion in C++11 语言的扩展):

concept StableGroup<typename C, typename Op>
: Container<C>
{
void operator()(Op, C, C::value_type);

axiom Stability(C c, Op op, C::size_type index, C::value_type val)
{
if (index <= c.size())
{
auto it = std::advance(c.begin(), index);
op(c, val);
return it;
}
<->
if (index <= c.size())
{
op(c, val);
return std::advance(c.begin(), index);
}
}
}

如果认为这正确地捕获了原始容器上的每个迭代器都等效于修改后容器上的相应迭代器的要求。不确定这是否很有用,但提出这样的公理是一个有趣的练习:)!

关于c++ - 如何检查容器是否稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16709828/

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