I have a class which has a string vector as a variable and a constructor which takes inputs to set the size of this vector. The only problem is the default value is NOT being set at all for the elements in the vector. What’s wrong here? Tried both resize and assign but just end up with blanks each time.
Class:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Lab
{
private:
vector<string> station;
int id;
public:
Lab()
{
station[0] = "Empty";
id = 0;
};
Lab(int ID, int size)
{
station.assign(size, "Empty");
id = ID;
};
Lab(const Lab& labcpy)
{
station.resize(labcpy.station.size());
id = labcpy.id;
};
Main where the size of the vector is set:
#include <fstream>
#include "lab.h"
using namespace std;
int main(int argc, char* argv[])
{
ifstream labnumber_file(argv[1]);
vector<Lab> lab_v;
int labnum;
int usernum;
while(!labnumber_file.eof())
{
labnumber_file >> labnum;
labnumber_file >> usernum;
lab_v.push_back(Lab(labnum, usernum));
}
Replace:
with
in your copy constructor. You are only allocating space, but are not copying data. Just use the vector’s assignment operator to copy data. It will also handle the re-sizing.
On a side note:
You might want to avoid using array operators[] as they do not do bounds checking.