मैट पीटर्ससन के लिए वेक्टर की प्रतिलिपि बनाने के स्पष्टीकरण के लिए धन्यवाद, यह काम लगता है। यहां कोड स्निपसेट:सी ++ में बाइनरी फ़ाइल में वेक्टर को सही तरीके से कैसे लिखना है?
#include <iostream>
#include <string.h>
#include <vector>
#include <fstream>
using namespace std;
class Student
{
private:
char m_name[30];
int m_score;
public:
Student()
{
}
Student(const Student& copy)
{
m_score = copy.m_score; //wonder why i can use this statment as
strncpy(m_name, copy.m_name, 30); //declare it private
}
Student(const char name[], const int &score)
:m_score(score)
{
strncpy(m_name, name, 30);
}
void print() const
{
cout.setf(ios::left);
cout.width(20);
cout << m_name << " " << m_score << endl;
}
};
int main()
{
vector<Student> student;
student.push_back(Student("Alex",19));
student.push_back(Student("Maria",20));
student.push_back(Student("muhamed",20));
student.push_back(Student("Jeniffer",20));
student.push_back(Student("Alex",20));
student.push_back(Student("Maria",21));
{
Student temp[student.size()];
unsigned int counter;
for(counter = 0; counter < student.size(); ++counter)
{
temp[counter] = student[counter];
}
ofstream fout("data.dat", ios::out | ios::binary);
fout.write((char*) &temp, sizeof(temp));
fout.close();
}
vector<Student> student2;
ifstream fin("data.dat", ios::in | ios::binary);
{
fin.seekg(0, ifstream::end);
int size = fin.tellg()/sizeof (Student);
Student temp2[size];
fin.seekg(0, ifstream::beg);
fin.read((char*)&temp2, sizeof(temp2));
int counter;
for(counter = 0; counter <6; ++counter)
{
student2.push_back(temp2[counter]);
}
fin.close();
}
vector<Student>::iterator itr = student2.begin();
while(itr != student2.end())
{
itr->print();
++itr;
}
return 0;
}
लेकिन मुझे अतिथि यह तरीका विशाल स्मृति और बोझिल बर्बाद कर देगा। शायद मैं इसे श्रीमान ओसेलॉट और अन्य सुझाव के साथ लिखने पर विचार करूंगा। उत्तर के लिए सभी को धन्यवाद।
मानक संकेत: 'g ++ -Wall -g' के साथ संकलित करें, कोई चेतावनी नहीं दिए जाने तक अपना कोड सुधारें, इसे डीबग करने के लिए' gdb' और 'valgrind' का उपयोग करना सीखें। –
अच्छी तरह से मैं टर्मिनल संकलित तकनीक के साथ अभी तक उपयोग नहीं किया जा रहा है। मुझे लगता है मुझे इसे किसी भी तरह सीखना चाहिए। उत्तर के लिए धन्यवाद। – dchochan
फिर, 'मेक' का उपयोग करना सीखें और अपना सरल 'मेकफ़ाइल' –