std :: set和比较器的数组

布兰登·泰勒·拉斯利

我试图弄清楚为什么当您访问std::set命名为asdf的数组时此代码无法编译如果没有尝试使用getItem函数,则代码将编译,但是,如果您尝试访问asdf的元素(例如本例中的索引0),则会编译该代码。编译器将抛出此错误。

main.cpp(21): error C2440: 'return': cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>> &'
      with
      [
          _Kty=test *
      ]
main.cpp(21): note: Reason: cannot convert from 'const std::set<test *,test::compare,std::allocator<_Kty>>' to 'const std::set<test *,std::less<_Kty>,std::allocator<_Kty>>'
      with
      [
          _Kty=test *
      ]
main.cpp(21): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

这是示例:

#include <set>

struct test {
    int idx;
    struct compare {
        bool operator()(const test* a, const test* b) {
            return a->idx < b->idx;
        }
    };
};


class asdf123 {
public:
    asdf123() {

    }

    const std::set<test*>& getItem() const
    {
        return asdf[0];
    }

private:
    typedef std::set<test*, test::compare> stuffType[100];
    stuffType asdf;
};

int main() {
    asdf123 a;
    return 0;
}

没有比较器,代码可以正常工作。

songyuanyao

std::set<test*, test::compare>并且std::set<test*>是differnet类型,并且不能从一个隐式转换为另一个,这就是编译器抱怨的原因。

std::set有两个默认的模板参数,因此std::set<test*, test::compare>

std::set<test*, test::compare, std::allocator<test*>> 

并且std::set<test*>

std::set<test*, std::less<test*>, std::allocator<test*>>

你可能会改变的返回类型getItem()const std::set<test*, test::compare>&解决这个问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

std :: set不同的比较器进行插入和排序

C + + std :: set与基于时间的比较器?

std::set 比较器函数如何工作?

无法使用std :: sort和自定义比较器对数组进行排序

“ Flattening” std :: set <std :: string>用于存储和比较?

std :: multiset定义用于插入和比较的比较器

std :: set_intersection和迭代器

自定义std :: set比较器-找不到匹配的[...]

使用自定义比较器的std :: set操作

std::tie 用于减少比较和字符数组

std :: function和std :: function的比较

容器使用 std::set 和多个比较标准

std::set 插入器不尊重自定义比较器。(可能的编译器错误?)

std :: min / std :: max作为模板比较器

std :: multiset比较器无法编译

std :: priority_queue中的比较器

std :: map是否分配其比较器?

std :: sort与自定义比较器

如何使用自定义比较器初始化 std::set 类数据成员

使用带有自定义构造函数的std :: set自定义比较器

如何在C ++中使用自定义比较器创建std :: set?

std :: is_sorted和严格较少的比较?

比较键和值std :: maps

不能对 std::set<std::string, std::less<>> 使用用户提供的比较函数

是否存在带有shared_ptr键的std :: set(或std :: map)STL比较器,该键提供基于值的查找?std :: owner_less到底做什么?

比较用std :: bind创建的std :: function

std :: vector的std :: vector的比较函数

比较std :: tuple_element和decltype(std :: get)时std :: is_same返回false

为非数组重载std :: begin()和std :: end()