0

I"m writing a method called put() that is suppose to output a map with the correct values. My printing method works but my actual method doesn't make the map correctly. The keys are strings and the values of the map is a set of strings. My method is also of type T to work with other values but its made for strings.

I'm trying to use a nest for each loop to grab the input set and use it for the keys in the map. The next for each loop is iterate through the set and insert the the values at the corresponding keys if the key is not equal too the value. That's where my problem is occurring but I'm not sure how to fix it.

input: set = {"a", "b", "c", "d"}

output: expected --vs-- actual

Key: a Value: b c d --- Key: a Value: b c d

Key: b Value: a c d --- Key: b Value: a b c d

Key: c Value: a b d --- Key: c Value: a b c d

and so on...

void
  put (const Container& c)
  {
    std::map<T, std::set<T>> map;
    std::set<T> set;
    for(auto i : c)
    {
      for(auto j : c)
      {
        if(i != j)   //this is where I think I am wrong
        {
         set.insert(j);
         map[i] = set;
        }      
      }
    }
     //my printing method is here but I left it out for simpler code
  }

int
  main ()
  {
    set<string> v = {"a", "b", "c", "d"};
    manager.put(v);
  }
CamWhis
  • 17
  • 6
  • You never clear `set` between iterations; you only add elements to it, but never remove any. – Igor Tandetnik Apr 19 '20 at 00:44
  • I'm not trying to clear from a set. I am iterating through the set and adding elements to it unless the value to be inserted == the key. then it wont insert a value that is equal to its key. My problem is how to check to see if the second, third, and so on values to be inserted are != to its key – CamWhis Apr 19 '20 at 17:16
  • You add `b` to the variable named `set` on the first iteration through the loop. You never remove any elements from the variable named `set`, so `b` will always be there; you cannot possibly have `{a c d}` in that variable. You need to either clear it between iterations, or move its declaration into the outer loop, so that you start each iteration with an empty set, not the set left over from previous iteration. – Igor Tandetnik Apr 19 '20 at 17:29
  • that helps a lot! thank you – CamWhis Apr 19 '20 at 19:25
  • Also just ran it and it worked! – CamWhis Apr 19 '20 at 19:34

0 Answers0