简体   繁体   English

通过取消引用迭代器将Vector写入文件

[英]Writing Vector to file by dereferencing iterator

I am writing the contents of vector to a file through iterator as fallows 我通过迭代器将vector的内容写入文件

for(vector<Student>::iterator itr=vec.begin();itr!=vec.end();itr++){
    out.write((char*)itr,sizeof *itr);
}

It's giving compile time error as no suitable conversion function exists.But when I dereferenced itr and taken its address as below 由于不存在合适的转换函数,因此出现编译时错误。但是当我取消引用itr并按如下所示获取其地址时

out.write( (char*)&(*itr),sizeof *itr);

its working fine. 它的工作正常。 So why here I can't use itr directly? 那么,为什么在这里我不能直接使用itr? Why I need to dereference it and take its address again? 为什么我需要取消引用并再次使用它的地址?

You can't just byte-by-byte serialise complex objects like this, but your attempt doesn't even try to do that! 您不能像这样逐字节地序列化复杂的对象,但是您甚至没有尝试这样做!

Your first example attempts to take an iterator , cast it to a char* (which is completely nonsensical) then write sizeof(Student) worth of bytes starting at that nonsensical pointer into a file. 您的第一个示例尝试采用一个迭代器 ,将其转换为char* (这完全是荒谬的),然后将从该荒谬的指针开始的价值sizeof(Student)个字节写入文件。

Your second example bypasses the helpful compiler errors telling you about your mistake, and forces the cast. 第二个示例绕过了有用的编译器错误,告诉您有关错误的信息,并强制进行强制转换 Sure, you get a result, but it's a total nonsense result and your program could even crash. 当然,您会得到一个结果,但这完全是胡说八道,程序甚至可能崩溃。

Firstly, you should be attempting to serialise the Student objects, not the iterators that point to them, and secondly, unless they are very simple objects and you know what you're doing, you're still going to need much more intelligent serialisation logic than just writing their component bytes into a file. 首先,您应该尝试序列化Student对象,而不是指向它们的迭代器,其次,除非它们是非常简单的对象并且您知道自己在做什么,否则您仍将需要更智能的序列化逻辑而不只是将其组成字节写入文件中。 Learn about alignment, padding, endianness, indirection.... 了解对齐,填充,字节序,间接...。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM