Minimal set of nested typedefs for a custom STL sequence?

与世无争的帅哥 提交于 2020-01-01 15:35:13

问题


What is the minimal set of nested typedefs that should be defined in a custom STL class meeting the Sequence concept? The custom sequence should be compatible with:

  1. std::back_insert_iterator
  2. BOOST_FOREACH
  3. Boost range concept.

回答1:


The C++ Standard says all containers must have the following typedefs (C++03 23.1/Table 65):

value_type
reference
const_reference
iterator
const_iterator
difference_type
size_type

Reversible containers must have the following typedefs (C++03 23.1/Table 66):

reverse_iterator
const_reverse_iterator



回答2:


I came up with this program to find the mininal set of nested typedefs:

#include <iostream>
#include <iterator>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/range/algorithm/sort.hpp>

struct Foo
{
    typedef std::vector<int> Vec;
    typedef Vec::const_reference const_reference;
    typedef Vec::iterator iterator;
    typedef Vec::const_iterator const_iterator;

    iterator begin() {return vec.begin();}
    iterator end() {return vec.end();}
    const_iterator begin() const {return vec.begin();}
    const_iterator end() const {return vec.end();}
    void push_back(const int& n) {vec.push_back(n);}

    Vec vec;
};

int main()
{
    Foo f;
    std::back_insert_iterator<Foo> it(f);
    *it = 2; ++it; *it = 1; ++it;
    boost::sort(f);
    BOOST_FOREACH(int x, f)
    {
        std::cout << x << " ";
    }
}

As you can see, at least const_reference, iterator, and const_iterator are needed.

I should mention that I compiled this with gcc 4.4.3 and boost 1.43.



来源:https://stackoverflow.com/questions/4823761/minimal-set-of-nested-typedefs-for-a-custom-stl-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!