C++ 将字符串向量转换为双二维数组向量
将C++ 将字符串向量转换为双二维数组向量,c++,string,vector,2d-vector,C++,String,Vector,2d Vector,将向量行转换为向量d的好方法是什么 我从文件中读取了500x9矢量字符串数据 vector<string> line; 矢量线; 我需要将这个字符串向量转换为大小为(500行,9列)的2D向量数组 向量d; 代码: 使用名称空间std; int main() { ///读取文件数据/// std::ifstream myfile; 打开(“somefile.txt”); std::矢量线; std::字符串str; while(getline(myfile,str)) 线。推回
向量
行转换为向量
d的好方法是什么
我从文件中读取了500x9矢量字符串数据
vector<string> line;
矢量线;
我需要将这个字符串向量转换为大小为(500行,9列)的2D向量数组
向量d;
代码:
使用名称空间std;
int main()
{
///读取文件数据///
std::ifstream myfile;
打开(“somefile.txt”);
std::矢量线;
std::字符串str;
while(getline(myfile,str))
线。推回(str);
myfile.close();
std::vector数据;
///将字符串转换为双精度///
std::transform(lines.begin()、lines.end()、data.begin()、std::stod);
}
我是标准算法的忠实粉丝。但我相信这里最好的例子是一个很好的老式while
-loop(如果您不确定行
可以被9整除,这一点尤其正确。)
向量d(line.size()/9,向量(9));
对于(auto i=0U;i+9这里有一个建议:打开一个编辑器,编写一些代码。可能是@Barmar的副本。感谢编辑方面的帮助…,不,它的方式不同,我已经能够从.txt文件而不是csv文件中读取数据,我的主要问题是将字符串向量转换为二维双向量。稍后我将不得不提取单个columnsHow这是不同的吗?你有一个逗号分隔的数字列表,CSV阅读器将返回一个2d向量。首先,它不是逗号分隔的。它只是空格,我认为它可以在一行或两行代码中解决。而不是像在那个问题中创建新类,我对这行代码有问题。这应该可以转换字符串nto double…如果我错了请纠正我?std::transform(lines.begin(),lines.end(),data.begin(),std::stod);感谢您的帮助谢谢Jonathan..非常感谢您的时间和努力..虽然我也设法用另一种方法来做,但此方法效果很好:)顺便说一句,因为我在我的示例中没有这样做,所以您可以使用:
for(const auto&I:d)copy(cbegin(I)、cend(I)、ostream_迭代器(cout,“\t”);
vector<vector <double> > d;
using namespace std;
int main()
{
/// read file data ///
std::ifstream myfile;
myfile.open("somefile.txt");
std::vector<string> lines;
std::string str;
while(getline(myfile,str))
lines.push_back(str);
myfile.close();
std::vector< std::vector<double> > data;
/// convert string to double ///
std::transform(lines.begin(), lines.end(), data.begin(), std::stod);
}
vector<vector<double>> d(line.size() / 9, vector<double>(9));
for(auto i = 0U; i + 9 <= line.size(); i += 9) {
transform(next(cbegin(line), i), next(begin(line), i + 9), begin(d[i / 9]), [](const auto& it){return stod(it);});
}