迭代std :: map <...>的简单方法?

Meh*_*dad 3 c++ iterator visual-c++

我有一个类似于以下类型的变量:

map<bool, map<string, pair<string, int> > > items;
Run Code Online (Sandbox Code Playgroud)

我传递给不同的功能.

有没有一种不那么繁琐的方式让我迭代它然后说

for (map<bool, map<string, pair<string, int> > >::iterator p = items.begin();
    p != items.end(); p++)
    ...
Run Code Online (Sandbox Code Playgroud)

每次?(即我可以以某种方式省略类型名称,使用宏或模板或其他东西?手册typedef不计算.)

我正在使用Visual C++ 2008.

Ale*_* C. 6

你可以用BOOST_FOREACH.为了清晰起见,您必须使用typedef:

typedef std::map<std::string, std::pair<std::string, int> > inner_map;
typedef std::pair<bool, inner_map> map_entry;

BOOST_FOREACH(map_entry& p, items)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢普通typedef和for循环.我看到typedef变量赋值的方式相同:

typedef std::map<std::string, std::pair<std::string, int> > inner_map;
typedef std::map<bool, inner_map>::iterator map_iterator;

for (map_iterator i = items.begin(); i != items.end(); ++i)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

那些typedef也可以是私有成员.这种编码风格更加清晰,因为您可以一目了然地看到所涉及的类型.

或者你可以使用plain std::for_each,如果你准备写一个仿函数.我在标准C++中并不喜欢这个,因为循环体不再是本地的(但在某些情况下这可能是一个优势):

struct some_functor
{
    template <typename K, typename V>
    void operator()(std::pair<K, V>& item)
    {
        // In the context below, K is bool and
        // V is map<string, pair<string, int> >
    }
};
Run Code Online (Sandbox Code Playgroud)

然后是

std::for_each(items.begin(), items.end(), some_functor());
Run Code Online (Sandbox Code Playgroud)

如果您升级到VS2010,您可以选择:autostd::for_eachlambda(我更喜欢).对于C++ 0x,从技术上讲,您还有基于范围的for循环(在VS2010中不可用).

最后,我会这样做:

class meaningful_data
{
    typedef std::map<std::string, std::pair<std::string, int> > inner_map;
    std::map<bool, inner_map> items;

public:
    typedef std::pair<bool, inner_map> value_type;
    typedef std::map<bool, inner_map>::iterator iterator;
    typedef std::map<bool, inner_map>::const_iterator const_iterator;

    iterator begin() { return items.begin(); }
    const_iterator begin() const { return items.begin(); }
    iterator end() { return items.end(); }
    const_iterator end() const { return items.end(); }

    // Add some interface here (as small as possible)
};
Run Code Online (Sandbox Code Playgroud)

并迭代如下:

for (meaningful_data::iterator i = d.begin(); i != d.end(); ++i)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

要么

BOOST_FOREACH(meaningful_data::value_type& i, d)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

你可能想要封装这样一个复杂的类型,至少有一些typedef(如果inner_map类型应该是公共的,你不会被迫使用一个完整的类).