Vector and algorithm question

I'm working on an assignment, writing a simple RPG program using a vector and an algorithm. I am having an issue getting my program to function properly and I am sure that my mistake is a simple one but I haven't been able to get any help from my teacher on this and I don't know where to turn at this point! At this part of my code:


weapon.push_back( " sword ");
weapon.push_back( " axe ");
weapon.push_back( " gun ");
weapon.push_back( " crossbow ");

cout << "Please choose a weapon from the table: \n";
int choice1;
cout << "You may pick from the following: sword, axe, gun, or crossbow.\n\n";
cin >> choice1;

string findWeapon;
getline(cin,findWeapon);
myIterator1= find(weapon.begin(), weapon.end(), findWeapon);

for (iter1=weapon.begin();iter1 != weapon.end(); ++iter1)
{
cout << "Today " << name << " chose: " << *iter1 << "to slay the Zombies!!\n\n";
}

clearly the code will spit out each different weapon with what is listed in the cout << "Today" ........etc. I want to be able to pick from a list of weapons. However, when I go to change to a constant iterator, I get an abort error telling me my iterator is not dereferencable. I am at a loss as my first vector in the program worked just fine but this one will not. Any help at all would be greatly appreciated!

Thanks!!!
Your program is a bit weird. You never use choice1. You never use myIterator1.

Also, why do you use std::vector?
If you don't want to store the same weapon more than once, std::set may be a better choice.

However, when I go to change to a constant iterator, I get an abort error telling me my iterator is not dereferencable.

Well if std::find() doesn't find the findWeapon, it will return weapons.end(). Which cannot be dereferenced.

http://www.cplusplus.com/reference/stl/set/end/
Last edited on
Topic archived. No new replies allowed.