c++ - 在 C++ 上的 std::set 中查找并更新自定义对象

标签 c++ c++11

我在我的项目中创建了 2 个自定义结构,每个都有一个 std::set。

struct Subject {
        std::string name;
        std::set<SubjectFrame> frames;

        Subject(std::string subject_name);

        void AddFrame(SubjectFrame &frame);

        bool operator<(const Subject &rhs) const { return (name  < rhs.name);}
        bool operator==(const Subject &rhs) const { return (name == rhs.name);}
};

struct Dataset {
        std::set<Subject> subjects;
        std::map<int, std::vector<Subject> > classification_groups;

        Dataset(const std::string ds_path);

        void AddSubject(Subject &subject);
        void GetDSFromFileSystem(const std::string dataset_path);
        void GetClassificationGroups(int number_of_groups_to_create);
};

每次我想向我的设置“框架”添加一些框架时,我都会调用此函数:

void Dataset::AddSubject(Subject &subject) {
        set<Subject>::iterator it = this->subjects.find(subject);
        if (it != this->subjects.end()) {
                for (Subject fr : this->subjects) {
                        it->AddFrame(fr);
                }
        }   else this->subjects.insert(subject);
}

调用这个函数:

void Subject::AddFrame(SubjectFrame &frame) {
        set<SubjectFrame>::iterator it = this->frames.find(frame);
        if (it != this->frames.end()) {
                if (frame.l_eye_centroid.x != 0) {
                        it->r_eye_centroid = frame.r_eye_centroid;
                        it->l_eye_centroid = frame.l_eye_centroid;
                }
                if (frame.path != "") it->path = frame.path;
                else return;
        }
        else this->frames.insert(frame);
}

因此,添加操作背后的逻辑是:我传递一个对象并检查我的 std::set 中是否已经存在具有该名称的对象。如果是,我用我的参数对象具有的信息更新现有对象,而已经注册的对象没有,如果没有,我插入对象。

当我尝试编译我的程序时出现以下错误:

error: no viable overloaded '=' it->r_eye_centroid = frame.r_eye_centroid;

error: no viable overloaded '=' it->l_eye_centroid = frame.l_eye_centroid;

error: no viable overloaded '=' if (frame.path != "") it->path = frame.path;

error: member function 'AddFrame' not viable: 'this' argument has type 'const Subject', but function is not marked const it->AddFrame(fr);

有人知道是什么原因造成的,我该如何解决这些问题?

最佳答案

对于 std::set,iterator-s 是 const,这是因为它们用作 set 中的键,不应修改以避免任何不一致严格的弱排序。

解决该问题的一种方法是使您要修改的字段可变,但要确保它未在您的set 排序中使用。

关于c++ - 在 C++ 上的 std::set 中查找并更新自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068030/

相关文章:

c++ - 将txt文件保存为变量名

c++ - 元素未在 map 中打印

C++ 错误 : expected primary-expression before ‘.’ token

c++ - 发送接收调用时带有 C++ 字符串的垃圾文本

c++ - 使用 std::bind 和 std::placeholders 的可变模板工厂

c++ - 从 Class<U> 调用 Class<T> 的私有(private)构造函数

c++ - C 和 C++ 的优化工具

c++ - Intel Thread Building Blocks 备选方案和许可

c++ - 如何使用 typeid 来计算指针中数据的类型?

c++ - 为模板化 key 专门化 std::hash