-1

I am trying to overload assignment operator to allow set being assigned to an unordered_set. And I have run into trouble, please help.

set<int> operator=(unordered_set<int> us)
{
    set<int> s;
    for(auto val:us) { s.insert(val); }
    return s;
}

I get the following error:

error: ‘std::set<int> operator=(std::unordered_set<int>)’ must be a nonstatic member function
 set<int> operator=(unordered_set<int> us)

This function is a global function, don't know why g++ thinks it is a static function. As a dumb solution, I add auto qualifier to the function.

set<int> auto operator=(unordered_set<int> us)
{
    set<int> s;
    for(auto val:us) { s.insert(val); }
    return s;
}

I get the following error:

error: two or more data types in declaration of ‘operator=’
 set<int>  auto operator=(unordered_set<int> us)

Any ideas how do I get around this? I have tried searching a solution for this but in vain.

  • 1
    The error is quite clear: You can not have non-member assignment operators. And even if it was allowed, think about what you know about operator overloading, or [read some good books about it](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), a non-member binary operator (like assignment) needs to take *two* arguments: The left-hand-side, and the right-hand-side. However, it's not allowed for assignment. – Some programmer dude May 20 '18 at 16:40

1 Answers1

1

The error is quite clear here. You cannot have a "global" assignment operator as you desire. It would have to be a member function of the unordered_set if you wanted to do it like this. Declare this function as a member of the class unordered_set.

std::set<T> std::unordered_set<T>::operator=(std::unordered_set<T> us)
{
    set<T> s;
    for(auto val:us) { s.insert(val); }
    return s;
}

Even so, this probably isn't the best solution. Why not make a global function that converts an unordered_set to a set without the operator?

std::set<int> unorderedToOrdered(std::unordered_set<int> us)
{
    set<int> s;
    for(auto val:us) { s.insert(val); }
    return s;
}

Then, you can just call it like this

// some unordered set containing values
std::unordered_set<int> uos;

// some set we want to convert to
std::set<int> s;

s = unorderedToOrdered(uos);
samuelnj
  • 1,627
  • 1
  • 10
  • 19