mercredi 28 février 2018

Subtraction of iterators for unordered_set does not work

Trying to find the index of an element in unordered set. Found that subtraction (operator '-') of iterators as one way of doing it.

vector<int> twoSum(vector<int>& nums, int target) 
{
    unordered_set<int> comp; 
    vector<int> res;
    for(int i = 0; i<nums.size(); i++)
    {
        //unordered_set<int>::iterator it = comp.find(nums[i]);
        if (comp.find(nums[i])!=comp.end())
        {
            //int pos = distance(comp.begin(), comp.find(nums[i]));
            auto pos = comp.find(nums[i]) - comp.begin();
            res.push_back((int)pos);
            res.push_back(i);
        }
        comp.insert(target-nums[i]);
    }
    return res;
}

But I get compile error on line with auto pos:

no match for 'operator-' (operand types are 'std::unordered_set<int>::iterator {aka std::__detail::_Node_iterator<int, true, false>}' and 'std::unordered_set<int>::iterator {aka std::__detail::_Node_iterator<int, true, false>}')

Have included iostream, iterator and unordered_set. Please advice. Thanks

Aucun commentaire:

Enregistrer un commentaire