c++ - 从对象返回函数c ++返回一个新对象
问题描述
我正在开发一个程序,该程序根据集合论相交由 2 个对象表示的两个集合。每个对象可以包含 0 个或多个元素。功能是给定的,不能只改变里面的实现。
在我的代码中,我检查调用对象和第二个对象(otherIntSet)是否为空,如果是,它们在空集处相交。如果它们包含任何元素,我会检查 data[] 中的元素是否包含在 otherIntSet 中。我使用“返回 IntSet();” 但我得到的只是空集。
IntSet IntSet::intersect(const IntSet& otherIntSet) const
{
if ( (this->isEmpty() ) && (otherIntSet.isEmpty() ) )
{
return IntSet();
}
else
{
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
IntSet().add(data[i]);
cout << IntSet();
}
}
}
}
我不确定如何返回正确创建的新对象,以便实际保存添加到其中的元素。谢谢
解决方案
在这个循环中:
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
IntSet().add(data[i]);
cout << IntSet();
}
}
您在每次迭代中创建一个临时IntSet
对象,然后呢?消失?那么有什么意义呢?相反,您想要的是拥有一个对象,将其填满并返回:
IntSet result;
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
result.add(data[i]);
}
}
return result;
顺便说一句,您的第一个条件可能应该是“或”,这是比“和”更好(更广泛)的检查:
if ( (this->isEmpty() ) || (otherIntSet.isEmpty() ) )
你可以到处玩,甚至最终得到这样的东西:
IntSet IntSet::intersect(const IntSet& otherIntSet) const
{
IntSet result;
if (!otherIntSet.isEmpty()) // <-- note negation
{
// We don't need to check if this->isEmpty(), the loop
// won't loop anyway if it is. And in case it isn't
// it saves us unnecessary call. Assuming that "isEmpty()"
// is derived from "used".
for (int i = 0; i < used; ++i)
{
if (otherIntSet.contains(data[i]) )
{
result.add(data[i]);
}
}
}
return result;
}
推荐阅读
- java - 契约测试在 Spring Boot 中因初始化错误而失败
- hibernate - JSON 响应和 POJO 具有不同大小写的列名
- r - RNAseq:将 RNA 标识符转换为基因
- java - 以特定时间间隔刷新令牌以供 API 使用
- django - 将更改迁移到数据库时遇到问题 - Python/Django
- linux-kernel - 如何理解 DSDT 表中定义的 ACPI _OSC 方法
- java - 为什么 Java websocket 服务器这么慢?
- vector - 如何在 VHDL 中测试矢量多路复用器的所有情况?
- java - 如何根据多个变量制作随机二维数组?
- mysql - mysql显示表中的数据最大值和总和