Iterator pointing to one structure component in a larger container in C ++ 11 using std :: function object
Let's say I have a vector of some type of structure; I am trying to iterate over all instances of a specific member in this structure. Since I want to be generic in my approach, I would like to use the std :: function <> object to indicate which piece of information I would like to access. I am creating the following template class
#include <iostream>
#include <vector>
#include <iterator>
#include <functional>
#include <algorithm>
#include <cmath>
template <typename SrcList, typename Tgt>
class Access
{
typedef std::function<Tgt &(typename SrcList::value_type &)> func_type;
typedef typename SrcList::iterator src_iterator;
typedef Tgt value_type;
SrcList &source;
func_type f;
public:
Access(SrcList &source_, func_type const &f_):
source(source_), f(f_) {}
class iterator:
public src_iterator,
public std::iterator<std::forward_iterator_tag, value_type>
{
Access const *obj;
public:
iterator(Access const *obj_, src_iterator i):
src_iterator(i),
obj(obj_)
{}
value_type &operator*()
{
return (obj->f)(src_iterator::operator*());
}
};
value_type &operator[](size_t i)
{ return f(source[i]); }
iterator begin()
{ return iterator(this, source.begin()); }
iterator end()
{ return iterator(this, source.end()); }
};
Next, we define the structure S and the main function to test the class
struct S
{
double v[3];
};
std::ostream &operator<<(std::ostream &out, S const &s)
{
return out << s.v[0] << " " << s.v[1] << " " << s.v[2];
}
int main()
{
std::vector<int> A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<S> Q(10);
for (unsigned k = 0; k < 3; ++k)
{
Access<std::vector<S>, double> acc(Q,
[k] (S &s) -> double&
{
return s.v[k];
});
std::transform(A.begin(), A.end(), acc.begin(),
[k] (int i)
{
return pow(i, k+1);
});
for (auto x : Q)
std::cout << x.v[k] << std::endl;
std::cout << "--- end of part " << k << " ---\n";
}
std::cout << std::endl;
for (auto x : Q)
std::cout << x << std::endl;
return 0;
}
this program should print numbers 0..10, their squares and their cubes. This method seems to work, however I get a memory dump right after printing "--- end of part 1 ---", saying "double free or corrupted". I ran the code through gdb and it seems that something is going wrong in the memory management of the std :: function <> element in Access <>, but I can't figure out what exactly is breaking this code. I have built a similar read-only construct and it works flawlessly.
What am I doing wrong here?
(using g ++ - 4.7.2)
Cheers, Johan
source to share