在c++中实现容器

Implement Container in c++

本文关键字:实现 c++      更新时间:2023-10-16

我想实现一个容器,其中包含最大的20个解决方案。如果容器包含20个解决方案,任何添加的解决方案只有在

时才被接受。

1) new_value <容器中最差值>

如果new_value已经在容器中(并且1)保存),则memcmp(new_assign, assign, assignment_size) != 0

则删除最差解。(包括int数组)对于所有的解,assignment_size是相同的。

struct Solution {
  double value;
  int *assignment;
  int assigment_size;
};

实现这个结构最简单的方法是什么?你可以使用STL的一些容器吗?

好的,谢谢。我希望这是正确的。它试图保持列表通过插入排序,这样更容易检查,然后你可以删除最后一个元素。

struct Solution {
  double power_peak;
  int *assignment;
  int size;
  ~Solution() { delete[] assignment; }
};

class Container {
  list<Solution> Solutions;
  uint max_size;
  double worst_solution;
public:
  Container (uint size)
  {
    max_size = size;
  }
  void addSolution(Solution s)
  {
    list<Solution>::iterator insert_position = Solutions.begin();
    while (insert_position != Solutions.end() && (*insert_position).power_peak < s.power_peak)
    {
      if ((*insert_position).power_peak == s.power_peak && memcmp((*insert_position).assignment, s.assignment, s.size) == 0)
      {
        return;
      }
      ++insert_position;
    }
    Solutions.insert(insert_position, s);
    if (Solutions.size() > max_size)
    {
      Solutions.pop_back();
    }
    worst_solution = (*(--(Solutions.end())))->power_peak;
  }
  double getWorst()
  {
    return worst_solution;
  }
};

注意:我假设您的解决方案是由您发布的Solution结构描述的。

最简单的解决方案是将std::array<Solution, 20>封装在自定义容器包装器中。

你应该这样写:

class SolutionsSequence
{
public:
    // in a function to add a solution to the sequence, you should
    // implement the criteria to decide which solution is worse
private:
    std::array<Solution, 20> solutions_;
};

除此之外,你不应该在c++中使用memcpy。考虑使用std::copystd::copy_n

还可以考虑使用std::vector来分配任务,然后您可以摆脱assignment_size