2016-04-23 102 views
1

我目前正在为CS类做一个任务,并且很困惑如何使用子集函数的语法。我仍在编写代码。我感到困惑的是(const Set & other)...(我知道它意味着一组然后是另一组)我只是好奇如何将它与我的代码一起使用。 _numItems和_numItems2是我暗示的地方是否使用(const Set & other)。另外,我可以获得关于如何返回此功能的帮助。所有帮助赞赏!这里是我的代码:C++学习函数语法

bool Set::isSubset(const Set &other) const 
{ 
    for (int i = 0; i < _numItems2; i++) { 
     for (int x = 0; i < _numItems; i++) 
    } 

    return 0; 
} 

// main.cpp中

#include <iostream> 
#include <cassert> 
#include "Set.h" 
using namespace std; 

int main() { 

    Set s1, s2, s3; 

    s1.addElement(7); 
    s1.addElement(3); 
    s1.addElement(5); 
    s2.addElement(3); 
    s2.addElement(5); 
    std::cout << s1.containsElement(286) << endl; 
    std::cout << s1.containsElement(7); 

    return 0; 
} 
+0

的如果作为参考传递的集合包含在调用集中,则函数应该返回true。 例子: 设置1:1 2 3 4 盘2:2 3 因为集1包含2个3,它为你解答:)设置2 – Stephen

+0

感谢这iretuns真实的,实际上,我意识到,我米只是混淆一点点我会写困惑地方说:_numItems2 – jnestor

+0

BOOL设置:: isSubset(常量组&其他)常量 { \t的for(int i = 0;我<_numItemsSet2;我++){ \t \t对(INT N = 0; N <_numItems; N ++){ \t \t \t如果(S1 [I] == S2 [n])的 \t \t \t \t休息; \t \t} \t \t如果(_numItemsSet2 == _numItems) \t \t \t返回假; \t} \t \t return true; – jnestor

回答

1

简单迭代法:

bool Set::isSubset(const Set &other) const 
{ 
    int j = 0; 

    if(other.size() > size()) { 
     return false; 
    } 

    //size() is the function or variable that denotes the number of elements in the set, replace as needed 
    for (int i = 0; i < size(); i++) { 
     //if the j index is greater or equal to the size, all elements were found in order 
     //therefore the set contains every portion of the subset 
     if (j >= other.size()) { 
      return true; 
     } 

     //if the items are the same, advance j index and advance i index by continuing to next iteration of loop 
     if (*this[i] == other[j]) { 
      j++; 
      continue; 
     } 
     //otherwise, if they are not the same reset j index to 0 and start process of finding the subset again 
     else { 
      j = 0; 
     } 
    } 

    //if i reaches the end of the main set and a subset is not found, it must not contain that subset therefore false 
    return false; 
} 

这个回答假设你的类有一个工作[]操作

+0

可能会将'other.size()'移出循环。无论大小如何,都不能成为子集。 – Thomas