Broccoli Broccoli - 2 months ago 8
C++ Question

C++ access set via iterator

I have the following code:

struct voxel
{
int x, y, z;
};
std::set<std::set<voxel>> regions;

std::set<std::set<voxel>>::iterator regions_it;
std::set<voxel>::iterator voxel_it;
for (regions_it = regions.begin(); regions_it != regions.end(); regions_it++){
for (voxel_it = regions_it->begin(); voxel_it != regions_it->end; voxel_it++){
if (condition){
struct voxel v = { 1, 2, 3 };
regions_it->insert(v);
}
}
}


Just assume that "condition" is a boolean. I have trouble specifically with
regions_it->insert(v)
. The arrow (->) is marked as error. I tried with
regions_it.insert(v)
but it doesn't work either.

regions_it
should be a pointer that points to a set of voxels if I'm not mistaken, but how can I call the insert method?

I'm still unfamiliar to C++. Would be nice if someone can help me out.

Answer

You don't have braces around:

if (condition)
             struct voxel v = { 1, 2, 3 };
             regions_it->insert(v);

so v is out of scope when you try to use it.

You also didn't put parenthesis on end here:

    for (voxel_it = regions_it->begin(); voxel_it != regions_it->end; voxel_it++){

However, the main problem is that you cannot change the elements in a set, as they are used for sorting the contents of the set and if you changed them directly, the set may no longer function as intended. Because of that, dereferencing an iterator on a set returns a const reference to its contents. A const std::set doesn't have an insert method.

Comments