Home > Software engineering >  How do I access a struct value that is in a set?
How do I access a struct value that is in a set?

Time:12-04

I am learning to code in c and I am learning to use sets currently, with the code (I will not use the specific code because of the length but will use an example) it wants me to use a struct and a set and with the things that needs to be done I need to be able to ​access and edit a variable in said struct while iterating through the set.

Here is an example of what I am trying to do:

#include <iostream>
#include <set>

using namespace std;

struct myStruct
{
    int testVal;
    int exVal;
};

int main()
{
    set<myStruct> tst;
    myStruct struc;
    
    struc.testVal = 10;
    struc.exVal = 5;

    tst.insert(struc);
    
    struc.testVal = 1;
    struc.exVal = 7;
    
    tst.insert(struc);
    
    for (set<myStruct>::iterator it = tst.begin(); it != test.end(); it  )
    {
        if (*it.testVal >= *it.exVal)
        {
            //do something
        }
    }
    
    return 0;
}

but whenever I try to do something like this it always gives me a lot of errors. (This is an example so what is trying to be done may seem like a pointless reason to try to do this) One of the main errors is 'std::set<[struct name]>::iterator {aka struct std::_Rb_tree_const_iterator<[struct name]>' has no member named '[struct value name]'

(anything in square brackets is not part of the error but dependent on what is in the code)

in the case of this example I put here the error would say:

error: 'std::set<myStruct>::iterator {aka struct std::_Rb_tree_const_iterator<myStruct>' has no member named 'testVal'

So how do I extract a value from a struct inside of a set using an iterator, and even possibly change it?

CodePudding user response:

std::set ensures it's elements are unique by having them in order. By default, that uses <. You don't have a < for myStruct, nor do you make a set with a different order.

The simplest fix would be to add

bool operator< (const myStruct & lhs, const myStruct & rhs) {
    return std::tie(lhs.testVal, lhs.exVal) < std::tie(rhs.testVal, rhs.exVal);
}

You may have to #include <tuple> for that.

even possibly change it?

You can't modify elements of a set, because that might change the order. To change it you have to take it out of the set, and put the new value in.

auto node = tst.extract(it);
// modify node.value()
tst.insert(node);
  •  Tags:  
  • c
  • Related