dump any STL container #2 template functions

template<typename M> void dumpMap(M const & cont) {
    for(auto const & i: cont)        cout<<i.first<<" -> "<<i.second<<endl;
}
template<typename CT> void dump(CT const & cont) {
    for(auto const & i: cont)        cout<<i<<endl;
}
/////////// above uses c++11 features
template<typename CT> void dump(const CT& cont) {
    typedef typename CT::const_iterator iterator; //typedef -- no choice
    iterator i;
    //non-compile --
    //CT::const_iterator i;
    for(i = cont.begin(); i!= cont.end(); ++i){
        cout<<*i <<" "<<endl;
    }
}
//! Better use iterator arguments
//! Better use iterator arguments
template<typename M>
void dumpMap(const M& cont) {
    typedef typename M::const_iterator iterator; //no choice
    iterator i;
    for(i = cont.begin(); i!= cont.end(); ++i){
        cout<<i->first<<" "<<i->second<<endl; // ->first may be unsupported. Checked during template expansion
    }
}
int main() {
    vector<int> v;
    v.push_back(12);
    v.push_back(24);
    map<char const *, int> map; // c-string i.e. char-pointer in a container
    map["1)"] = 11;
    map["3)"] = 33;
    dump(v);
    dumpMap(map);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s