map_utils: complete rewrite in C++11 way

* Use C++11 STL stuff to have more generic code.
* Allocate the vector once to improve runtime-performance.

Change-Id: Ic18d87d2abf83f7c934a8bc6598f36a71328fcd7
This commit is contained in:
Guillaume Roguez
2017-08-25 16:12:29 -04:00
parent e8857a9bb0
commit 38faaebf1d
2 changed files with 30 additions and 28 deletions

View File

@ -2858,9 +2858,7 @@ Manager::getConferenceDetails(
std::vector<std::string>
Manager::getConferenceList() const
{
std::vector<std::string> v;
map_utils::vectorFromMapKeys(pimpl_->conferenceMap_, v);
return v;
return map_utils::extractKeys(pimpl_->conferenceMap_);
}
std::vector<std::string>

View File

@ -1,7 +1,7 @@
/*
* Copyright (C) 2013-2017 Savoir-faire Linux Inc.
* Copyright (C) 2017 Savoir-faire Linux Inc.
*
* Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
* Author: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -18,37 +18,41 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef MAP_UTILS_H_
#define MAP_UTILS_H_
#pragma once
#include <vector>
#include <map>
#include <iterator>
#include <algorithm>
#include <tuple>
namespace ring { namespace map_utils {
template <typename M, typename V>
void vectorFromMapKeys(const M &m, V &v)
///< Return the N-th type of a tuple type used as the Container compliant value type
template <typename C, std::size_t N>
using type_element = typename std::remove_cv<typename std::tuple_element<N, typename C::value_type>::type>::type;
///< Extract in a std::vector object each N-th values of tuples contained in a Container compliant object \a container.
template <std::size_t N, typename C>
inline std::vector<type_element<C, N>>
extractElements(const C& container)
{
for (typename M::const_iterator it = m.begin(); it != m.end(); ++it)
v.push_back(it->first);
std::vector<type_element<C, N>> result;
if (container.size() > 0) {
result.resize(container.size());
auto iter = std::begin(container);
std::generate(std::begin(result), std::end(result), [&]{ return std::get<N>(*iter++); });
}
return result;
}
template <typename M, typename V>
void vectorFromMapValues(const M &m, V &v)
{
for (typename M::const_iterator it = m.begin(); it != m.end(); ++it)
v.push_back(it->second);
}
template <typename M>
inline auto
extractKeys(const M& map) -> decltype(extractElements<0>(map))
{ return extractElements<0>(map); }
template <typename M, typename V>
typename M::const_iterator
findByValue(const M &m, V &v) {
for (typename M::const_iterator it = m.begin(); it != m.end(); ++it)
if (it->second == v)
return it;
return m.cend();
}
template <typename M>
inline auto
extractValues(const M& map) -> decltype(extractElements<1>(map))
{ return extractElements<1>(map); }
}} // namespace ring::map_utils
#endif // MAP_UTILS_H_