Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm looking for a way to reference the items within my game based on their values.
C++
class item() {
     item();
     ~item();
     item(string name)
     private:
          string name;
}

item sword("sword");

vector<string> inventory;
inventory.pushback(sword.name);

While the code above is probably full of errors, it represents the concepts. Is there a way to reference the item sword from its name value in the inventory vector? Or would I have to use pointers? If so, how would I do that?

Thanks!

What I have tried:

Looking around the internet for ways to do this.
Posted
Updated 13-Sep-23 7:05am
v2

That does not make a lot of sense. Your item class contains only a single property which is a string. And your vector contains only strings. So how could an element of that vector refer back to the item?

You probably need to use a std::map - cppreference.com[^] type to keep track of things.

But that is largely a guess as it is not clear what exactly you are trying to do.
 
Share this answer
 
Comments
Brennon Nevels 13-Sep-23 15:03pm    
5
(If I got you) You might use a std::unordered_map too look-up items by their name property.
E.g.
C++
#include <iostream>
#include <unordered_map>
using namespace std;

class Item
{
  string name;
  int value;
  //...
public:
  Item(){}
  Item(string name, int value):name{name},value{value}{}
  string get_name(){ return name; };
  int get_value() { return value; };
  //...
  void show() const
  {
    cout << name << " " << value;
  }
  //...
};


int main()
{

  unordered_map<string, Item> inventory;

  inventory.emplace("foo", Item{"foo", 100});
  inventory.emplace("boo", Item{"boo", 20});
  inventory.emplace("goo", Item{"goo", -50});

  const auto & item_boo = inventory.at("boo"); // retrieve a reference of the Item by its name.
  item_boo.show(); cout << "\n";

  const auto & item_bar = inventory.at("bar"); // this is doomed to fail: no "bar" in your inventory...
  item_bar.show(); cout << "\n";
}
 
Share this answer
 
Comments
Brennon Nevels 13-Sep-23 15:01pm    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900