2010-07-24 69 views
0

我試圖在C++中嵌入IntSetArray它編譯得很好,但結果是錯誤的第一次300是好的,其他數字在零以下某些非常奇怪的數字.e.g -8231313這樣的事情) 什麼是錯的?它是代碼IntSetArray在C++中的實現

#include <iostream> 
using namespace std; 
int quantity=10; 
class Set 
{ 
private : 
    int n,*x; 
public: 
    Set(int maxval){ 
     x=new int[quantity+1]; 
     n=0; 
     x[0]=maxval; 

    } 
    int size(){ return n;} 
    void insert(int t){ 

     for (int i=0;x[i]<t;i++) 
     { 

       if (x[i]==t) 
        return ; 
       for (int j=n;j>=i;j--) 
        x[j+1]=x[j]; 
       x[i]=t; 
     } 

       n++; 




    } 

    void display() 
    { 
      for (int i=0;i<n;i++){ 
       cout<<x[i]<<" "<<"\n"; 
      } 
    } 



}; 

int main(){ 

    Set s(300); 
    s.insert(123); 
    s.insert(45); 
    s.insert(89); 
    s.insert(50); 
    s.insert(13); 
    s.insert(19); 
    s.display(); 

    return 0; 
} 

回答

1

想想你第一次嘗試插入東西會發生什麼。 x[0]包含300和t,你要插入的東西,是123

insert方法的第一條語句是這樣的:

 for (int i=0;x[i]<t;i++) 

for循環的增量ixi個元素小於t。但是x的第0個元素是300,它不小於123,所以循環從不執行。由於在構造函數中你只初始化了第一個元素x,其餘的元素都有垃圾值,所以不會改變。

我認爲你很可能不希望第二個循環進入第一個循環。看起來您試圖對外部循環做的是找到x中的第一個位置,其中值大於或等於t,然後內部循環將所有內容向下移動並插入t。那麼你應該做的是:

void insert(int t){ 

    int i; // Declare this outside the first loop so that it 
      // remains accessible afterwords 

    for (i=0;x[i]<t;i++) 
    { 
     // Do nothing; the whole point is to increment i 
    } 

    // Now i contains the first index of x where x[i] >= t 
    // So now do the shift and insert: 

    if (x[i]==t) 
     return ; 

    for (int j=n;j>=i;j--) 
     x[j+1]=x[j]; 

    x[i]=t; 
    n++; 
} 

不同的,並有可能更容易理解,這樣寫的:

 int i; 
    for (i=0;x[i]<t;i++) 
    { 
     // Do nothing; the whole point is to increment i 
    } 

是這樣的:

 int i = 0; 
    while (x[i] < t) ++i; 
0

爲什麼不使用一個std::set<int>