如何将列声明为向量
How to declare my column as a vector?
我的代码
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <sstream>
#include <cmath>
int main(){
std::ifstream ifs("MFSO7.dat");
std::string line;
while(std::getline(ifs, line)) // read one line from ifs
{
std::istringstream iss(line); // access line as a stream
float column1;
float column2;
float column3;
iss >> column1;
std::cout << column1 << std::endl;
}
std::vector<float> v1 = column1;
std::vector<float> v2;
transform(v1.begin(), v1.end(), back_inserter(v2),[](float n){return std::pow(n,2);});
copy(v2.begin(), v2.end(), std::ostream_iterator<float>( std::cout, " "));
}
我已经从我的txt文件中读取了三列,然后我只需要第一列进行进一步的计算。我想用w来求所有元素的平方。但是我得到
k.cpp: In function ‘int main()’:
k.cpp:24:28: error: ‘column1’ was not declared in this scope
std::vector<float> v1 = column1;
如何解决这个问题?
将元素添加到循环内的vector:
std::vector<float> v1;
while(std::getline(ifs, line)) // read one line from ifs
{
std::istringstream iss(line); // access line as a stream
float column1;
iss >> column1;
v1.push_back(column1);
std::cout << column1 << std::endl;
}
// now v1 contains the first column of numbers from your file
// go ahead and transform it into v2
- 声明三个向量,表示
while
循环之前的列。 - 填充
while
环中矢量的内容
std::vector<float> column1;
std::vector<float> column2;
std::vector<float> column3;
while(std::getline(ifs, line)) // read one line from ifs
{
std::istringstream iss(line); // access line as a stream
float item1;
float item2;
float item3;
// Read the items from the line
iss >> item1 >> item2 >> item3;
// Add them to the columns.
column1.push_back(item1);
column2.push_back(item2);
column3.push_back(item3);
std::cout << item1 << " " << item2 << " " << item3 << std::endl;
}
相关文章:
- 声明高维向量的更简洁的方法
- 标准::向量声明中使用的模板参数
- 使用全局声明的向量时,C++双重释放错误/损坏
- 为什么这种向量声明无效?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 如何声明一个标准::提升直方图的向量?提升直方图的类型是什么?
- 在类中声明向量的大小
- C++ 通过函数声明后初始化向量
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- 如何声明指向类对象的指针向量?
- 我不明白这个向量声明语句
- <string> C++ 中的向量声明
- 使用更大值和向量声明优先级队列
- 将向量声明为类成员
- 全局和主类中的向量声明
- C++如何将对象的向量声明为类的成员
- 如何将unique_ptr的向量声明为类数据成员?
- 对齐数据类型Eigen::矩阵的数组或向量声明
- 看不懂这个向量声明
- 将对象向量声明为另一个类的成员