Sign in to follow this  
Quasimojo

Adding objects to vectors

Recommended Posts

Considering the following simple stat object:

struct Stat
{
unsigned short ID;
string Code;
string Name;
string Description;
}


How would I read values in from a text file and populate a vector of type Stat? I've tried variations of the following with no luck:


ifstream file;
string line;
size_t found;
int startPos = 1;
vector<Stat>::iterator i;

file.open(FILE_STATS); // defined constant for file name
if (file.is_open())
{
while (file >> line)
{
_stats.push_back(Stat());
i = _stats[_stats.size()];
found = line.find("|");
if (found != string::npos)
{
i.ID = (short int)line.substr(startPos, found - 1);
startPos = found + 1;
}
found = line.find("|", found);
if (found != string::npos)
{
i.Name = line.substr(startPos, found - startPos - 1);
startPos = found + 1;
}
i.Description = line.substr(startPos, line.length());
}



I'm sure part of the problem is my lack of knowledge in the use of vectors, so could someone help me out with their correct usage?

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
So what's the problem? Compiler error? Runtime error? Little pink cats dancing on your monitor?


Lol, I guess that might help. The error is as follows:

no match for ‘operator=’ in ‘i = ((GameData*)this)->GameData::_stats.std::vector<_Tp, _Alloc>::operator[] [with _Tp = Stat, _Alloc = std::allocator<Stat>](((GameData*)this)->GameData::_stats.std::vector<_Tp, _Alloc>::size [with _Tp = Stat, _Alloc = std::allocator<Stat>]())’

Honestly, I have little to no idea what this error means.

Share this post


Link to post
Share on other sites
i = _stats[_stats.size()];



this is wrong. First of all your indexing is out of bounds (+1). _stats[_stats.size()] will return a reference to an element in the vector and not an iterator. This is what gives you the compilation error.

You are also using dot to get the members of i. An iterator is similar to a pointer so you need to use an arrow, i->.

I don't think you need to use an iterator here at all. Use a reference instead.
Stat& i = _stats.back();


then you can still use dot to access the members.

Share this post


Link to post
Share on other sites
Thanks folks. I think I got it figured out. I was just making it more complicated than it needs to be. Now I'm simply creating a Stat object, modifying it's members and adding it to the vector with push_back(). Seems to work fine.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this