如何将列声明为向量

How to declare my column as a vector?

本文关键字:向量 声明      更新时间:2023-10-16

我的代码

#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
  1. 声明三个向量,表示while循环之前的列。
  2. 填充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;
}