0

I have an unordered set of pair of integers maintained by the hash of the first value of pair. insert() function of unordered set returns an iterator to the currently inserted element. Now is there any way to use that iterator and update the second value of the inserted pair as it is not used for computing hash as I mentioned in the comment

 struct hasher
    {
        public:
        size_t operator()(const pair<int, int> & a) const {
            return std::hash<int>()(a.first); }
    };

    struct comparer
    {
        public:
        bool operator()(const pair<int, int>& a, const pair<int, int>& b) const {
            if (a.first == b.first)
                return true;
            else
                return false;
        }
    };
    unordered_set<pair<int, int> , hasher, comparer> st;
int main() {
    auto tmp = st.insert({1,2}); // this returs a pair of iterator pointing to currently inserted element and boolean value representing whether inserted or not
    //(*(tmp.first)).second = 3; <- I want this part to work

}
  • You can't. Keys are not to be mutated. – NathanOliver Jun 12 '20 at 14:38
  • 2
    Use `std::unordered_map` instead. Take the first entry of the pair as key and the second as value. You can update the value but not the key. – n314159 Jun 12 '20 at 14:38
  • Can this be done using unordered_set? second value is not used for hash computation – SANTHOS KUMAR Jun 12 '20 at 14:40
  • Why would you want to do it with `unordered_set`? The approach with `unordered_map` is superior. – n314159 Jun 12 '20 at 14:44
  • Values in `std::(unordered_)set` are immutable. The only way would be to remove this element and insert another, with changed value. Compiler doesn't care if some parts of structure are not used for calculating hash. – Yksisarvinen Jun 12 '20 at 14:45
  • Side note: the body of `comparer::operator()` can be reduced to just `return a.first == b.first;`. The conditional is just obfuscation. – cdhowie Jun 12 '20 at 14:45
  • @NathanOliver I wonder if it would work with a custom type where the second value is declared `mutable`? (Though this seems like abuse of `mutable`.) – cdhowie Jun 12 '20 at 14:46
  • @cdhowie That would work. – NathanOliver Jun 12 '20 at 14:49
  • I was trying to implement [this](https://stackoverflow.com/questions/12761315/random-element-from-unordered-set-in-o1#:~:text=if%20already%20in%20the%20unordered,return%20the%20value%20in%20(5)) , as author mentioned of using unordered set – SANTHOS KUMAR Jun 12 '20 at 15:01
  • 1
    I dont see what your links has to do with your question. – n314159 Jun 12 '20 at 16:00

0 Answers0