【问题标题】:unordered_set to set conversion using overloading operator=unordered_set 使用重载 operator= 设置转换
【发布时间】:2018-05-20 16:36:05
【问题描述】:

我正在尝试重载赋值运算符以允许将集合分配给 unordered_set。我遇到了麻烦,请帮忙。

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

我收到以下错误:

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

这个函数是全局函数,不知道为什么g++会认为是静态函数。作为一个愚蠢的解决方案,我在函数中添加了自动限定符。

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

我收到以下错误:

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

任何想法如何解决这个问题?我曾尝试为此寻找解决方案,但徒劳无功。

【问题讨论】:

  • 错误很明显:不能有非成员赋值运算符。即使它被允许,想想你对运算符重载的了解,或者read some good books about it,非成员二元运算符(如赋值)需要采用 两个 参数: , 和右手边。但是,它不允许分配。

标签: c++ operator-overloading unordered-set


【解决方案1】:

这里的错误很明显。您不能根据需要拥有“全局”赋值运算符。如果您想这样做,它必须是unordered_set 的成员函数。将此函数声明为 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;
}

即便如此,这可能不是最好的解决方案。为什么不创建一个全局函数,在没有运算符的情况下将 unordered_set 转换为 set

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

那么,你可以这样称呼它

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

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

s = unorderedToOrdered(uos);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多