从两个列之一返回值,或跳过数组中的所有其他元素

Return values from one of two columns, or skip every other element in an array?

本文关键字:数组 元素 其他 两个 返回值      更新时间:2023-10-16

我正在尝试编写两个单独的函数,这两个功能都从数据文件中读取,但只返回两个列中的一个。(评论不在.dat文件中,只是为了澄清而写)

//  Hours     Pay Rate
    40.0       10.00
    38.5        9.50
    16.0        7.50
    42.5        8.25
    22.5        9.50
    40.0        8.00
    38.0        8.00
    40.0        9.00
    44.0       11.75

如何返回一个函数中代表"小时"的元素,然后在另一个功能中返回"付费率"?

使用 fstream ifstream 对象和提取操作员。

std::ifstream fin(YourFilenameHere);
double hours, rate;
fin >> hours >> rate;

这些对象的类位于fstream标题中。

// "hours" and "payRate" might as well be class members, depending
// on your design.
vector<float> hours;
vector<float> payRate;
std::ifstream in(fileName.c_str());
string line;
while (std::getline(in, line)) {
  // Assuming they are separated in the file by a tab, this is not clear from your question.
  size_t indexOfTab = line.find('t');
  hours.push_back(atof(line.substr(0. indexOfTab).c_str());
  payRate.push_back(atof(line.substr(indexOfTab +1).c_str()));
}

现在,您可以在数小时乘数小时访问I'th进入[I],同样的薪金率。同样,您可以通过返回相应的向量来"返回一列",如果您确实需要。