我正在编写一个程序来使用插入排序对办公室员工的向量进行排序。我在插入员工记录时面临疑问。疑点是:-
- 在评论#1 中,为什么我使用指向 cOffice 类的指针向量?为什么我不能只使用简单对象的向量?
- 在评论#2 中,为什么我使用
new
关键字在运行时创建内存?为什么我不能像将对象复制到其他对象一样复制一个类实例(连同参数)?
代码和注释如下:-
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class cPerson
{
private:
string firstname,lastname;
int age;
public:
cPerson(string fn,string ln,int a) // constructor to input the firstname, lastname and age of the person
{
firstname=fn;
lastname=ln;
age=a;
}
void displaycPerson()
{
cout<<"First Name = "<<firstname<<"\n";
cout<<"Last Name = "<<lastname<<"\n";
cout<<"Age = "<<age<<"\n";
}
string getLastName()
{
return lastname;
}
};
class cOffice
{
private:
vector<cPerson*> v; // Comment#1 and the alteranate code is: vector<cPerson> v;
int nElem;
public:
cOffice(int max)
{
v.resize(max);
nElem=0;
}
~cOffice()
{
for(int i=0;i<nElem;i++) // no use of the destructor if the above code is implemented
delete v[i];
}
void insertRec(string fn1, string ln1, int a1) // inserting the record
{
v[nElem] = new cPerson(fn1,ln1,a1); // Comment#2 and the alteranate code is: v[nElem] = cPerson(fn1,ln1,a1);
nElem++;
}
void InsertionSort()
{
int compare,pivot;
for(pivot=1;pivot<nElem;pivot++)
{
cPerson* temp = v[pivot];
compare=pivot;
while(compare>0&&v[compare-1]->getLastName()>=temp->getLastName())
{
v[compare]=v[compare-1];
compare--;
}
v[compare] = temp;
}
}
void display()
{
for(int i=0;i<nElem;i++)
v[i]->displaycPerson();
}
};
int main(void)
{
cOffice obj(10);
obj.insertRec("Evans", "Patty", 24);
obj.insertRec("Adams", "Henry", 63);
obj.insertRec("Yee", "Tom", 43);
obj.insertRec("Smith", "Lorraine", 37);
obj.insertRec("Hashimoto", "Sato", 21);
obj.insertRec("Stimson", "Henry", 29);
obj.insertRec("Velasquez", "Jose", 72);
obj.insertRec("Lamarque", "Henry", 54);
obj.insertRec("Vang", "Minh", 22);
obj.insertRec("Creswell", "Lucinda", 18);
obj.display();
obj.InsertionSort();
obj.display();
return 0;
}
显然,其余代码将通过替换->
和.
删除所有取消引用操作符进行相应更改*
。
如果我进行了问题中提到的所有编辑,程序会显示错误,如下所示:
In member function 'void std::vector<_Tp, _Alloc>::resize(std::vector<_Tp, Alloc>::size_type, std::vector<_Tp, _Alloc>::value_type) [with _Tp = cPerson; _Alloc = std::allocator<cPerson>; std::vector<_Tp, _Alloc>::size_type = unsigned int; std::vector<_Tp, _Alloc>::value_type = cPerson]':
exp.cpp:40:16: error: no matching function for call to 'cPerson::cPerson()'
exp.cpp:40:16: note: candidates are:
exp.cpp:11:2: note: cPerson::cPerson(std::string, std::string, int)
exp.cpp:11:2: note: candidate expects 3 arguments, 0 provided
exp.cpp:5:7: note: cPerson::cPerson(const cPerson&)
exp.cpp:5:7: note: candidate expects 1 argument, 0 provided