使用c++从文件中提取三维矢量

3d vectors from file using c++

本文关键字:三维 提取 c++ 文件 使用      更新时间:2023-10-16

文本文件的数据如下所示。

.i 8
.o 8
00000000 00000000
00010001 00010010
00000100 01000000

请注意,在第一列中,0和1是独立的。我想将这些数据解析为3d矢量-3行2列,每列8个元素为整数类型并显示矢量。

我试过这样的代码

 #include <string>
 #include <iostream> 
 #include <sstream>
 #include <vector>
 #include <bitset>
 #include <fstream>
 #include <stdio.h>
 #include <stdlib.h>
 #include "Line12.hpp"
 using namespace std;
 void printLine12(Line12 line1)
 { 
     cout << "first:" << line1.getFirst() << endl;
     cout << "in:" << line1.getIn() << endl;       
 }
 int main()
 {
     std::vector<Line12> lines12;
     std::vector<std::vector<std::bitset<8> > > a;
std::ifstream in("C:/Users/Lenovo/Desktop/hwb8_64.pla");
std::string Line;
for(int i=1; i<=258;i++)
{
  std::getline(in,Line);
  if(i==1 || i==2)
  {
  Line12 s(Line);
  lines12.push_back(s);
  }
  else if(i >= 3 && i<=258)
  {
    a.push_back(std::vector< std::bitset<8> >());
    std::istringstream iss(Line);
    std::string bits;
    while (iss >> bits)
    {
    a.back().push_back(std::bitset<8>(bits));
    }     
  }               
}
system ("PAUSE");
for(int i=1; i<=258;i++)
{
  if(i==1 || i==2)
  {
  Line12 s1 = lines12.at(i);
  printLine12(s1);
  } 
  else if(i>=3 && i<=258)
  {
   for (int x = 0; x < a.size(); ++x)
   {
    for (int y = 0; y < a[i].size(); ++y)
    {
        for (int z = 7; z >= 0; --z)
        {
            std::cout << a[x][y][z];
        }
        std::cout << " ";
    }
    std::cout << std::endl;
  }
 } 
}      
system ("PAUSE");
return 0;
}

我收到一个错误std::invalid_argument --> bitset::_M_copy_from _ptr

如何删除此错误?

实时演示链接。

#include <string>
#include <iostream> 
#include <sstream>
#include <vector>
#include <bitset>
#include <fstream>
int main()
{ 
    std::vector< std::vector< std::bitset<8> > > v3d;
    std::ifstream in(path_to_file);
    std::string line;
    while (std::getline(in, line))
    {
        v3d.push_back(std::vector< std::bitset<8> >());
        std::istringstream iss(line);
        std::string bits;
        while (iss >> bits)
        {
            v3d.back().push_back(std::bitset<8>(bits));
        }
    }
    for (int i = 0; i < v3d.size(); ++i)
    {
        for (int j = 0; j < v3d[i].size(); ++j)
        {
            for (int k = 7; k >= 0; --k)
            {
                std::cout << v3d[i][j][k];
            }
            std::cout << " ";
        }
        std::cout << std::endl;
    }
}