[英]How do I initialize an empty array of objects in C++?
我正在嘗試創建Contact類的對象的空數組。 從一個空數組開始,我想在AddrBook.cpp中創建一個函數以將Contact對象添加到對象數組,稱為addressBook。
我可以在AddrBook.h中正確初始化數組嗎?
如何檢查Contact對象是否存在於特定索引處?
AddrBook.cpp
#include "AddrBook.h"
namespace address_book_test
{
const int CAPACITY = 5;
void AddrBook::addContact(Contact& itemToAdd) // Add Contact to the AddrBook (using Contact object)
{
for (int i = 0; i < CAPACITY; i++)
{
if (/*Contact object does not exist at i*/)
{
/*Add Contact object*/
return;
}
}
return;
}
...
}
AddrBook.h
#ifndef ADDR_BOOK_H
#define ADDR_BOOK_H
#include <fstream>
using namespace std;
#include "Contact.h"
namespace address_book_test
{
class AddrBook
{
public:
static const int CAPACITY = 5;
// CONSTRUCTOR
AddrBook() { used = 0; }
// Modification Member Functions
void addContact(Contact& itemToAdd); // Add Contact to the AddrBook (using Contact object)
...
private:
static Contact addressBook[CAPACITY]; // The array used to store Contact objects
int used; // How much of addressBook is used
};
}
#endif
Contact.cpp
#ifndef CONTACT_H
#define CONTACT_H
#include <fstream>
using namespace std;
#include "Address.h"
#include "Name.h"
namespace address_book_test
{
class Contact
{
public:
// Constructor
Contact(string inLastName = "",
string inFirstName = "",
string inStreetAddress = "",
string inCity = "",
string inState = "",
string inZip = "",
string inPhone = "",
string inEmail = "",
string inBirthday = "",
string inPictureFile = "")
{
Name(inLastName, inFirstName);
Address(inStreetAddress, inCity, inState, inZip);
setPhone(inPhone);
setEmail(inEmail);
setBirthday(inBirthday);
setPictureFile(inPictureFile);
}
...
private:
Name fullName;
Address fullAddress;
string phone;
string email;
string birthday;
string pictureFile;
};
}
#endif
不要使用數組,請使用:
std::vector<Contact> addressBook;
代替
static Contact addressBook[CAPACITY];
您是否真的需要將其定義為靜態?
使用vector時,您不需要變量“ used”。 如果您想知道您有多少個聯系人,只需要寫
addressBook.size();
現在,如果您要查找特定的聯系人,可以使用find:
if(find(addressBook.begin(), addressBook.end(), my_contact) != addressBook.end()){
...
}
您有一個名為“ used”的變量,所以我想您想使用該變量來跟蹤數組中有多少個位置被填充,那么當您填充數組中的另一個空間時,只需增加該變量,然后可以通過執行以下操作來檢查該點是否已被使用:if(i> = used){}您只需要記住該數組從索引0開始,並且當數組被填充時,您使用的變量為1,因此總是比上一次填充的索引高一個。
如果要減少應用程序的內存占用量,可以使用call_once初始化矢量,這是在第一次向地址簿中添加元素時
std::vector<Contact> addressBook;
void AddContact(string Contact) {
std::call_once(onceFlag, [this] { this->addressBook.reserve(1000); cout << "size Reserved" << endl; });
addressBook.push_back(Contact);
}
“保留大小”僅會出現一次
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.