0

I'm trying to write a program that takes a user's input and use it to call a specific vector without using a long if statement. For example, if a user were to input "silver", I would like the program to call on the vector named silver. This way, the user can select a specific vector simply by typing a word in.

Is there any way to do this while avoiding if statements? My full program calls on lots of colors that the user inputs, and making if statements for all of them would be tedious.

#include <iostream>
#include "cmath"
#include <vector>

using namespace std;

int main() {
    string color1;
    
    vector<double> gold = {0, 0, pow(10, -1), .95, 1.05};
    vector<double> silver = {0, 0, pow(10, -2), .9, 1.10};
    
    cout << "input color:";
    cin >> color1;
    
    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
Pozu
  • 1
  • 1
  • 2
    Welcome to Stack Overflow. Your question is unclear and your code is unnecessarily complicated. When you are trying to implement a new functionality, it behooves you to aim for the *simplest possible use* of that functionality. There's no reason to involve vectors -- or strings -- but if you want to avoid tedious `if` statements, I suggest you look into `std::map`. – Beta Sep 07 '22 at 03:27
  • @Beta I just updated the post to make it a little more clear. What should I use instead of strings or vectors? – Pozu Sep 07 '22 at 03:36
  • 1
    @Pozu use [`std::map`](https://en.cppreference.com/w/cpp/container/map), like Beta suggested. Use `std::string` as the key type, and `std::vector` as the value type. – Remy Lebeau Sep 07 '22 at 04:13
  • FYI `pow(10, -2)` can be written as `1e-2` – Wyck Sep 07 '22 at 04:58

1 Answers1

2

Using std::map as indicated in comments:

#include <map>
#include <vector>
#include <cmath>
#include <string>
#include <iostream>

int main() {
  std::map<std::string, std::vector<double>> m = {
    { "gold",   { 0, 0, pow(10, -1), .95, 1.05 } },
    { "silver", { 0, 0, pow(10, -2), .9,  1.10 } }
  };

  std::string color;

  std::cin >> color;

  std::cout << m[color][4] << std::endl;

  return 0;
}

Note that this does no checking to ensure the string input by the user is a key in the map.

Chris
  • 26,361
  • 5
  • 21
  • 42