1

this is basically what I am trying to do:

class Player
{
public:
    void setInventory(string inventory[]) { this->inventory = inventory; }
private:
    string inventory[4];
};

normally I would use strncpy(); but sadly using the parameter inventory[] as the source does not work because it isn't a const char *. I want to keep this as an in class function if possible in one or two lines. I just want to know if there is a short way of doing this rather than creating a function outside of the class for it. Thanks

1

3 Answers 3

2

There's std::copy if you want copies of the array elements or std::move if you're allowed to move from them.

Example:

class Player
{
public:
    void setInventory(std::string inventory[]) {
        std::copy(inventory, inventory + 4, this->inventory);
    }
private:
    std::string inventory[4];
};

Note that you should make sure that your "array parameter" (it's a pointer, actually) should've (at least) the required 4 elements. If possible it's better to encode the size into the type, for example using std::array.

struct Player {
  void setInventory(std::array<std::string, 4> i) {
    inventory = i;
  }
  std::array<std::string, 4> inventory;
};

This works because std::array implements the assignment operator operator=.

Sign up to request clarification or add additional context in comments.

Comments

0

You should really make your inventory storage into a type or class itself so you can treat it uniformly and clearly. That would automatically get you copy/move operations (assuming a recent standards-compliant compiler) to keep the handling clear:

typedef std::array<std::string, 4> Inventory;

class Player
{
public:
    void setInventory(Inventory &&inventory) {
        this->inventory = inventory;
    }
private:
    Inventory inventory;
};

Doing it this way also allows you to expand & enhance Inventory itself in the future with zero or minimal refactoring of code that handles it from the outside.

Comments

0

You won't use stdncpy(), inventory is an array of std::string, not char.

You can write a simple loop to do this,

void setInventory(string inventory[]) {
    for (int i = 0; i < 4; i++) 
        this->inventory[i] = inventory[i];
}

but the most simple way is to use std::array.

class Player
{
public:
    void setInventory(const std::array<std::string, 4>& inventory) { this->inventory = inventory; }
private:
    std::array<std::string, 4> inventory;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.