How can one initialize static map, where value is std::unique_ptr?
static void f()
{
static std::map<int, std::unique_ptr<MyClass>> = {
{ 0, std::make_unique<MyClass>() }
};
}
Of course this does not work (copy-ctor of std::unique_ptr is deleted).
Is it possible?
The Problem is that constructing from std::initializer-list copies its contents. (objects in std::initializer_list are inherently const).
To solve your problem: You can initialize the map from a separate function...
std::map<int, std::unique_ptr<MyClass>> init(){
std::map<int, std::unique_ptr<MyClass>> mp;
mp[0] = std::make_unique<MyClass>();
mp[1] = std::make_unique<MyClass>();
//...etc
return mp;
}
And then call it
static void f()
{
static std::map<int, std::unique_ptr<MyClass>> mp = init();
}
See it Live On Coliru
Writing bespoke crestion code seems boring and gets in the way of clarity.
Here is reasonably efficient generic container initialization code. It stores your data in a temporary std::array like an initializer list does, but it moves out instead of making it const.
The make_map takes an even number of elements, the first being key the second value.
template<class E, std::size_t N>
struct make_container_t{
std::array<E,N> elements;
template<class Container>
operator Container()&&{
return {
std::make_move_iterator(begin(elements)),
std::make_move_iterator(end(elements))
};
}
};
template<class E0, class...Es>
make_container_t<E0, 1+sizeof...(Es)>
make_container( E0 e0, Es... es ){
return {{{std::move(e0), std::move(es)...}}};
}
namespace details{
template<std::size_t...Is, class K0, class V0, class...Ts>
make_container_t<std::pair<K0,V0>,sizeof...(Is)>
make_map( std::index_sequence<Is...>, std::tuple<K0&,V0&,Ts&...> ts ){
return {{{
std::make_pair(
std::move(std::get<Is*2>(ts)),
std::move(std::get<Is*2+1>(ts))
)...
}}};
}
}
template<class...Es>
auto make_map( Es... es ){
static_assert( !(sizeof...(es)&1), "key missing a value? Try even arguments.");
return details::make_map(
std::make_index_sequence<sizeof...(Es)/2>{},
std::tie( es... )
);
}
This should reduce it to:
static std::map<int, std::unique_ptr<MyClass>> bob =
make_map(0, std::make_unique<MyClass>());
... barring typos.
Live example.
another way to do this is to use a lambda. it's the same as using a separate function but puts the map's initialisation closer to the action. In this case I've used a combination of an auto& and decltype to avoid having to name the type of the map, but that's just for fun.
Note that the argument passed into the lambda is a reference to an object that has not yet been constructed at the point of the call, so we must not reference it in any way. It's only used for type deduction.
#include <memory>
#include <map>
#include <utility>
struct MyClass {};
static auto& f()
{
static std::map<int, std::unique_ptr<MyClass>> mp = [](auto& model)
{
auto mp = std::decay_t<decltype(model)> {};
mp.emplace(0, std::make_unique<MyClass>());
mp.emplace(1, std::make_unique<MyClass>());
return mp;
}(mp);
return mp;
}
int main()
{
auto& m = f();
}
Here's another way. In this case we've passed a temporary into the lambda and relied on copy elision/RVO.
#include <memory>
#include <map>
#include <utility>
struct MyClass {};
static auto& f()
{
static auto mp = [](auto mp)
{
mp.emplace(0, std::make_unique<MyClass>());
mp.emplace(1, std::make_unique<MyClass>());
return mp;
}(std::map<int, std::unique_ptr<MyClass>>{});
return mp;
}
int main()
{
auto& m = f();
}
And yet another way, using a lambda capture in a mutable lambda.
#include <memory>
#include <map>
#include <utility>
struct MyClass {};
static auto& f()
{
static auto mp = [mp = std::map<int, std::unique_ptr<MyClass>>{}]() mutable
{
mp.emplace(0, std::make_unique<MyClass>());
mp.emplace(1, std::make_unique<MyClass>());
return std::move(mp);
}();
return mp;
}
int main()
{
auto& m = f();
}
Related
I want to hide details of the lambda function into private part of a class.
I tried to separate the lambda function part from for_each() function.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Sol
{
private:
vector<int> vec = vector<int>{ 1,2,3,4,5 };
int target = 10;
auto lambdaFunc = [=](int& v) { v += target; };
public:
void addConst() {
for_each(vec.begin(), vec.end(), lambdaFunc);
}
void printVec() {
for_each(vec.begin(), vec.end(), [](int v) {cout << v << endl; });
}
};
int main()
{
Sol sol;
sol.addConst();
sol.printVec();
return 0;
}
If I don't separate lambdaFunc from the for_each() function, I got elements of vector printed out.
However, by separating lambdaFunc, I got error message:
error: non-static data member declared 'auto'
Changing auto to static auto didn't solve.
If you have access to c++17 compiler, the best option is to provide a private member function as #VittorioRomeo shown in his answer(which is more straight forward IMO).
c++11 Solution!
Another way(s) is to provide the type for the lambda. You can
either use std::function with some type-erasure cost to define the
type of the lambda.
(See Live)
std::function<void(int&)> lambdaFunc = [=](int& v) { v += target; };
Or, if lambda can be changed to capture less one, that can be stored
into a typed function pointer like follows. In which target will
be passed as the second parameter of the lambda which made the lambda
capture-less. But that need also change of addConst() function.
(See Live)
class Sol
{
private:
std::vector<int> vec{ 1,2,3,4,5 };
// ^^^^^^^^^^^^^^ -> can use just braced-init-list
int target{ 10 };
void(*lambdaFunc)(int&, int) = [](int& v, int tar) { v += tar; };
//^^^^^^^^^^^^^^^^^^^^^^^^^ // fun-pointer type
public:
void addConst()
{
for (auto& element : vec) lambdaFunc(element, target);
}
};
Not sure why you would want to do this. If you really have a valid reason, you can use a private member function instead:
class Sol{
private:
auto lambdaFunc() { return [=](int& v) { v += target; }; }
public:
void addConst() {
for_each(vec.begin(), vec.end(), lambdaFunc());
}
};
I want to set the keys of a std::map using the elements of a std::set (or a std::vector).
Something like the following...
std::set<int> keys = { 3,4,6 };
std::map<int,string> results(keys); // syntax error
Can this be done without explicitly iterating over the set?
You can't. A map is not a set. They're fundamentally different containers, even if the underlying structure is similar.
That said, anything's possible. The range constructor of std::map is linear time if the elements of the range are already sorted, which set guarantees for us. So all you need to do is apply a transformer to every element to produce a new range. The simplest would be to just use something like boost::make_transform_iterator (or roll your own):
template <class K, class F
class V = decltype(std::declval<F&>()(std::declval<K const&>()))::second_type>
std::map<K, V> as_map(std::set<K> const& s, F&& f) {
return std::map<K,V>(
boost::make_transform_iterator(s.begin(), f),
boost::make_transform_iterator(s.end(), f));
}
std::map<int,string> results =
as_map(keys, [](int i){
return std::make_pair(i, std::string{});
});
which if you always will want default initialization, can just reduce to:
template <class V, class K>
std::map<K, V> as_map_default(std::set<K> const& s) {
auto f = [](K const& k) { return std::make_pair(k, V{}); }
return std::map<K,V>(
boost::make_transform_iterator(s.begin(), f),
boost::make_transform_iterator(s.end(), f));
}
std::map<int,string> results = as_map_default<string>(keys);
Can this be done without explicitly iterating over the set?
No. There is no way to know the keys in the set without iterating over it. You may write functions to make it appear as if there is an implicit transformation, but those functions must ultimately iterate the source collection.
A simple way is as follows:
#include <set>
#include <map>
#include <string>
auto build_map(const std::set<int>& source) -> std::map<int,std::string>
{
std::map<int,std::string> results;
for (auto const& i : source) {
results[i];
}
return results;
}
int main()
{
std::set<int> keys = { 3,4,6 };
auto results = build_map(keys);
}
Of course we may templatise if that improves readability:
#include <set>
#include <vector>
#include <unordered_set>
#include <map>
#include <string>
#include <utility>
template<class MappedType, class SourceContainer>
auto build_map(SourceContainer&& source)
{
using source_type = std::decay_t<SourceContainer>;
using key_type = typename source_type::value_type;
std::map<key_type , MappedType> results;
for (auto const& i : source) {
results[i];
}
return results;
}
int main()
{
std::set<int> keys = { 3,4,6 };
auto results = build_map<std::string>(keys);
// also
results = build_map<std::string>(std::vector<int>{3, 4, 6});
results = build_map<std::string>(std::unordered_set<int>{3, 4, 6});
}
I will start from code:
#include <iostream>
#include <vector>
using namespace std;
struct A
{
int color;
A(int p_f) : field(p_f) {}
};
int main ()
{
A la[4] = {A(3),A(5),A(2),A(1)};
std::vector<int> lv = {begin(la).color, end(la).color};//I would like to create vector from specific value from array la
for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it) std::cout << ' ' << *it;
return 0;
}
Generally I would like to create a vector from specific values from array.
As you can see la is A array and I would like to create vector containing not the whole la array, but only color.
vector(int) not vector(A), which vector{3,5,2,1}, so not A, but only int color. It can be done using in C++11 also. Thanks.
This should work.
std::vector<int> lv;
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), [](const A& a){
return a.color;
});
Also here is another way:
Refactor your structure to get color from a method:
struct A
{
int color;
A(int p_f) : color(p_f) {}
int getColor() const {
return color;
}
};
In this case you may use bind:
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::bind(&A::getColor, std::placeholders::_1));
Or you may also use std::mem_fn to method which is a bit shorter (thanks to #Piotr S.):
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::mem_fn(&A::getColor));
Or you may use std::mem_fn to data member. In this case you don't even need to implement a getter method:
std::transform(std::begin(la), std::end(la), std::back_inserter(lv), std::mem_fn(&A::color));
Following may help:
namespace detail
{
using std::begin;
using std::end;
template <typename Container, typename F>
auto RetrieveTransformation(const Container& c, F f)
-> std::vector<std::decay_t<decltype(f(*begin(c)))>>
{
// if `F` return `const T&`, we want `std::vector<T>`,
// so we remove reference and cv qualifier with `decay_t`.
//
// That handles additionally the case of lambda
// The return type of lambda [](const std::string&s) { return s;}
// - is `const std::string` for msvc
// - is `std::string` for for gcc
// (Note that the return type rules have changed:
// see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1048)
using F_Ret = std::decay_t<decltype(f(*begin(c)))>;
std::vector<F_Ret> res;
res.reserve(std::distance(begin(c), end(c)));
for (const auto& e : c)
{
res.push_back(f(e));
}
return res;
}
}
template <typename Container, typename F>
auto RetrieveTransformation(const Container& c, F f)
-> decltype(detail::RetrieveTransformation(c, f))
{
return detail::RetrieveTransformation(c, f);
}
And then use it as
std::vector<int> lv = RetrieveTransformation(la, std::mem_fn(&A::getColor));
// or
// auto lv = RetrieveTransformation(la, [](const A&a){return a.color;});
Live Demo
For example
struct A
{
static vector<int> s;
};
vector<int> A::s = {1, 2, 3};
However, my compiler doesn't support initialization list. Any way to implement it easily? Does lambda function help here?
Any way to implement it easily?
There's nothing particularly elegant. You can either copy the data from a static array, or initialise it with the result of a function call. The former might use more memory than you'd like, and the latter needs some slightly messy code.
Boost has a library to make that slightly less ugly:
#include <boost/assign/list_of.hpp>
vector<int> A::s = boost::assign::list_of(1)(2)(3);
Does lambda function help here?
Yes, it can save you from having to name a function just to initialise the vector:
vector<int> A::s = [] {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
return v;
}();
(Strictly speaking, this should have an explicit return type, []()->vector<int>, since the lambda body contains more than just a return statement. Some compilers will accept my version, and I believe it will become standard in 2014.)
I always fear being shot down for initialization ordering here for questions like this, but..
#include <iostream>
#include <vector>
#include <iterator>
struct A
{
static std::vector<int> s;
};
static const int s_data[] = { 1,2,3 };
std::vector<int> A::s(std::begin(s_data), std::end(s_data));
int main()
{
std::copy(A::s.begin(), A::s.end(),
std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Output
1 2 3
Just because you can doesn't mean you should =P
Winning the award for the least efficient way to do this:
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
template<typename T>
std::vector<T> v_init(const T& t)
{
return std::vector<T>(1,t);
}
template<typename T, typename... Args>
std::vector<T> v_init(T&& t, Args&&... args)
{
const T values[] = { t, args... };
std::vector<T> v1(std::begin(values), std::end(values));
return v1;
}
struct A
{
static std::vector<int> s;
};
std::vector<int> A::s(v_init(1,2,3,4,5));
int main(int argc, const char *argv[])
{
std::copy(A::s.begin(), A::s.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Output
1 2 3 4 5
This should puke at compile-time if T and anything in Args... is not type-compliant or type-castable. Of course, if you have variadic templates odds are you also have initializer lists, but it makes for fun brain-food if nothing else.
Write a simple init function for the vector:
vector<int> init()
{
vector<int> v;
v.reserve(3);
v.push_back(1);
v.push_back(2);
v.push_back(3);
return v;
};
vector<int> A::s = init();
You can initialize an std::vector from two pointers
int xv[] = {1,2,3,4,5,6,7,8,9};
std::vector<int> x(xv, xv+(sizeof(xv)/sizeof(xv[0])));
You can even factor this out in a template function:
template<typename T, int n>
std::vector<T> from_array(T (&v)[n]) {
return std::vector<T>(v, v+n);
}
Another idea:
struct A
{
static std::vector<int> s;
};
std::vector<int> A::s;
static bool dummy((A::s.push_back(1), A::s.push_back(2), A::s.push_back(3), false));
I developed a scripting engine that has many built-in functions, so to call any function, my code just went into an if .. else if .. else if wall checking the name but I would like to develop a more efficient solution.
Should I use a hashmap with strings as keys and pointers as values? How could I do it by using an STL map?
EDIT:
Another point that came into my mind: of course using a map will force the compiler not to inline functions, but my inefficient approach didn't have any overhead generated by the necessity of function calls, it just executes code.
So I wonder if the overhead generated by the function call will be any better than having an if..else chain.. otherwise I could minimize the number of comparisons by checking a character at runtime (will be longer but faster).
Whatever your function signatures are:
typedef void (*ScriptFunction)(void); // function pointer type
typedef std::unordered_map<std::string, ScriptFunction> script_map;
// ...
void some_function()
{
}
// ...
script_map m;
m.emplace("blah", &some_function);
// ...
void call_script(const std::string& pFunction)
{
auto iter = m.find(pFunction);
if (iter == m.end())
{
// not found
}
(*iter->second)();
}
Note that the ScriptFunction type could be generalized to std::function</* whatever*/> so you can support any callable thing, not just exactly function pointers.
In C++11 you can do something like this :
This Interface needs only the return type and it takes care of everything else from the caller side.
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <typeinfo>
#include <typeindex>
#include <cassert>
void fun1(void){
std::cout<<"inside fun1\n";
}
int fun2(){
std::cout<<"inside fun2\n";
return 2;
}
int fun3(int a){
std::cout<<"inside fun3\n";
return a;
}
std::vector<int> fun4(){
std::cout<<"inside fun4\n";
std::vector<int> v(4,100);
return v;
}
// every function pointer will be stored as this type
typedef void (*voidFunctionType)(void);
struct Interface{
std::map<std::string,std::pair<voidFunctionType,std::type_index>> m1;
template<typename T>
void insert(std::string s1, T f1){
auto tt = std::type_index(typeid(f1));
m1.insert(std::make_pair(s1,
std::make_pair((voidFunctionType)f1,tt)));
}
template<typename T,typename... Args>
T searchAndCall(std::string s1, Args&&... args){
auto mapIter = m1.find(s1);
/*chk if not end*/
auto mapVal = mapIter->second;
// auto typeCastedFun = reinterpret_cast<T(*)(Args ...)>(mapVal.first);
auto typeCastedFun = (T(*)(Args ...))(mapVal.first);
//compare the types is equal or not
assert(mapVal.second == std::type_index(typeid(typeCastedFun)));
return typeCastedFun(std::forward<Args>(args)...);
}
};
int main(){
Interface a1;
a1.insert("fun1",fun1);
a1.insert("fun2",fun2);
a1.insert("fun3",fun3);
a1.insert("fun4",fun4);
a1.searchAndCall<void>("fun1");
int retVal = a1.searchAndCall<int>("fun3",2);
a1.searchAndCall<int>("fun2");
auto temp = a1.searchAndCall<std::vector<int>>("fun4");
return 0;
}
You can also use Boost.Function and Boost.Bind what even allows you, to some degree, to have map of heterogeneous functions:
typedef boost::function<void, void> fun_t;
typedef std::map<std::string, fun_t> funs_t;
funs_t f;
void foo() {}
void goo(std::string& p) {}
void bar(int& p) {}
f["foo"] = foo;
f["goo"] = boost::bind(goo, "I am goo");
f["bar"] = boost::bind(bar, int(17));
It can be a map of functions of compatible prototypes as well, of course.
Above answers seem to give a complete overview, this regards only your second question:
Map element retrieval by key has O(log n) complexity. Hashmap retrieval by key has O(1) complexity + a little stuff on the side in case of collisions. So if theres a good hash function for your function names, use it. Your implementation will have a standard one. It should be fine.
But be aware, that anything below a hundred elements will not benefit all too much.
The only downside of a hash map is collision. In your case, the hashmap will be relatively static. You know the function names you support. So I advise you to create a simple test case, where you call unordered_map<...>::hash_function with all your keys to make sure that nothing collides. After that, you can forget about it.
A quick google for potential improvements on hash functions got me there:
A fiew good hash functions
Maybe, depending on your naming conventions, you can improve on some aspects of the function.
Well, you can use any_map to store functions with different signatures (but calling it will be messy) and you can use int_map to call functions with a specific signature (looks nicer).
int FuncA()
{
return 1;
}
float FuncB()
{
return 2;
}
int main()
{
// Int map
map<string,int(*)()> int_map;
int_map["A"] = FuncA;
// Call it
cout<<int_map["A"]()<<endl;
// Add it to your map
map<string, void(*)> any_map;
any_map["A"] = FuncA;
any_map["B"] = FuncB;
// Call
cout<<reinterpret_cast<float(*)()>(any_map["B"])()<<endl;
}
I've managed to modify the example from Mohit to work on member function pointers:
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <typeinfo>
#include <typeindex>
#include <cassert>
template <typename A>
using voidFunctionType = void (A::*)(void);
template <typename A>
struct Interface{
std::map<std::string,std::pair<voidFunctionType<A>,std::type_index>> m1;
template<typename T>
void insert(std::string s1, T f1){
auto tt = std::type_index(typeid(f1));
m1.insert(std::make_pair(s1,
std::make_pair((voidFunctionType<A>)f1,tt)));
}
template<typename T,typename... Args>
T searchAndCall(A a, std::string s1, Args&&... args){
auto mapIter = m1.find(s1);
auto mapVal = mapIter->second;
auto typeCastedFun = (T(A::*)(Args ...))(mapVal.first);
assert(mapVal.second == std::type_index(typeid(typeCastedFun)));
return (a.*typeCastedFun)(std::forward<Args>(args)...);
}
};
class someclass {
public:
void fun1(void);
int fun2();
int fun3(int a);
std::vector<int> fun4();
};
void someclass::fun1(void){
std::cout<<"inside fun1\n";
}
int someclass::fun2(){
std::cout<<"inside fun2\n";
return 2;
}
int someclass::fun3(int a){
std::cout<<"inside fun3\n";
return a;
}
std::vector<int> someclass::fun4(){
std::cout<<"inside fun4\n";
std::vector<int> v(4,100);
return v;
}
int main(){
Interface<someclass> a1;
a1.insert("fun3",&someclass::fun3);
someclass s;
int retVal = a1.searchAndCall<int>(s, "fun3", 3);
return 0;
}