从 txt 文件中读取数据到向量中
Reading data from txt file into vectors
由于其他问题,我试图在程序的一部分中使用 vectors
而不是数组。我以前从未真正使用过它们。
这是代码的一部分:
#include <vector>
ifstream file("data.txt");
vector<int> beds;
vector<int> people;
vector<int> balconies;
while(!file.eof()){
file >> people.push_back();
file >> beds.push_back();
file >> balconies.push_back();
}
我不知道它是否有效。无论如何,现在我有一个错误:No matching member function for call to 'push_back'
.
之前将输入数据存储在变量中,然后推送该变量
int example;
file >> example;
people.push_back(example);
或使用std::istream_iterator
方法 std::vector::push_back
接受一个参数,该参数是要添加到向量末尾的值。因此,您需要将每个调用分为两个步骤:首先将值读入 int
,然后将该值 push_back
读入向量。
while(!file.eof()){
int temp;
file >> temp;
people.push_back(temp);
file >> temp;
beds.push_back(temp);
file >> temp;
balconies.push_back(temp);
}
如评论中所述,我建议反对您所写的 while
条件。 This post 详细解释原因,并提供更好的替代方案。
由于其他问题,我试图在程序的一部分中使用 vectors
而不是数组。我以前从未真正使用过它们。
这是代码的一部分:
#include <vector>
ifstream file("data.txt");
vector<int> beds;
vector<int> people;
vector<int> balconies;
while(!file.eof()){
file >> people.push_back();
file >> beds.push_back();
file >> balconies.push_back();
}
我不知道它是否有效。无论如何,现在我有一个错误:No matching member function for call to 'push_back'
.
之前将输入数据存储在变量中,然后推送该变量
int example;
file >> example;
people.push_back(example);
或使用std::istream_iterator
方法 std::vector::push_back
接受一个参数,该参数是要添加到向量末尾的值。因此,您需要将每个调用分为两个步骤:首先将值读入 int
,然后将该值 push_back
读入向量。
while(!file.eof()){
int temp;
file >> temp;
people.push_back(temp);
file >> temp;
beds.push_back(temp);
file >> temp;
balconies.push_back(temp);
}
如评论中所述,我建议反对您所写的 while
条件。 This post 详细解释原因,并提供更好的替代方案。