C++类实例

1 c++

我正在做intro c ++的家庭作业,但我被困了.

Account *GetAccount(int an);

int main()
{
Account *a1,*a2,*b1;
a1=GetAccount(123);
a2=GetAccount(456);
b1=GetAccount(123);
if(a1==b1)
  cout<<"YES"<<endl;
else
  cout<<"NO"<<endl;
Run Code Online (Sandbox Code Playgroud)

GetAccount方法应该检查实例是否已经存在具有相同的帐号,如果存在,则返回该实例.

我能想到的唯一方法是创建帐户数组并搜索帐户,如果它不存在,则在数组中插入新帐户.如果存在,则返回指向数组的指针.

这种方法对我来说似乎并不高效,还有其他方法吗?

Igo*_*kon 8

是.而不是数组,使用地图.它在空间方面更有效,而且几乎同样快.

您可以使用STL并将您的帐户保存在std :: map中,这些变体之一:

map<int, Account> or
map<int, Account*>
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,您将帐户保留在地图中,在第二种情况下,您将指针保留在帐户中,并负责创建/删除.哪种变体更合适?这取决于您创建/初始化帐户的方式.


关于STL地图使用的简短教程

当你将指针保留在地图中时,我会对此案进行解释.

这是您声明地图的方式:

map<int, Account*> accounts;
Run Code Online (Sandbox Code Playgroud)

这是您可以向地图添加新帐户的方法:

int account_id = 123; // or anything else

Account* account = new Account(...paramters for the constructor...)
// any additional code to initialize the account goes here

accounts[account_id] = account;  // this adds account to the map
Run Code Online (Sandbox Code Playgroud)

这是检查account_id帐户是否在地图中的方法:

if (accounts.find(account_id) != accounts.end()) {
  // It is in the map
} else {
  // it is not in the map
}
Run Code Online (Sandbox Code Playgroud)

这是您从地图获取指向帐户的指针:

Account* ifoundit = accounts[account_id];
Run Code Online (Sandbox Code Playgroud)

最后,在程序结束的某个地方,您需要清理地图并删除所有帐户对象.即使没有清理,该程序也能正常工作,但重要的是要在自己之后进行清理.我把这作为练习留给你:)找到如何迭代地图的所有元素,并适当地应用删除.