[英]Loading data into a vector of structures
我試圖將文本文件中的一些數據加載到結構向量中。 我的問題是,你如何表明矢量的大小? 或者我應該使用向量push_back函數動態執行此操作,如果是這樣,填充結構時這是如何工作的?
完整的計划概述如下:
我的結構定義為
struct employee{
string name;
int id;
double salary;
};
並且文本文件(data.txt)包含以下格式的11個條目:
Mike Tuff
1005 57889.9
其中“Mike Tuff”是名稱,“1005”是id,“57889.9”是薪水。
我試圖使用以下代碼將數據加載到結構的向量中:
#include "Employee.h" //employee structure defined in header file
using namespace std;
vector<employee>emps; //global vector
// load data into a global vector of employees.
void loadData(string filename)
{
int i = 0;
ifstream fileIn;
fileIn.open(filename.c_str());
if( ! fileIn ) // if the bool value of fileIn is false
cout << "The input file did not open.";
while(fileIn)
{
fileIn >> emps[i].name >>emps[i].id >> emps[i].salary ;
i++;
}
return;
}
當我執行此操作時,我收到一條錯誤消息:“調試斷言失敗!表達式:向量下標超出范圍。”
std::istream & operator >> operator(std::istream & in, employee & e)
{
return in >> e.name >> e.id >> e.salary; // double not make good monetary datatype.
}
int main()
{
std::vector<employee> emp;
std::copy(std::istream_iterator<employee>(std::cin), std::istream_iterator<employee>(), std::back_inserter(emp));
}
vector
是可擴展的,但只能通過push_back()
, resize()
和一些其他函數 - 如果你使用emps[i]
並且i
大於或等於vector
的大小(最初為0),程序會崩潰(如果你很幸運)或產生奇怪的結果。 如果您事先知道所需的大小,可以調用例如emps.resize(11)
或將其聲明為vector<employee> emps(11);
emps.resize(11)
vector<employee> emps(11);
。 否則,您應該在循環中創建一個臨時employee
,讀入它,並將其傳遞給emps.push_back()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.