如何检查容器是否稳定 [英] How to check whether a container is stable
问题描述
std :: vector
是一个不稳定的容器,即通过调整向量大小,迭代器可能会失效。
相反, std :: list
或 boost :: container :: stable_vector
迭代器有效,直到删除相应的元素。
std::vector
is an unstable container, i.e. by resizing the vector, iterators might become invalidated.
In contrast, std::list
or boost::container::stable_vector
are stable containers which keep the iterators valid until the removal of the corresponding element.
有没有办法检查给定的容器是否稳定?例如,如果我有像
Is there a way to check whether a given container is stable? For instance, if I have something like
template<template <typename A, typename B=std::allocator<A> > class T=std::list>
class Foo
{
}
推荐答案
我不认为有任何可用的提供这样的信息,但你可以写你自己的特质。但是,您将需要专门为每个可能使用的稳定容器,这可能不是一个选项。
I don't think there is anything available providing such information, but you could write your own trait. However, you will need to specialize it for every stable container that may be used, which is perhaps not an option.
#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
}
我不认为有办法自动
为了有趣,我尝试写下什么概念/公理的稳定性看起来像(概念和公理是对考虑包含在C ++ 11中):
Just for fun, I tried writing what the concept/axiom for stability would look like (concepts and axioms are an extension to the language that were 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);
}
}
}
要求原始容器上的每个迭代器都等同于修改后的容器上的相应迭代器。不确定这是非常有用,但是提出这样的公理是一个有趣的练习:)
If think this correctly captures the requirement that every iterator over the original container is equivalent to the corresponding iterator over the modified container. Not sure this is very useful, but coming up with such axioms is an interesting exercise :)!
这篇关于如何检查容器是否稳定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!