Question

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;
}
Was it helpful?

Solution

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.

OTHER TIPS

You shouldn't use at() in a for loop condition like that. The element does not change between iteration and there is a overhead in retrieving it at every turn. So you should just retrieve it using find and then loop on the iterators:

addheader_t::const_iterator header_iter = addheader.find(suffix); // Retrieve the element

if (header_iter != addheader.end()) // Check that it does exist
{
  // Retrieve the sub-map in the pair
  const headerpair_t& header_pair_map = it->second;

  // Loop on the elements
  for (headerpair_t::const_iterator it = header_pair_map.begin(); header_pair_map.end(); ++it)
  {
    // Use insert to avoid a useless element construction
    // Use also `std::make_pair`, but can we directly insert the pair from headerpair ?
    meta.insert(std::make_pair(it->first, it->second));
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top