C++의 간단한 문제를 해결하기 위해 고정 된 (최악의 경우) 번호없이 사용자 정의 클래스 유형의 객체 벡터를 사용할 수있는 방법을 이해하고 싶습니다. 사물. 즉사용자 정의 클래스 유형 객체의 벡터 사용
현재 나는 10000 내가 가정 한 기록의 일부 최대 값입니다
vector<grades> students(10000);
을 사용해야합니다. 일부 파일에 더 많은 레코드가 있으면 분명히 충돌합니다.
그래서 아래 코드의 경우, 내 클래스 객체의 벡터를 동적으로 확장하고 내 클래스 변수의 레코드를 읽는 방법. 아래 코드에서 설명한대로 push_back()을 사용할 수 없습니다. 아니면 push_back()을 어떻게 사용할 수 있습니까? 아래
코드 설명해야 - 참고
class grades
{
public:
string mName;
string mSurname;
int mAge;
string mLocation;
int mMarks;
char mGrade;
//void readdata();
void calcgrade();
void showgrade(string name_surname);
};
using namespace std;
int main(int argc,char *argv[])
{
**vector<grades> students(10000);// I do not want to do this but make it dynamic**
ifstream infile;
char c;
int i=0;
int no_of_records=0;
infile.open(argv[1],ios::in);
if(infile.is_open() != true)
{
cerr << "Error opening input data file:" <<argv[1] << "...exiting\n";
exit(-1);
}
while(!infile.eof())
{
infile >> students[i].mName;//Can i use push_back() here and for reading all below entities, to make vector grow dynamically
infile >> students[i].mSurname;
infile >> students[i].mAge;
infile >> students[i].mLocation;
infile >> students[i].mMarks;
i++;
no_of_records++;
}
for(i=0;i<no_of_records;i++)
{
//Do some functions on each object students[i] in the vector
}
}
: - 나는 고정되어 하나의 행에서 엔티티와 엔티티의 다른 유형의 수의 순서 (아래와 같은 항목이 C에서 텍스트 파일을 ++ 읽은 I 알고 있지만 행의 수는 다른 입력 파일에 따라 달라질 수 있습니다) 읽을 수 :
Name1 Surname1 Course1 Marks1
Name2 Surname2 Course2 Marks2
Name3 Surname3 Course3 Marks3
...
...
이 편집 : 코드가 기록 엔티티의 모든 의사 공간의 종류 탭을 처리하기 위해
벡터의 요소를 누르면서, 값을 읽어 다음vector<grades> students;
을 그리고 : 더 이상
while(!infile.eof())
{
grades student;
infile >> student.mName;
infile >> student.mSurname;
infile >> student.mAge;
infile >> student.mLocation;
infile >> student.mMarks;
students.push_back(student);
}
당신은 no_of_records
을 필요로하지 않기 때문에,
while(!infile.eof())
{
c=infile.get();
if(isalnum(c))
{
infile.seekg(-1,ios::cur);
}
if(isalnum(c))
{
grades stud_temp;
infile >> stud_temp.mName;
infile >> stud_temp.mSurname;
infile >> stud_temp.mAge;
infile >> stud_temp.mLocation;
infile >> stud_temp.mMarks;
students.push_back(stud_temp);
}
}
나는 당신의 루프를위한 더 나은 해결책을 가지고있다 : http://ideone.com/hMgoP –
@BenjaminLindley - 그게 전부다. 그것은 작동하지만 논리를 이해할 수 없었다. 디버깅을 시도했지만 로직을 얻을 수 없었습니다. for()에서 코드의 어느 부분이 증분 연산 인 테스트 표현식입니다. 각 레코드 자체의 시작 부분이나 끝과 끝 사이의 공백을 어떻게 처리합니까? – goldenmean
테스트 표현식은 모든 데이터를 읽는 부분입니다 :'inFile >> temp.mName >> temp.mAge etc ...'- 두 가지 기본적인 사실에 의존합니다. 1) istream operator >>는 스트림을 반환합니다. 2) 스트림은 부울 컨텍스트에서 유효성을 테스트 할 수 있습니다. 따라서 데이터를 읽으려고 시도하고 실패하면 (eof 또는 다른 이유로 인해) 조건은 거짓입니다. 읽기가 성공하면 조건은 참입니다. - 증분 작업이 없습니다. 단순히 여백을 건너 뛰는 것만 큼 작업자가 정상적으로 처리하는 공백에 의존하여 추가 공간을 처리합니다. –