簡體   English   中英

C++中的迭代器將向量寫入二進制文件的正確方法

[英]The right way to write a vector to a binary file by iterator in C++

我已經搜索了很多此類問題,但沒有得到滿意的答案。

我正在研究 function 以使用 C++ 中的 ofstream::write 方法將向量容器寫入二進制文件。

#include <vector>
#include <fstream>

typedef std::vector<unsigned char> byteArray;

byteArray data;
data.push_back('a');
data.push_back('b');
data.push_back('c');
data.push_back('d');

std::ofstream fout("out_file", std::ios::out | std::ios::trunc | std::ios::binary);

// I know the right way should be as following:
fout.write((char *)&data[0], data.size());

// But what I cannot understand is why the following expression is wrong, since gcc compiler says
// invalid cast from type ‘__gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned char> >’ to type ‘char*’

for(auto iter = data.begin(); iter != data.end(); iter++)
{
    fout.write((char *)iter, 1);
}

fout.close();

據我了解,迭代器 iter 是一個指針,它指向向量“數據”中的一個元素。 所以我認為(char *) iter會將底層數據類型重新解釋為char,那么它應該滿足fout.write的參數要求。 但實際上,情況並非如此。 我也很困惑,gcc 說 iter 是一種迭代器<unsigned char*, std::vector >,對吧? iter 不應該是 unsigned char * 類型嗎?

我怎么了? 非常感謝您的幫助。

據我了解,迭代器 iter 是一個指針

它不是。 std::vector::iterator是未指定的類型。

您可以期望它具有一些類似指針的屬性,但您不應假設它可能是什么特定類型。

由於您需要一個指針,請取消引用迭代器並獲取該結果的地址。 那是一個指針。

fout.write((char *)&*iter, 1);

更好的是,使用 C++ 模型而不是難以跟蹤的 C 模型。

fout.write( static_cast<char*>(&*iter), 1 );

更安全(Martin York 始終是一顆珍貴的寶石)——不要假設包含類型的大小。 未來可能會改變。 這種變化不會增加過度對沖。

fout.write( static_cast<char*>(&*iter), size_of(byteArray[0]) );

指針可以用作迭代器,但迭代器不必是指針。

通過提供取消引用operator*() 、遞增operator++()等操作,迭代器的行為或多或少類似於指針,請參見LegacyInputIterator的要求

盡管具體定義會隨着時間而改變,但請參閱std::input_or_output_iterator以了解 C++20 中的定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM