Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing map with C++98 standard

Tags:

c++

c++11

c++98

I have the following C++11 compatible code and I need to compile it with C++98 which doesn't have support for '.at'. How to rewrite it to be compatible with C++98 ?

String suffix("sss");
headers_t& meta = ...;
typedef std::map<std::string, std::string> headerpair_t;
typedef std::map<std::string, headerpair_t> addheader_t;

addheader_t addheader;

for(headerpair_t::const_iterator piter = addheader.at(suffix).begin(); piter !=  addheader.at(suffix).end(); ++piter){
    // Adding header
    meta[(*piter).first] = (*piter).second;
}
like image 446
Shan Muh Avatar asked Mar 15 '26 02:03

Shan Muh


1 Answers

Just create an at() function which mimicks what C++11 std::map<...>::at() does:

template <typename K, typename V, typename C, typename A>
V const& at(std::map<K, V, C, A> const& m, K const& k) {
    typename std::map<K, V, C, A>::const_iterator it(m.find(k));
    if (it == m.end()) {
        throw std::out_of_range("key not found in map");
    }
    return it->second;
}

Note that calling at() in each iteration of a loop is a Bad Idea! Searching a std::map<...> is efficient in the theoretical sense but that doesn't mean that it is fast in practice! You are much better off to search the relevant node just one and then keep using it.

like image 163
Dietmar Kühl Avatar answered Mar 16 '26 16:03

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!