2016-04-23 156 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