Copy map/multimap keys to vector or set - c++

I have written below code to convert keys in map or multimap to set:
template<typename STLContainer>
inline auto CopyContanerKeyToSet(const STLContainer& cont)
{
std::set<decltype(cont.begin()->first)> lset;
std::transform(cont.begin(),cont.end(),std::inserter(lset,lset.end()),[](const auto it) { return it.first;});
return lset
}
Now there is requirement that sometimes I need to convert keys into vector as well. So I just want to know how to write template function that can accept vector or set as template argument and after that create that container accordingly.

We can solve this with a Template template parameter. This allows us to specify just the main type without specifying the template type of that type. Doing that gives us
template< template<typename ...> class OutputContainer, typename STLContainer>
inline auto CopyContanerKeyToSet(const STLContainer& cont)
{
OutputContainer<typename STLContainer::key_type> lset;
std::transform(cont.begin(),cont.end(),std::inserter(lset,lset.end()),[](const auto it) { return it.first;});
return lset;
}
And then we can use that with something like this
int main()
{
std::map<std::string, int> foo{ {"this", 1}, {"second", 1} };
auto output = CopyContanerKeyToSet<std::vector>(foo);
for (const auto& e : output)
std::cout << e << " ";
}
Which gives us
second this
Live Example
I also changed <decltype(cont.begin()->first)> to <typename STLContainer::key_type> as value_type of the map/multimap has a const key_type for the std::pair which we do not want for the vector/set.

Related

How can i get template's type if my instance is stl map?

I want a get_value template function.
please see the following code:
template<typename T>
(something i want) get_value(const T& m, int key) {
auto it = m.upper_bound(key);
return it == m.begin() ? (*it).second : (*--it).second; // please notice here,
// if my instance is map<int, map<string, int>> the return type should be m.second's type
// that's map<string, int>
}
int main() {
std::map<int, std::map<std::string, int>> m;
auto& it = get_value(m, 10);
}
as you can see, the template function should have a return type, which is depend on instance's second type, is there any method i can get this type to make the code runnable?
The "second type" in a std::map<K,V> is called std::map<K,V>::mapped_type. However, you can use auto to let the compiler deduce that for you:
template<typename T>
auto get_value(const T& m, int key) {
auto it = m.upper_bound(key);
return it == m.begin() ? (*it).second : (*--it).second; // please notice here,
}
or with explicit type:
template<typename T>
typename T::mapped_type get_value(const T& m, int key) {
auto it = m.upper_bound(key);
return it == m.begin() ? (*it).second : (*--it).second; // please notice here,
}
If you can use C++14 standard or above, the safest way to go would be to use decltype(auto) as the return type:
template<typename T>
decltype(auto) get_value(const T& m, int key);
The difference to a plain auto is that decltype(auto) preserves cv-qualifiers, and in your case you most likely want to forward exactly the same type that std::map gives you.
For example, since the actual code uses std::map<int, std::map<std::string, int>>, you might want to avoid copying the return value every time, and decltype(auto) will achieve that.

Automatically deducing element type of pair container from the function template argument

I want to write a template function which takes a container of key-value pairs (e.g map<K,V> or vector<pair<K,V>>) and returns a container of container of keys. For example:
template<typename C, typename K, typename V>
vector<vector<K>> partition_keys(const C& input)
{
vector<vector<K>> result;
...
// do something
for (const auto &pair : input)
{
cout << pair.first << "," << pair.second << std::endl;
}
...
return result;
}
Here's how I would like to call it:
// map
map<string, string> product_categories;
partition_keys(product_categories); // doesn't work
partition_keys<map<string, string>, string, string>(product_categories); // have to do this
// vector
vector<pair<string, string>> movie_genres;
partition_keys(movie_genres); // doesn't work
partition_keys<vector<pair<string, string>>, string, string>(movie_genres); // have to do this
But, the compiler cannot deduce the template parameters K and V without explicitly specifying them. I want the function to work with any container having pair of any type; so I want to avoid writing separate template functions for map<K,V>, list<pair<K,V>>, vector<pair<K,V>>, etc.
So, I had to modify the template function signature as follows to make it work the way I want:
template<typename C,
typename K = remove_const_t<C::value_type::first_type>,
typename V = C::value_type::second_type>
vector<vector<K>> partition_keys(const C& input);
Is there a better way to do this? Is it a good practice to deduce types of K and V based on value_type of C? Also, there is a possibility of caller explicitly passing invalid arguments for K and V.
Note also how I had remove constness of key type by calling remove_const_t because for a map, C::value_type::first_type is a const type and the standard doesn't allow creating a collection of a const type.
You are doing the right way, more specifically:
template<typename C,
typename Pair = typename C::value_type,
typename Key = std::remove_const_t<typename Pair::first_type>,
typename Value = typename Pair::first_type
>
vector<vector<Key>> partition_keys(const C& input)
is correct (Demo). However, if you need to use similar type decomposition for different template functions like:
....repeat above templated type decomposition....
vector<vector<Key>> sorted_keys(const C& input);
....repeat above templated type decomposition....
vector<vector<Key>> filtered_keys(const C& input);
It may be too much of typing to do. In that case, you can make a simple trait class to help you with that.
template<typename T>
struct PTraits{
using pair_type = typename T::value_type;
using key_type = std::remove_const_t<typename pair_type::first_type>;
using value_type = typename pair_type::second_type;
};
template<typename T>
using KeyTypper = typename PTraits<T>::key_type;
Then use as...
template<typename C, typename Key = KeyTypper<C>>
vector<vector<Key>> partition_keys(const C& input);
template<typename C, typename Key = KeyTypper<C>>
vector<vector<Key>> sorted_keys(const C& input);
template<typename C, typename Key = KeyTypper<C>>
vector<vector<Key>> filtered_keys(const C& input);
Demo
It is fine. If you don't like the clutter in template parameters, you can put the key type directly in the return type, possibly in trailing form:
template <typename C>
auto partition_keys(const C& input)
-> vector<vector<remove_const_t<typename C::value_type::first_type>>>;
or rely on return type deduction for normal functions and omit the return type entirely:
template <typename C>
auto partition_keys(const C& input)
{
vector<vector<remove_const_t<typename C::value_type::first_type>>> result;
//...
return result;
}

Creating an iterator to a map in a class template

I have this class template which contains a map as following:
template<class K, class V>
class interval_map {
private:
std::map<K,V> m_map;
}
And I want to have a function that adds values to the maps and checks whether the key already exists or not so I am trying to do this using iterator :
void add_elements_test2 ( K const& key,V const& val)
{
std::make_pair<typename std::map<K,V>::iterator,bool>x;
x= m_map.insert(std::make_pair(key,val));
if(x.second = false)
{
cout<<"Key alreads exists "<<endl;
}
}
but I get this error when I create the operator:
std::make_pair<typename std::map<K,V>::iterator,bool>x;
Is this is a correct way?
std::make_pair<typename std::map<K,V>::iterator,bool>x;
It not correct the correct way to declare a std::pair. If you want to declare a std::pair for the return of insert then you need
std::pair<typename std::map<K,V>::iterator,bool> x;
And now x has the correct type. std::make_pair is a function that is used to construct a std::pair and you pass it the variables to make the pair from.
Instead of having to type all this though you can simply use auto like
auto x = m_map.insert(std::make_pair(key,val));
//...
Now x has the correct type and you do a lot less typing.
You also have a typo in
if(x.second = false)
In the above you are doing assignment, not comparison. Since you are setting the value to false the if statement will never run as it will always evaluate to false. You need
if(x.second == false)
Simply use auto:
auto x = m_map.insert(std::make_pair(key, val));
if (!x.second)
{
cout << "Key already exists" << endl;
}
Note: the type you want is pair
std::pair<typename std::map<K, V>::iterator, bool>
std::make_pair is an utility function to create std::pair.
I wrote this answer so that you don't hate template classes in the future. There are 2 scenarios you need to consider, and I have listed them both in the code below. Let me know if you have any questions, the comments are detailed.
Scenario 1, add_elements_test2 is defined inside the class
template<class K, class V>
class interval_map {
private:
std::map<K,V> m_map;
// This is fine because the K and V types are in the same scope for the map, and add_elements_test2
void add_elements_test2 ( K const& key,V const& val)
{
// Use auto here to simplify your life a little
auto x = m_map.insert(std::make_pair(key,val)); // actual type is std::pair<K, bool>
if(x.second == false)
{
cout<<"Key already exists "<<endl;
}
}
};
Scenario 2, add_elements_test2 is defined outside the class
template<class K, class V>
class interval_map {
private:
std::map<K,V> m_map;
void add_elements_test2 ( K const& key,V const& val);
};
// need another template
template<class K, class V>
// need to template interval_map, this could cause headaches if you did not realize this is a templated class
void interval_map<K, V>::add_elements_test2 ( K const& key,V const& val)
{
// Use auto here to simplify your life a little
auto x = m_map.insert(std::make_pair(key,val)); // actual type is std::pair<K, bool>
if(x.second == false)
{
cout<<"Key already exists "<<endl;
}
}
Essentially, your mistake with x is the type definition.
// pair is in the utility header
std::pair<K, bool> x= m_map.insert(std::make_pair(key,val));

Getting a list of values from a map

Is there an stl way to get a list of values from a map?
i.e, I have:
std::map<A,B> myMap;
and I would like a function that will return just the list of values, i.e, std::list<B> (or set for that matter.
Is there a built-in stl way to do this?
A map element is defined as a map::value_type, and the type of it is a pair<A,B>. first is the key and second is the value. You can write a functor to extract second from a value_type, and copy that in to a vector (or a list, or whatever you want.) The best way to do the copying is to use transform, which does just what its name implies: it takes a value of one type and transforms it to a different type of value.
Here's a complete working example:
#include <cstdlib>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
using namespace std;
typedef map<unsigned, string> MyMap;
MyMap my_map;
struct get_second : public std::unary_function<MyMap::value_type, string>
{
string operator()(const MyMap::value_type& value) const
{
return value.second;
}
};
int main()
{
my_map[1] = "one";
my_map[2] = "two";
my_map[3] = "three";
my_map[4] = "four";
my_map[5] = "five";
// get a vector of values
vector<string> my_vals;
transform(my_map.begin(), my_map.end(), back_inserter(my_vals), get_second() );
// dump the list
copy( my_vals.begin(), my_vals.end(), ostream_iterator<string>(cout, "\n"));
}
EDIT:
If you have a compiler that supports C++0x lambdas, you can eliminate the functor entirely. This is very useful for making code more readable and, arguable, easier to maintain since you don't end up with dozens of little one-off functors floating around in your codebase. Here's how you would change the code above to use a lambda:
transform(my_map.begin(), my_map.end(), back_inserter(my_vals), [](const MyMap::value_type& val){return val.second;} );
There's nothing built in, no. It's simple enough to write your own function, though: Iterate over the map. The iterator will give you a pair<A, B>. Add each second value to the result list.
You can't just "get" such a list because there is no pre-existing list stored anywhere in the guts, but you can build one:
typedef std::map<A,B> myMapType;
myMapType myMap;
std::list<B> valueList;
for (myMapType::const_iterator it=myMap.begin(); it!=myMap.end(); ++it) {
valueList.push_back( it->second );
}
Or if you really like the more STL way:
class GetSecond {
template<typename T1, typename T2>
const T2& operator()( const std::pair<T1,T2>& key_val ) const
{ return key_val.second; }
};
typedef std::map<A,B> myMapType;
myMapType myMap;
std::list<B> valueList;
std::transform(myMap.begin(), myMap.end(), std::back_inserter(valueList),
GetSecond());
One of many "built-in" ways is of course the most obvious one. Just iterate over all pair elements, which are ordered by key (pair::first), and add the value (pair::second) to a new container, which you can construct with the correct capacity to get rid of excess allocations during the iteration and adding.
Just a note: std::list is seldom the container you actually want to be using. Unless, of course, you really, really do need its specific features.
Sure.
std::list<B> list;
std::for_each(myMap.begin(), myMap.end(), [&](const std::pair<const A, B>& ref) {
list.push_back(ref.second);
});
If you don't have a C++0x compiler, first you have my sympathies, and second, you will need to build a quick function object for this purpose.
You can use boost's transform_iterator: http://www.boost.org/doc/libs/1_64_0/libs/iterator/doc/transform_iterator.html
struct GetSecond {
template <typename K, typename T>
const T& operator()(const std::pair<K, T> & p) const { return p.second; }
template <typename K, typename T>
T& operator()(std::pair<K, T> & p) const { return p.second; }
};
template <typename MapType>
auto begin_values(MapType& m) -> decltype(boost::make_transform_iterator(m.begin(), GetSecond())) {
return boost::make_transform_iterator(m.begin(), GetSecond());
}
template <typename MapType>
auto end_values(MapType& m) -> decltype(boost::make_transform_iterator(m.end(), GetSecond())) {
return boost::make_transform_iterator(m.end(), GetSecond());
}
template <typename MapType>
struct MapValues {
MapType & m;
MapValues(MapType & m) : m(m) {}
typedef decltype(begin_values(m)) iterator;
iterator begin() { return begin_values(m); }
iterator end() { return end_values(m); }
};
template <typename MapType>
MapValues<MapType> get_values(MapType & m) {
return MapValues<MapType>(m);
}
int main() {
std::map<int, double> m;
m[0] = 1.0;
m[10] = 2.0;
for (auto& x : get_values(m)) {
std::cout << x << ',';
x += 1;
}
std::cout << std::endl;
const std::map<int, double> mm = m;
for (auto& x : get_values(mm)) {
std::cout << x << ',';
}
std::cout << std::endl;
}

std::map default value

Is there a way to specify the default value std::map's operator[] returns when an key does not exist?
While this does not exactly answer the question, I have circumvented the problem with code like this:
struct IntDefaultedToMinusOne
{
int i = -1;
};
std::map<std::string, IntDefaultedToMinusOne > mymap;
No, there isn't. The simplest solution is to write your own free template function to do this. Something like:
#include <string>
#include <map>
using namespace std;
template <typename K, typename V>
V GetWithDef(const std::map <K,V> & m, const K & key, const V & defval ) {
typename std::map<K,V>::const_iterator it = m.find( key );
if ( it == m.end() ) {
return defval;
}
else {
return it->second;
}
}
int main() {
map <string,int> x;
...
int i = GetWithDef( x, string("foo"), 42 );
}
C++11 Update
Purpose: Account for generic associative containers, as well as optional comparator and allocator parameters.
template <template<class,class,class...> class C, typename K, typename V, typename... Args>
V GetWithDef(const C<K,V,Args...>& m, K const& key, const V & defval)
{
typename C<K,V,Args...>::const_iterator it = m.find( key );
if (it == m.end())
return defval;
return it->second;
}
C++17 provides try_emplace which does exactly this. It takes a key and an argument list for the value constructor and returns a pair: an iterator and a bool.: http://en.cppreference.com/w/cpp/container/map/try_emplace
The C++ standard (23.3.1.2) specifies that the newly inserted value is default constructed, so map itself doesn't provide a way of doing it. Your choices are:
Give the value type a default constructor that initialises it to the value you want, or
Wrap the map in your own class that provides a default value and implements operator[] to insert that default.
The value is initialized using the default constructor, as the other answers say. However, it is useful to add that in case of simple types (integral types such as int, float, pointer or POD (plan old data) types), the values are zero-initialized (or zeroed by value-initialization (which is effectively the same thing), depending on which version of C++ is used).
Anyway, the bottomline is, that maps with simple types will zero-initialize the new items automatically. So in some cases, there is no need to worry about explicitly specifying the default initial value.
std::map<int, char*> map;
typedef char *P;
char *p = map[123],
*p1 = P(); // map uses the same construct inside, causes zero-initialization
assert(!p && !p1); // both will be 0
See Do the parentheses after the type name make a difference with new? for more details on the matter.
There is no way to specify the default value - it is always value constructed by the default (zero parameter constructor).
In fact operator[] probably does more than you expect as if a value does not exist for the given key in the map it will insert a new one with the value from the default constructor.
template<typename T, T X>
struct Default {
Default () : val(T(X)) {}
Default (T const & val) : val(val) {}
operator T & () { return val; }
operator T const & () const { return val; }
T val;
};
<...>
std::map<KeyType, Default<ValueType, DefaultValue> > mapping;
More General Version, Support C++98/03 and More Containers
Works with generic associative containers, the only template parameter is the container type itself.
Supported containers: std::map, std::multimap, std::unordered_map, std::unordered_multimap, wxHashMap, QMap, QMultiMap, QHash, QMultiHash, etc.
template<typename MAP>
const typename MAP::mapped_type& get_with_default(const MAP& m,
const typename MAP::key_type& key,
const typename MAP::mapped_type& defval)
{
typename MAP::const_iterator it = m.find(key);
if (it == m.end())
return defval;
return it->second;
}
Usage:
std::map<int, std::string> t;
t[1] = "one";
string s = get_with_default(t, 2, "unknown");
Here is a similar implementation by using a wrapper class, which is more similar to the method get() of dict type in Python: https://github.com/hltj/wxMEdit/blob/master/src/xm/xm_utils.hpp
template<typename MAP>
struct map_wrapper
{
typedef typename MAP::key_type K;
typedef typename MAP::mapped_type V;
typedef typename MAP::const_iterator CIT;
map_wrapper(const MAP& m) :m_map(m) {}
const V& get(const K& key, const V& default_val) const
{
CIT it = m_map.find(key);
if (it == m_map.end())
return default_val;
return it->second;
}
private:
const MAP& m_map;
};
template<typename MAP>
map_wrapper<MAP> wrap_map(const MAP& m)
{
return map_wrapper<MAP>(m);
}
Usage:
std::map<int, std::string> t;
t[1] = "one";
string s = wrap_map(t).get(2, "unknown");
One workaround is to use map::at() instead of [].
If a key does not exist, at throws an exception.
Even nicer, this also works for vectors, and is thus suited for generic programming where you may swap the map with a vector.
Using a custom value for unregistered key may be dangerous since that custom value (like -1) may be processed further down in the code. With exceptions, it's easier to spot bugs.
Expanding on the answer https://stackoverflow.com/a/2333816/272642, this template function uses std::map's key_type and mapped_type typedefs to deduce the type of key and def.
This doesn't work with containers without these typedefs.
template <typename C>
typename C::mapped_type getWithDefault(const C& m, const typename C::key_type& key, const typename C::mapped_type& def) {
typename C::const_iterator it = m.find(key);
if (it == m.end())
return def;
return it->second;
}
This allows you to use
std::map<std::string, int*> m;
int* v = getWithDefault(m, "a", NULL);
without needing to cast the arguments like std::string("a"), (int*) NULL.
Pre-C++17, use std::map::insert(), for newer versions use try_emplace(). It may be counter-intuitive, but these functions effectively have the behaviour of operator[] with custom default values.
Realizing that I'm quite late to this party, but if you're interested in the behaviour of operator[] with custom defaults (that is: find the element with the given key, if it isn't present insert a chosen default value and return a reference to either the newly inserted value or the existing value), there is already a function available to you pre C++17: std::map::insert(). insert will not actually insert if the key already exists, but instead return an iterator to the existing value.
Say, you wanted a map of string-to-int and insert a default value of 42 if the key wasn't present yet:
std::map<std::string, int> answers;
int count_answers( const std::string &question)
{
auto &value = answers.insert( {question, 42}).first->second;
return value++;
}
int main() {
std::cout << count_answers( "Life, the universe and everything") << '\n';
std::cout << count_answers( "Life, the universe and everything") << '\n';
std::cout << count_answers( "Life, the universe and everything") << '\n';
return 0;
}
which should output 42, 43 and 44.
If the cost of constructing the map value is high (if either copying/moving the key or the value type is expensive), this comes at a significant performance penalty, which would be circumvented with C++17's try_emplace().
If you have access to C++17, my solution is as follows:
std::map<std::string, std::optional<int>> myNullables;
std::cout << myNullables["empty-key"].value_or(-1) << std::endl;
This allows you to specify a 'default value' at each use of the map. This may not necessarily be what you want or need, but I'll post it here for the sake of completeness. This solution lends itself well to a functional paradigm, as maps (and dictionaries) are often used with such a style anyway:
Map<String, int> myNullables;
print(myNullables["empty-key"] ?? -1);
Maybe you can give a custom allocator who allocate with a default value you want.
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map;
With C++20 it is simple to write such getter:
constexpr auto &getOrDefault(const auto &map, const auto &key, const auto &defaultValue)
{
const auto itr = map.find(key);
return itr == map.cend() ? defaultValue : itr->second;
}
Here is a correct approach that will conditionally return a reference if the caller passes in an lvalue reference to the mapped type.
template <typename Map, typename DefVal>
using get_default_return_t = std::conditional_t<std::is_same_v<std::decay_t<DefVal>,
typename Map::mapped_type> && std::is_lvalue_reference_v<DefVal>,
const typename Map::mapped_type&, typename Map::mapped_type>;
template <typename Map, typename Key, typename DefVal>
get_default_return_t<Map, DefVal> get_default(const Map& map, const Key& key, DefVal&& defval)
{
auto i = map.find(key);
return i != map.end() ? i->second : defval;
}
int main()
{
std::map<std::string, std::string> map;
const char cstr[] = "world";
std::string str = "world";
auto& ref = get_default(map, "hello", str);
auto& ref2 = get_default(map, "hello", std::string{"world"}); // fails to compile
auto& ref3 = get_default(map, "hello", cstr); // fails to compile
return 0;
}
If you would like to keep using operator[] just like when you don't have to specify a default value other than what comes out from T() (where T is the value type), you can inherit T and specify a different default value in the constructor:
#include <iostream>
#include <map>
#include <string>
int main() {
class string_with_my_default : public std::string {
public:
string_with_my_default() : std::string("my default") {}
};
std::map<std::string, string_with_my_default> m;
std::cout << m["first-key"] << std::endl;
}
However, if T is a primitive type, try this:
#include <iostream>
#include <map>
#include <string>
template <int default_val>
class int_with_my_default {
private:
int val = default_val;
public:
operator int &() { return val; }
int* operator &() { return &val; }
};
int main() {
std::map<std::string, int_with_my_default<1> > m;
std::cout << m["first-key"] << std::endl;
++ m["second-key"];
std::cout << m["second-key"] << std::endl;
}
See also C++ Class wrapper around fundamental types