在c++中实现容器
Implement Container in c++
我想实现一个容器,其中包含最大的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::copy
或std::copy_n
。
还可以考虑使用std::vector
来分配任务,然后您可以摆脱assignment_size
。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的