2014-03-28 24 views
1

我已經使這個代碼存儲了以二進制序列輸入的每個位1的位置。該程序的輸出不是它所期望的。我得到的10100的輸出是0x7fff9109be00。下面是代碼:一個C++程序,存儲每個位1的位置在二進制序列中

#include <iostream> 
#include <bitset> 
using namespace std; 

    int main() 
    { 
    bitset <5> inpSeq; 
    int x = 0; 
    int xorArray[x]; 
    unsigned int i; 
    cout << "Enter a 5-bit sequence: \n"; 
    cin >> inpSeq; 
    for (i = 0; i < inpSeq.size(); i++) 
    { 
     if (inpSeq[i] == 1) 
     { 
     x = x+1; 
     xorArray[x] = i; 
     } 
    } 
    cout << xorArray << "\n"; 
    } 

更新爲清楚:我腦子裏想的是什麼是「清點< < xorArray」將位打印1的位置。

+4

您希望我們去猜測什麼是需要的,否則你」是否會在午夜告訴我們? –

+2

我想,您正在打印陣列的內存地址。 – gravitas

+0

對不起,如果我還不夠清楚。輸出是xorArray,它應該是序列中位1的位置列表。所以如果我輸入了10100,輸出應該是2和4. –

回答

2
cout << xorArray << "\n"; 

這並不打印xorArray的元素;它打印它的地址。

您必須重複(「環比」)是:

for (auto x : xorArray) 
    cout << x << ' '; 
cout << '\n'; 

你的另一個問題是,你要使用可變長度數組,不存在C++。改用矢量。

現在it gives you your desired output

#include <iostream> 
#include <bitset> 
#include <vector> 

using namespace std; 

int main() 
{ 
    bitset<5> inpSeq("10111"); 

    std::vector<int> xorArray; 

    for (unsigned int i = 0; i < inpSeq.size(); i++) { 
     if (inpSeq[i] == 1) 
      xorArray.push_back(i); 
    } 

    for (auto x : xorArray) 
     cout << x << ' '; 
    cout << '\n'; 
} 

如果你不使用C++ 11無論出於何種原因,您可以執行最後的循環中的傳統方式:

for (std::vector<int>::const_iterator it = xorArray.begin(), 
             end = xorArray.end(), 
    it != end; ++it) { 
    cout << *it << ' '; 
} 

還是天真方法:

for (unsigned int i = 0; i < xorArray.size(); i++) 
    cout << xorArray[i] << ' '; 
+0

我不熟悉迭代的概念。請你提供一個鏈接或簡單的解釋?! –

+1

@MohamedAhmed:不,你不是。你已經做到了。它意味着循環一些東西。您的C++書籍確實涵蓋了它。 –

+1

@MohamedAhmed認爲迭代器是指向容器元素的指針變量:'.begin()'給出第一個元素,'.end()'在容器結束後給出*。 – OMGtechy

2

我對你想要達到的目標有點不清楚,但我認爲以下可能會有所幫助。

#include <iostream> 
#include <bitset> 
#include <list> 

using namespace std; 

int main() { 
    bitset<5> inpSeq; 
    unsigned int i; 
    list<int> xorList; 
    cout << "Enter a 5-bit sequence: \n"; 
    cin >> inpSeq; 

    for (i = 0; i < inpSeq.size(); ++i) { 
     if (inpSeq[i] == 1) { 
      xorList.push_back(i); 
     } 
    } 

    for (list<int>::iterator list_iter = xorList.begin(); 
     list_iter != xorList.end(); list_iter++) 
    { 
     cout << *list_iter << endl; 
    } 

    return 0; 
} 

我之所以使用列表是因爲您提到想要存儲1位的位置。該名單被用作這些職位的容器,以防您在程序的另一個點需要他們。

原始代碼的一個問題是,您爲變量'x'賦值0。當您聲明xorArray [x]時,這意味着您本質上創建了一個長度爲0的數組。這是不正確的語法。它看起來像你實際上試圖在運行時動態分配數組的大小。這需要指針的不同語法和用法。該列表允許您爲遇到的每個1位增長數據結構。

另外,還可以不通過使用

cout << xorArray << endl 

要打印的陣列中的第一個元素的存儲器地址打印的陣列的值,因此,xorArray [0]。無論何時想要打印數據結構(如列表或數組)的值,都需要遍歷整個結構並逐個打印值。這是上述代碼中第二個用於()循環的目的。

最後,存儲的值與0索引一致。如果你想從1開始的頭寸,你必須使用

xorList.push_back(i+1); 

希望這有助於!

+0

我想使用循環中存儲的位置對這些位置指向的位進行XOR運算。我的最終目標是線性反饋移位寄存器。你的代碼是完美的,但我真的需要知道我的錯在哪裏。 –

+0

我已經更新了我的答案,以解釋我的代碼以及原始帖子所需的更改。 – dgp

+0

這是一個很好的答案。 –

相關問題