为3D数据结构提供简单的基于文本的文件格式:
d d d d d
d d d d d
d d d d d
d d d d d
d d d d d
-
s s s s s
s s s s s
s s s s s
s s s s s
s s s s s
-
g g g g g
g g g g g
g g g g g
g g g g g
g g g g g
-
表示短字符串的5x5x3数据结构。我想知道如何有效地将这些数据加载到std::vector<std::vector<std::vector<std::string>>>
类型的结构中?
到目前为止我试过这个:
std::ifstream file("file.txt");
std::vector<std::vector<std::vector<std::string>>> data;
int lines = 0;
std::string line;
while(std::getline(file, line)){
std::stringstream stream(line);
if (line.size() > 1){
lines++;
data.resize(lines);
data.back().push_back(std::vector<std::string>());
std::string val;
while(stream >> val){
data.back().back().push_back(val);
}
}
}
虽然只是在二维中填充3D矢量,但它有些工作。我仍然不确定效率。
答案 0 :(得分:0)
也许这段代码很糟糕但是它完成了任务。:)而不是我使用std :: cin的文件。
#include <iostream>
#include <vector>
#include <string>
int main()
{
const size_t N = 3;
const size_t M = 5;
std::vector<std::vector<std::vector<std::string>>> v;
v.reserve( N );
std::vector<std::vector<std::string>> v2;
v2.reserve( M );
size_t k = 0;
do
{
v2.clear();
std::vector<std::string> v1;
v1.reserve( M );
size_t j = 0;
do
{
v1.clear();
std::string s;
for ( size_t i = 0; i < M && std::cin >> s; i++ )
{
v1.push_back( s );
}
if ( !v1.empty() ) v2.push_back( v1 );
} while ( ++j < M && !v1.empty() );
if ( !v2.empty() ) v.push_back( v2 );
} while ( k < N && ! v2.empty() );
for ( const std::vector<std::vector<std::string>> &v2 : v )
{
for ( const std::vector<std::string> &v1 : v2 )
{
for ( const std::string &s : v1 ) std::cout << s << ' ';
std::cout << std::endl;
}
std::cout << std::endl;
}
return 0;
}
输出(使用相同的输入):
"d" "d" "d" "d" "d"
"d" "d" "d" "d" "d"
"d" "d" "d" "d" "d"
"d" "d" "d" "d" "d"
"d" "d" "d" "d" "d"
"s" "s" "s" "s" "s"
"s" "s" "s" "s" "s"
"s" "s" "s" "s" "s"
"s" "s" "s" "s" "s"
"s" "s" "s" "s" "s"
"g" "g" "g" "g" "g"
"g" "g" "g" "g" "g"
"g" "g" "g" "g" "g"
"g" "g" "g" "g" "g"
"g" "g" "g" "g" "g"
答案 1 :(得分:0)
解决方案变得非常类似于我在问题中展示的内容。虽然做了一些小修改:
std::ifstream file("file.txt");
std::vector<std::vector<std::vector<std::string>>> data;
data.push_back(std::vector<std::vector<std::string>>());
std::string line;
while(std::getline(file, line)){
std::stringstream stream(line);
if (line.size() > 1){
data.back().push_back(std::vector<std::string>());
std::string val;
while(stream >> val){
data.back().back().push_back(val);
}
}
else {
array_.push_back(std::vector<std::vector<Entity>>());
}
}
打印结果:
for (auto v1 : data){
for (auto v2 : v1){
for(auto s : v2){
std::cout << s << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
给予:
d d d d d
d d d d d
d d d d d
d d d d d
d d d d d
s s s s s
... etc