C++从二叉搜索树中检索对象问题求助
Hey there! Let’s figure out why your Account transactions aren’t sticking after retrieving from the binary search tree (BST)—this is a common gotcha with object storage in trees, so let’s break down the most likely culprits:
1. You’re storing/retrieving copies of Account objects, not references/pointers
The biggest issue here is usually that your BST is holding copies of your Account instances instead of direct references to the original objects. Here’s what happens:
- When you insert an Account into the BST, if you pass it by value (instead of a pointer or reference), the tree creates a duplicate copy.
- When you deposit money, you might be modifying the original Account, but the BST still has its own copy.
- Then when you retrieve from the BST, you get another copy—so any withdrawal you do on this copy doesn’t affect the original (or the tree’s stored copy).
Fix this by:
- Storing pointers (e.g.,
Account*in C++) or object references (in Java/C#) in your BST nodes instead of value-type Account objects. - Ensuring your
retrievefunction returns a reference or pointer to the actual Account stored in the tree, not a new copy.
Example of a corrected retrieve function (C++):
// Returns a reference to the original Account in the BST Account& BST::retrieve(int accountID) { Node* current = root; while (current != nullptr) { if (accountID == current->account.getID()) { return current->account; // Return reference, not copy } else if (accountID < current->account.getID()) { current = current->left; } else { current = current->right; } } // Handle account not found case here throw std::runtime_error("Account not found"); }
2. Your BST’s retrieve logic is fetching the wrong Account
If your BST uses a key (like account ID) to organize nodes, double-check your comparison logic. A tiny bug here (e.g., using < instead of <= in a comparison) could cause retrieve to return a different Account than the one you deposited into.
Verify this by:
- Printing the account ID (or a unique identifier like memory address/hash code) before depositing, after depositing, and after retrieving. If the identifiers don’t match, your retrieve function is pulling the wrong object.
3. Accidental object duplication in transaction logic
Double-check your deposit/withdraw/transfer methods to make sure they’re modifying the Account instance directly, not creating a new copy and modifying that instead. For example, if your deposit method returns a new Account with updated balance instead of modifying the current instance, that would break persistence in the BST.
Quick test to confirm:
After depositing into an Account, retrieve it immediately and print its balance. If the balance is still 0, you’re definitely working with a copy instead of the original object.
内容的提问来源于stack exchange,提问作者paul

