Say I have a vector of some struct type; I’m trying to iterate over all instances of a specific member within this struct. Because I want to be general in my approach I’d like to use a std::function<> object to specify which piece of information I’d like to access. I build 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 a struct S, and a 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 the numbers 0..10, their squares and their cubes. The method seems to work, however I get a memory dump, right after printing “— end of part 1 —“, saying: “double free or corruption”. I’ve ran the code through gdb, and it seems somethings going wrong in the memory management of the std::function<> member in Access<>, but I can’t figure what precisely breaks this code. I’ve build a similar construct with read-only access, and it works flawlessly.
What am I doing wrong here?
(using g++-4.7.2)
Cheers, Johan
The problem is that vector
Acontains 11 entries, while vectorQcontains only 10.std::transform<>expects the target range to be at least as big as the source range.A simple fix would be to change the definition of
Qas follows: