【问题标题】:C++ - match and replace element by value in custom data type vectorC++ - 在自定义数据类型向量中按值匹配和替换元素
【发布时间】:2018-07-04 18:46:23
【问题描述】:

我有一个包含不同组数据的向量。如果我将一个组的新数据插入到向量中,它应该用相同组号的新数据替换旧数据。对于此特定示例,std::replace 给出错误std::replace': no matching overloaded function found

#include <iostream>
#include <vector>
#include <algorithm>

class data
{
    public:
        int group;
        bool condition;
        int time;
        friend bool operator==(const data& lhs, const data& rhs);
        data(int g, bool c, int t) 
        {
            group = g;
            condition = c;
            time = t;
        }
};

bool  operator==(const data& lhs, const data& rhs)
{
    return lhs.group == rhs.group;
}
int main(int argc, char**)
{
    data info_1(10, true , 1);
    data info_2(20, true, 1);
    data info_3(10, false, 4);

    std::vector<data> data_vector;

    data_vector.push_back(info_1);
    data_vector.push_back(info_2);

    std::replace(data_vector.begin(), data_vector.end(), data_vector ,info_3);

    std::cout << "vector size: " << data_vector.size() << "\n";
    for (int i = 0; i < data_vector.size(); i++)
    {
        std::cout << "group number: " << data_vector[i].group << std::boolalpha << " condition: " << data_vector[i].condition << "\n";
    }
    system("pause");
    return 0;
}

【问题讨论】:

  • 这里有什么特殊原因需要使用矢量而不是地图吗?
  • 错误是什么?
  • @neo, 'std::replace': no matching overloaded function found
  • 至于错误,应在问题正文中发布附加信息,而不是在 cmets 中。
  • std::replace_if(data_vector.begin(), data_vector.end(), [&amp;info_3](auto&amp;&amp;el) {return el.getGroup() == info_3.getGroup(); }, info_3);

标签: c++ algorithm vector


【解决方案1】:

根据https://en.cppreference.com/w/cpp/algorithm/replacestd::replace()的第三个参数是const T&amp; old_value。您正在传递整个向量。这就是你得到no matching overloaded function found的原因。

【讨论】:

    【解决方案2】:

    您应该使用std::map,其中组是键,其余数据是值。

    这样,当您插入地图时,会添加一个新项目,除非其组号已经存在,然后它会替换现有项目。

    class data
    {
        public:
            bool condition;
            int time;
            friend bool operator==(const data& lhs, const data& rhs);
            data(bool c, int t) 
            {
                condition = c;
                time = t;
            }
    };
    

    然后使用std::map&lt;int, Data&gt; 作为容器。

    您还可以实现一个包装类,将std::map&lt;int, Data&gt; 作为私有成员,实现插入和迭代(可能还有删除等),然后您可以在它之外使用ExtendedData 或其他实现正如你最初实现Data 一样。

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多