将数据插入矢量
Insert data into vector
我有一个.txt文件,其中的数据格式如下:
1.23,2.34,3.45
4.56,5.67,6.78
如何在矢量中插入数字
vector[1]={1.23,4.56,...}
vector[2]={2.34,5.67,...}
vector[3]={3.45,6.78,...}
代码
ifstream in("data.txt");
vector<vector<int> > v;
if (in) {
string line;
while (getline(in,line)) {
v.push_back(std::vector<int>());
stringstream split(line);
int value;
while (split >> value)
v.back().push_back(value);
}
}
代码中存在多个问题
-
您的内部
vector
应该是float
或double
的vector
,而不是int
。 -
您的
value
变量也应该是float
或double
-
阅读时你需要越过分隔符(逗号)。
-
您需要创建与每行中的值一样多的内部向量。我在下面通过使用一个布尔
first
变量来实现这一点——我使用它来确保只在读取第一行时创建向量。 -
push_back
到的内部向量的索引与被推回的行上的值的列编号相同。我使用变量col
来计算当前在一行上读取的列编号。
您需要与列数一样多的内部向量。每个内部向量的成员数与文件中的行数一样多。
ifstream in("data.txt");
vector<vector<double> > v;
bool first = false;
if (in)
{
string line;
while (getline(in,line))
{
istringstream split(line);
double value;
int col = 0;
char sep;
while (split >> value)
{
if(!first)
{
// Each new value read on line 1 should create a new inner vector
v.push_back(std::vector<double>());
}
v[col].push_back(value);
++col;
// read past the separator
split>>sep;
}
// Finished reading line 1 and creating as many inner
// vectors as required
first = true;
}
}
相关文章:
- 在 QAbstractTableModel 上的 setModel 之后插入数据
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 增强循环缓冲区push_back在前面插入数据
- 程序 使用链表插入数据时停止工作
- 如何与LIBPQXX API同时插入数据?(PostgreSQL,线程)
- 如何在其中创建2D字符串向量并插入数据
- 二叉搜索树插入数据问题
- 通过指定第 n 个节点位置在单链接列表中插入数据
- 默认情况下构造函数插入数据后,我没有得到任何输出,但我不确定为什么不
- 在std::映射中插入数据
- 插入数据时出现分段错误
- 如何在C++的排序文件中插入数据
- 在二进制树中插入数据时出错
- 在双通道矩阵中插入数据
- 用于插入数据而非搜索的最快数据结构
- 无法在映射的映射的STL映射中插入数据
- 如何插入数据到sqlite使用qt
- 为什么在c++中,在矢量结束后插入数据是错误的
- 在没有c++方法的类中插入数据
- 在矢量中插入数据时多次调用复制构造函数