-1

Pretty simple c++ question here, how do I replace part of variable reference with another variable, almost to concatenate it.

For example I have a structure with item1, item2, item3, I ask the user what Item they want the information of which is stored in a variable itemNo for example:

cout << "The item you selected is " << item(itemNo).name;

if itemNo==1 the reference would need to become item1.name;

Brackets is wrong in this scenario, but what is the right way to insert a number to form the right variable reference?

3
  • 6
    You want to learn arrays. Commented Jan 24, 2023 at 8:49
  • 4
    You can't do this, but you don't need to. Just use an array instead of 3 separate variables. Commented Jan 24, 2023 at 8:49
  • Brackets is wrong in this scenario, not if you overload operator(). But whether that is the right thing to do or not depends on the context (though it seems unlikely). Probably you need a vector or a map. Commented Jan 24, 2023 at 8:55

2 Answers 2

1

As mentioned in comments, if you name member item1,item2, item3,etc then you rather want a std::array, or if the number of items is dynamic then std::vector. Once you use a container as member, the container does provide a means of element access. However, as you are asking for it, it follows a way to make items(itemNo).name work. It makes use of operator overloading. And it uses a vector to store the data.

#include <string>
#include <vector>
#include <iostream>

struct Item { std::string name = "name";};
struct Items {
    std::vector<Item> data = std::vector<Item>(10);
    Item& operator()(size_t i) { return data[i];}
    const Item& operator()(size_t i) const { return data[i];}
};

int main() {
    Items items;
    items(5).name = "Hallo";
    std::cout << items(0).name << " " << items(5).name;
}

For further reading I refer you to operators@cppreference and What are the basic rules and idioms for operator overloading?. For the containers container@cppreference, std::array, and std::vector.

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

Comments

-1

You can define struct as a holder for your item

struct item {
   std::string name;
}

and then you can store items in array.

#include <array>
#include <string>
#include <iostream>

struct item {
   std::string name;
};

int main() {
  std::array<item, 3> items{ {{.name = "item1"}, {.name = "item2"}, {.name = "item3"}}};
  item& current_item = items[0];
  std::size_t  chosen{0};
  std::cout << "choose item (1-3):\n";
  std::cin >> chosen;
  current_item = items[chosen];

  std::cout <<  "current item: " << current_item.name << "\n";
}

You can switch to std::vector if you want to store dynamic number of elements.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.