练习了一下vector推入类的简单例子,结果循环不了,求大神看一下咋回事
程序代码:
#pragma once #include<cstring> #include<iostream> using std::cout; using std::endl; class person { public: person(const char * first, const char * second); person(const person & p1); person & operator =(const person & p1); bool operator <(const person & p1) const; void show() const; void initname(const char * first, const char * second); ~person(); private: char * firstname; char * secondname; };
程序代码:
#include "StdAfx.h" #include "person.h" person::person(const char * first, const char * second) { initname(first,second); } person::person(const person & p1) { initname(p1.firstname,p1.secondname); } person & person::operator =(const person & p1) { delete [] firstname; delete [] secondname; initname(p1.firstname,p1.secondname); return *this; } bool person::operator <(const person & p1) const { if(strcmp(this->firstname,p1.firstname)<0||((strcmp(this->firstname,p1.firstname)==0)&&(strcmp(this->secondname,p1.secondname)<0))) return 1; return 0; } void person::show() const { cout<<firstname<<" "<<secondname<<endl; } void person::initname(const char * first, const char * second) { unsigned int len=strlen(first)+1; this->firstname=new char(len); strcpy_s(firstname,len,first); len=strlen(second)+1; this->secondname=new char(len); strcpy_s(secondname,len,second); } person::~person(void) { delete [] firstname; delete [] secondname; }
程序代码:
// vestor01.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" //#include<iostream> #include"person.h" #include<vector> using std::vector; using std::cin; int main() { vector<person> people; const size_t maxlength=50; char firstname[maxlength]; char secondname[maxlength]; while(1) { cout<<"请输入姓(或enter终止):"; cin.getline(firstname,maxlength ,'\n'); if(strlen(firstname)==0) break; cout<<"请输入名:"; cin.getline(secondname,maxlength ,'\n'); //people.push_back(person(firstname,secondname)); person p(firstname,secondname); people.push_back(p); } cout<<endl; auto iter=people.begin(); if(iter!=people.end()) iter++->show(); return 0; }