开发者

need help with vector out of range error

guys, I'm reading from a file and input into a vector, but I keep getting a pop up box with: "vector employees out of range!" error. It is like if I'm trying to access pass the last index in the vector, but if that's the case I don't see... any help appreciated text file:

123 vazquez 60000
222 james 100000
333 jons 50000
444 page 40000
555 plant 40000

code:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;

struct employees { int id; string lname; double salary; };
void getData(vector<employees>& list, ifstream& inf);
int i = 0;
int main()
{
    string filename("file2.txt");
    vector<employees> list;
    ifstream inf;
    inf.open(filename);

    getData(list, inf);
    inf.close();

    for(unsigned int j = 0; j < list.size(); j++)
    {
        cout << list[j].id << " " << list[i].lname << endl;
    }

    system("pause");
    return 0;
}

void getData(vector<employees>& list, ifstream& inf)
{
    int i = 0;
    while(inf)开发者_开发百科
    {
        inf >> list[i].id >> list[i].lname >> list[i].salary;
        i++;
    }
}


When you pass list into getData(), it has zero elements in it. You then try to access the element at index i (starting at 0), but there is no such element, hence the error.

You need to insert new elements into the container; the easiest way to do this would be to create a temporary object, read the data into that object, and then insert that object into the container.

employee e;
while (inf >> e.id >> e.lname >> e.salary)
    list.push_back(e);

Note that this also fixes your incorrect input loop. In your incorrect loop, the stream could reach EOF or otherwise fail during one of the reads in the loop, but you don't detect that until after you've incremented i.


In your while loop in getData, you need to push_back an employees each time. Or you can define the >> operator for your employees class, and you wouldn't even need the getData function, you could just past an istream_iterator into the vector constructor.

Example using istream_iterator:

#include <iostream>
#include <vector>
#include <string>
#include <iterator>

struct employee { int id; std::string lname; double salary; };
std::istream& operator>>(std::istream& is, employee& e) {
  return is >> e.id >> e.lname >> e.salary;
}

int main() {
  std::string filename("file2.txt");
  std::ifstream inf;
  inf.open(filename); //add error checking here

  std::vector<employee> list((std::istream_iterator<employee>(inf)), std::istream_iterator<employee>());
  for (std::vector<employee>::iterator iter = list.begin(); iter != list.end(); ++iter) {
    std::cout << iter->id << " " << iter->lname << std::endl;
  }
  return 0;
}


list[i].lname should be list[j].lname

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜