std::string allElementsIntoString (const Container& container, char between);
is to create a string of all the elements of container
with the char between
between all of them (but not at the end of the string). This is working fine. Now I want to add a third parameter which will be a lambda function that will transform the elements to some other type first, and then carry out the above. This works too, as the second use of allElementsIntoString
shows, but the third use of allElementsIntoString
crashes when I suddenly use a global variable in the lambda function. I cannot figure out why this case does not work. Am I missing something here?
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <type_traits>
#include <list>
#include <map>
template <typename Container>
inline std::string allElementsIntoString (const Container& container, char between) {
std::ostringstream ss;
for (const typename Container::value_type& x : container)
ss << x << between;
std::string singleString = ss.str();
singleString.pop_back(); // Removing the last 'between' character at the end.
return singleString;
}
template <typename Container, typename F>
inline std::string allElementsIntoString (const Container& container, char between, const F& f) {
std::list<typename std::result_of<F(typename Container::value_type)>::type> list(container.size());
std::transform (container.begin(), container.end(), list.begin(), f);
return allElementsIntoString (list, between);
}
const std::map<int, std::string> map = {
{1, "apple"}, {2, "hello"}, {3, "hi"}, {4, "orange"}, {5, "potato"}
};
int main() {
const std::list<int> numbers = {1,2,3,4,5};
std::cout << allElementsIntoString (numbers, '#') << '\n'; // Works fine.
std::cout << allElementsIntoString (numbers, '#',
[](int x)->double {return 2.5 * x;}) << '\n'; // Works fine.
std::cout << allElementsIntoString (numbers, '#',
[](int x)->std::string {map.find(x)->second;}) << '\n'; // Why the crash here???
}
Tested on GCC 4.9.2 and Visual Studio 2015.
Aucun commentaire:
Enregistrer un commentaire