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

标签 c++ stl iterator containers

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/

相关文章:

c++ - 带有 exit(1) 调用的库的 Rcpp

c++ - C\C++ 中的 Windows USB 设备刷新

c++ - 如何指定 QString::indexOf 方法?

c++ - unordered_set 通过地址传递

java - 使用迭代器或 for 循环获取类转换异常

c++ - 我必须实现哪些功能才能使类可迭代?

c++ - poll() 不标记可读数据

c++ - std::map,指向映射键值的指针,这可能吗?

c++ - 标准 vector push_back' : 2 overloads have no legal conversion for 'this' pointer error

java - Java 无限循环遍历 ArrayList