STL兼容的容器

5
我一直很好奇什么是符合STL标准的容器(或者Boost标准,我的理解是它们要么相同,要么非常相似)。我看到了一些人所谓的STL兼容的例子(例如,在codeproject上的这个和实际的STL容器),但我不确定哪些组件是必须的。
根据我所了解的,我至少需要以下内容:
1. STL兼容的迭代器(当前STL仅使用双向或更高级别的迭代器,不知道这是否是必需的还是只是偶然发生的情况,仍在弄清楚哪些内容是必需的才能被认为是“STL兼容的迭代器”); 2. 定义分配器的机制(默认为std::allocator),以及正确使用它们(仍在努力弄清楚这最后一部分的含义); 3. 用于元编程的公共typedef(指针类型、const指针类型、引用类型、值类型、const引用类型、差异类型,可能还有其他一些?)。附带问题:什么是difference type? 4. “通用”的(即使用元编程/模板使容器能够容纳几乎任何类型)。
还有其他我错过的东西吗?或者更糟糕的是,在上面的列表中错误了(例如,像const-correctness、线程安全、异常生成/处理等问题)?此外,是否有规范文档详细说明所需的内容,如果这样的文档存在的话?

1
我甚至不确定“STL兼容”是否真的意味着比讲话者想要的更多。标准模板库已经过时了;其中很多内容已经被纳入C++标准库,这就是今天使用的内容。因此,如果他们使用术语“C++兼容”或“C++标准库兼容”,可能会更有意义。如果某个东西“符合C++ 2011标准”,那么可能意味着“您可以使用这个容器来进行新的for语法”。 - Mike DeSimone
哦,我没有意识到STL与C++标准库不同。我想这是同样的问题,但在稍微不同的上下文中。我只是想知道如何创建自己的容器,其功能/接口基本与标准库相同,但当然是用于保存不同的数据结构。 - helloworld922
1
很多人使用“STL”一词来表示“在C++标准库中幸存下来的STL部分”。术语的含义随着时间的推移而经常发生变化。 - Bo Persson
1个回答

6
  1. Iterators: the standard library defines iterator categories. You want to supply iterators that model one of those categories. Depending on your viewpoint, the istream_iterator and ostream_iterator allow streams to be containers that don't supply bidirectional iterators.

  2. Basically, you use the allocator's allocate(n) to allocate space for n objects, and deallocate(p, n) to free the space for n objects pointed to by p. You normally don't use the allocator's construct or destroy members.

  3. Yes, there are a few others (e.g., associative containers define a key_type). difference_type is a type that can represent the difference between two pointers. It's normally supplied by the allocator, so a container will just have a typedef something like:

    typedef Allocator::difference_type difference_type;
    
  4. There's not necessarily (or even commonly) any metaprogramming involved, just (fairly basic) generic programming. I.e., you define a template, but don't necessarily carry out any computation at compile time (which would be metaprogramming).

在最初提出这个问题时,当前标准并没有定义任何关于线程或线程安全的内容。您所使用的任何线程支持都是完全独立的,并且您需要遵循它指定的规则(通常是多个线程可以读取容器,但线程需要独占式访问以写入容器)。

从C++11开始,标准确实增加了对线程的支持,包括有关线程安全、数据竞争等的定义。这指定允许并行读取,但写入需要是独占的。


你是指这本书吗:http://www.amazon.com/Standard-Library-Tutorial-Reference/dp/0201379260/ref=ntt_at_ep_dpt_1 - helloworld922
@helloworld922:抱歉——我可能应该提供一个链接,但是没错,那就是我想说的那个。 - Jerry Coffin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接