簡體   English   中英

讀寫矢量 <bool> 到C ++中的文件

[英]Reading and writing vector<bool> to a file in c++

我有一個向量,其大小可能真的很大(一百萬個元素)。 我將向量的內容作為字節值寫入到文件中。 我無法弄清楚如何將字節值讀回到向量中。

這是代碼:

#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
using namespace std;

int main()
{
  // Filling a vector with values
  std::vector<bool> ve;
  ve.push_back(true);
  ve.push_back(false);
  ve.push_back(true);
  ve.push_back(false);
  ve.push_back(true);
  // Printing the values of the vector
  for(unsigned int i = 0; i < ve.size(); i++)
      cout << ve.at(i) << ".";
  cout << endl;

  // Writing the vector contents to a file
  const char* file_name = "abc.txt";
  ofstream outfile(file_name, ios::out | ios::binary);
  outfile.write((const char*)&(ve[0]), ve.size());
  outfile.close();
  // Reading the file and filling the vector with values
  ifstream infile ("abc.txt", ifstream::binary);
  vector<bool> out_ve((std::istreambuf_iterator<char>(infile)),
                       std::istreambuf_iterator<char>());

  while( !infile.eof() )
      out_ve.push_back(infile.get());

  // Checking if the values read are the same as the original values
  cout << "SIZE: " << out_ve.size() << endl;
  for(unsigned int i = 0; i < out_ve.size(); i++)
    cout << out_ve.at(i) << ".";
  cout << endl;

  infile.close();
  return 0;
}

[edit]寫入后關閉文件,輸出與輸入非常不同。

1.0.1.0.1.
SIZE: 6
1.1.1.0.1.1.

如何將正確的元素放入向量out_ve?

從大多數STL容器寫入數據無法通過outfile.write((const char*)&(ve[0]), ve.size()); 因為他們以復雜的方式管理內存,這對於他們的運作方式至關重要。 使用vector ,它可以工作,因為內存存儲是連續的,但是vector<bool>是特殊的,因為它將多個vector<bool>打包到一個字節中。 正如評論者已經指出的那樣, ve[0]返回一個特殊的臨時准引用類型,並且通過強制轉換為char*寫出該引用將產生與向量中的數據完全無關的東西。

即使此構造使您可以訪問向量的原始存儲器,但用於寫出數據的代碼與用於讀入數據的代碼也不兼容。 您用於寫出數據的代碼會將 8個bool條目打包到每個char ,但是您用於讀取數據的代碼會將每個char轉換為單個bool

由於您正在使用istreambuf_iterator回讀數據,所以為什么不以相同的方式將其寫出:

std::copy(ve.begin(), ve.end(), std::ostreambuf_iterator<char>(outfile));

這樣每字節寫出一個bool

如果您想以打包表示形式寫出數據,每個bool寫一個位,我認為您需要發明自己的輸入和輸出迭代器。

vector<bool>不是真實的vector 您在其他地方找到的可用於向量的代碼不會。 並且您一定不能忽略“臨時地址”。 這條線

outfile.write((const char*)&(ve[0]), ve.size());

不適用於vector<bool>

問題在於您要處理的地址不是您認為的類型。

嘗試執行AND操作:

#define logical_and(x, y)   ((x==y) ? x | y)

您應該研究運算符重載,並使運算符返回文件中的下一個無符號字符,然后使用atoi將值轉換為整數

防爆。

template<typename T>
  T operator << (ifstream& file)
  {
    return reinterpret_cast<T>(file.get());
  };

以上僅是一個示例(未經測試。一段時間未使用c ++模板,因此可能需要重新制作)

祝你好運

亞歷山大·弗蘭克蘭(Tandex)

暫無
暫無

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

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