2016-09-17 21 views
1

我想要構建一個銀行系統。它要求用戶創建最多10個帳戶對象,然後將它們插入到對象數組中。後來我需要提到某些對象數組中使用被稱爲對象以產生一個預測, 到目前爲止,這是我做了什麼比我上輸入什麼> 10如何檢查對象數組是否有用於我的學校項目的引用對象

  cout << "\nHow many accounts do you wish to crate: \n"; 
     cin >> accounts; 
     for (int i = 0; i < accounts; i++) 
     { 
      cout << "\n>> Enter your details for your Account: " << accCount << " <<" << endl; 
      newAccounts[i] = EnterAccountDetails(); 
      if (newAccounts[i].accNo == 0) 
      { 
       for (int j = i; j < accounts; j++) 
       { 
        newAccounts[j] = newAccounts[j + 1]; 
        accounts-=1; 
       } 
       break; 
      } 
      accCount++; 
     } 
+0

您的代碼段是不完整的查詢更多關於算法庫。你應該編輯它以包含所有相關的代碼,並編輯你的問題,如果可以的話,使用更好的語法。看看你現在擁有的東西,我可以告訴一些非常糟糕的事情發生在'EnterAccountDetails()'上,因爲之後你不得不應用一些醜陋的修復。 –

+0

@CJMki我們可以看到你的EntrAccountDetails()函數代碼嗎? – Chris

+0

@MichaelMcGuire:哎喲真不好意思。我是這個論壇的新手。 –

回答

1

你可以使用std::find,這是做到這一點的功能!

如果您的對象沒有定義operator==,則可以使用帶有lambda的std::find_if

// If you have operator== defined 
auto element = std::find(std::begin(yourArray), std::end(yourArray), elementToFind); 

if (element != std::end(yourArray)) { 
    // Your elementToFind exist in the array! 
    // You can access it with `*element` 
} 

隨着std::find_if

// If don't have operator== defined 
auto element = std::find_if(std::begin(yourArray), std::end(yourArray), [&](auto&& check){ 
    return elementToFind.someProperty == check.someProperty; 
}); 

if (element != std::end(yourArray)) { 
    // Your elementToFind exist in the array! 
    // You can access it with `*element` 
} 

語法[](){ /* return ... */ }被稱爲lambda表達式,它像某種您發送到std::find_if功能,所以它可以比較平等元素的內聯函數。

請注意,您必須包括下面的頭:

#include <algorithm> 

您可以在Algorithms library

+0

@ Guilaume,要使用'find',我們必須包含任何lib軟件包嗎? –

+0

不需要。您只需要從標準庫中包含標題。該庫默認鏈接到您的程序。 –

+0

謝謝,'auto'在那裏做了什麼? –

1

上面看起來很不錯其它致電cin >> accounts。 (你需要限制我可以輸入的內容)。 由於我們無法看到您的EnterAccountDetails()函數,因此您最終得到的是一組對象。你可以通過本地索引號和使用迭代這個對象數組。符號,個別屬性。

for(int i=0, i < accCount, ++i) { 
    if (newAccounts[i].someProperty == someValue) { 
     dostuff(); 
    } 
} 

Customer EnterAccountDetails() { 
    Customer BankAccount; 
    cout << "\n>Enter Bank Account Number (4-digit):\n"; 
    cout << ">If you wish to stop creating new accounts press 0 .." << endl; 
    cin >> BankAccount.accNo; 
    if (BankAccount.accNo == 0) { 
     BankAccount.accNo = NULL; 
     return BankAccount; 
    } else ... 
+0

繼續並將(現在直接在此評論之下)函數定義添加到您的問題。這似乎是好的,但很難閱讀評論。那麼,你的具體問題是什麼? – Chris

+0

'客戶EnterAccount詳細信息() { Customer BankAccount; cout << "\n>輸入銀行帳號(4位數):\ n「; cout << ">如果您想停止創建新帳戶,請按0 ..」<< endl; cin >> BankAccount.accNo; if(BankAccount.accNo == 0) { return BankAccount; } else' –

+0

我一直在試圖弄清楚如何將代碼放入註釋:S,但是錯誤是,如果用戶輸入0到BankAccount.accNo應該返回一個空值到數組並限制數組的大小直到那一點。 –

相關問題