c++ - Access number that corresponds to string -
let's have following variables:
int number1 = 2; int number2 = 4; ... int numbern = 43;
now want access these elements in loop on number 'i', following:
for (int = 0; < n; i++) { if(number1 == somefunc("number" + to_string(i))) { // stuff } }
here 'somefunc' should make sure recognizes want use number string corresponds to. how this?
for using std::map can this:
#include <iostream> #include <stdlib.h> #include <map> #include <string> using namespace std; int main (void) { map<string,int> mymap; mymap["number1"] = 2; mymap["number2"] = 4; /* ... */ char number[2]; number[1] = '\0'; for(int ii=1; ii<=2; ii++) { number[0] = (char)(ii+48); cout << string("number")+string(number) << ": "; mymap[string("number")+string(number)] += 1; cout << mymap[string("number")+string(number)] << endl; } return 0; }
here string key through can access actual number. in example didn't ensure key exists anyway should done normally.
Comments
Post a Comment