I was expecting the second assert in the following to pass. I’m asking for your help.
Edit: It didn’t work when I had poss everywhere instead of poss_a in some places.
#include <vector>
#include <cassert>
class Sampler
{
public:
std::vector<int*> poss;
std::vector<int*>::const_iterator poss_it;
Sampler(std::vector<int*> poss_a) : poss(poss_a), poss_it(poss.begin())
{
assert( (poss[0]) == (*poss_it) ); //passes
}
};
int main()
{
int someInt;
std::vector<int*> poss_a(1, &someInt);
Sampler sampler(poss_a);
assert( ((sampler.poss)[0]) == (*(sampler.poss_it)) ); //passes now
return 0;
}
The
poss_it(poss.begin())line in your initializer list is pulling an iterator from the poss that is the input to the constructor, not the one that is a field of the class.This is a scope issue. When you’re in the constructor, it’s fine, because your iterator is a pointer to the input to the function. When you leave the constructor however, it’s pointing to the same spot in memory but now you have no idea what’s at that location.
You should change the name of the input variable in the constructor. You want one that does this:
Whereas what your current one is doing is this: