c++ - Value Type from Arbitrary Iterator in Template Function -
i trying retrieve value type iterator parameter. how that? googled , see iterator_trait features, couldn't figure out how implement on function. iterator templated t can take either integers or float numbers, , on following function trying iterate through container of either integers or float numbers, , store them, depending on value type, new vector container.
to summarize, how value type information arbitrary iterator
template<typename t> void merge_function(t begin, t mid, t end) { vector<auto> left_half (begin, mid); left_half.push_back(infinite); vector<auto> right_half (mid+1, end); right_half.push_back(infinite); }
update: trying sort of in-place merge sort.
vector<int> numbers = {5, 6, 3, 4, 1, 2, 7, 13, -6, 0, 3, 1, -2}; vector<int> l_half(numbers.begin(), numbers.end());
this works, try similar thing on following
template<typename t> void practice(t begin, t end) { auto length = end - begin; auto mid = length/2; typedef typename std::iterator_traits<t>::value_type value_type; vector<value_type> l_half(begin, mid); vector<value_type> r_half(mid+1, end); r_half.push_back(10000); }
so in main function call
practice(numbers.begin(), numbers.end());
and @ first including following
#include <iostream> using namespace std; #include <algorithm> #include <vector> #include <iterator> template<typename t> void practice(t begin, t end);
but in line vector l_half(begin, mid);
i getting error
/~~/main.cpp:105:14: no matching constructor initialization of 'vector<int>'
i using macbook air, latest version.
typedef typename std::iterator_traits<t>::value_type value_type; std::vector<value_type> left_half(begin, mid); ...
you can in c++11:
typedef typename std::remove_reference<decltype(*begin)>::type value_type;
that work lazily implemented iterator classes don't have value_type
definition.
if, reason, don't have actual iterator work with, iterator type, more general form this:
typedef typename std::remove_reference<decltype(*std::declval<t>())>::type value_type;
Comments
Post a Comment