How to use string or char as a reference to variable?

I need to take a character as input which will match either one of the already created variable. Now, how can I send this character to a function as the reference to that variable? Any help is appreciated since I'm pretty much newbie.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
vector <vector <float> > a;
vector <vector <float> > b;
vector <float> c;

void input(char ch)
{
    float in;
    int i=0;
    while(i<5)
    {
        cin>>in;
        'ch'.push_back(in);
        i++;
    }
}

void output(char ch)
{
    int i;
    while('ch'[i]!=NULL)
        cout<<'ch'[i];
}

int main()
{
    map <char,char> inp;
    char ch;
    cin>>ch;
    inp[ch]=
    input(ch);
    output(ch);
}
I'm not sure I understand. Can you give an example of what you want the user to be able to do? Example input/output?

Are you trying to map a character to one of your vector<vector<float>>s (a/b)?

Here's an example of something. It's not using vectors but maybe it helps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <map>

using std::cout;
using std::cin;

int main()
{
    std::map<char, int> mapping;
    
    while (true)
    {
        cout << "Input character variable ('q' to quit): ";
        char varname;
        cin >> varname;
        
        if (varname == 'q')
            break;
        
        if (mapping.find(varname) != mapping.end())
        {
            cout << "Variable already exists! Its value is " << mapping[varname] << ".\n";
        }
        else
        {
            cout << "Enter value for new variable: ";
            cin >> mapping[varname];
        }
    }
}
Last edited on
If I understand you right, you have 3 variables a, and c. These are vectors of floats. The user enters a letter (a,b or c) and you want to call input() and output() with the corresponding vector.

This is a demonstration of how pointers can be helpful for things other than dynamic memory. You can create a pointer to a vector, set it to the appropriate one based on the letter entered, and make the calls with the pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <vector>
#include <iostream>

using namespace std;

vector <float> a, b, c;		// declare 3 vectors of float

void input(vector<float> &v)
{
    float in;
    int i=0;
    while(i<5)
    {
        cin>>in;
	v.push_back(in);
        i++;
    }
}

void output(vector<float> &v)
{
    for (unsigned i=0; i<v.size(); ++i) {
	cout << v[i] << ' ';
    }
    cout << '\n';
}

int main()
{
    char ch;
    vector<float> *pv=nullptr;

    cin>>ch;
    if (ch == 'a') pv = &a;
    else if (ch == 'b') pv = &b;
    else if (ch == 'c') pv = &c;
    else {
	cout << "bad input character\n";
	return 1;
    }

    // Now use pv to call input() and output()
    input(*pv);
    output(*pv);
}

@dhayden

Pointer is a good option for this but if the number of variable is too many using conditional becomes too tedious.
@Ganado

'map' is good in your exmple but for my program map would make it a bit too complicated. But if there's no other option I will use map. But still I would like to have a better option.
Last edited on
@Rakib771, why don't you say what you are ultimately trying to do ... NOT how you would code it. Then you might get a better answer.

Just inputting a vector, then outputting it again, doesn't seem to be worthy of any great complexity.

As written, there is nothing in your program that justifies using more than one vector in the first place.
Last edited on
@lastchance

What I'm trying to do is that, the program will have multiple matrices and the user will chose which matrix to input data to. So, I need to pass the matrix name to the input function. I'm trying to do it with map but doesn't work very well and becomes complex. I'm looking for a way, if that exists, to make the function recognize the matrix from a character/string.
if the number of variable is too many using conditional becomes too tedious.

You surely know the "greatest of three" homework task, that student implements with:
1
2
3
4
T one, two, three;
// input values

// complex and redundant if-statements 

That does not scale, as you said. The next lesson introduces arrays:
1
2
3
4
std::vector<T> data;
// input values with loop

cout << *std::max_element( std::begin(data), std::end(data) );

Distinct, unique variables are packed as nameless (but indexed) elements into array and iteration does the work.

That solution is scalable. It works for any number of values without touching the code.


Your challenge is therefore how to define a container, list, dictionary, lookup table, mapping, index from characters into elements.


Combining ideas from Ganado and dhayden:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>
#include <map>
#include <iostream>

using VF = std::vector<float>;

void input( VF& );
void output( VF& );

int main()
{
  // create three vector variables:
  std::map<char, VF> variables;
  variables.emplace( 'a', VF() );
  variables.emplace( 'f', VF() );
  variables.emplace( 'k', VF() );
  // you could read the keys dynamically from input

  char ch;
  cin>>ch;
  auto location = variables.find( ch );
  if ( location == mapping.end() ) {
    std::cout << "bad input character\n";
    return 1;
  }
  // Now use the selected variable
    input( location->second );
    output( location->second );
}



Back to OP:
1
2
3
vector <vector <float> > a;
vector <vector <float> > b;
vector <float> c;

Oh my. The T a; T b; U c; does not convert into T array[3];

We cannot call input( T& ) with the c that is not a T.
Is that why you did ask: "how to pass identifier of data"?

Lets say that variables are:
1
2
string one;
vector<vector<double>> two;


Your input() receives identifier (ID) somehow. It must somehow:
1
2
3
4
5
if ( ID refers to one ) {
  // operate on text
else if  ( ID refers to two ) {
  // operate with container of numbers
}

The output() has to repeat the same based-on-type logic.

That does not scale and we can't put all data into our array (std::map<char, VF> variables;).

You can implement the type-based decisions with overloading:
1
2
3
4
void input( int& );
void input( string& );
void input( vector<float>& );
void input( vector<vector<double>>& );

The caller remains problematic:
1
2
3
4
5
6
7
8
9
10
11
12
    string a; vector<float> b; vector<vector<double>> c;
    cin>>ch;
    if (ch == 'a') {
      input( a );
      output( a );
    } else if (ch == 'b') {
      input( b );
      output( b );
    } else if (ch == 'c') {
      input( c );
      output( c );
    }

However, you could have polymorphic data type class hierarchy in order to have an array of variables.


EDIT: Do all the "matrices" have the same type or not?
Last edited on
Also, in an attempt to shed some light on this: A C++ program does not care what variables are called. Whether you called your variable std::vector<float> a; vs. std::vector<float> dafdjjadshdsf38r738728; makes no difference (beyond syntax/name restriction rules).

After a C++ program is compiled, those variable names no longer exist. So if you want to make some association at run-time between a string (the variable's name) and the data that name corresponds to, you as the programmer have to do that yourself.

[Note that languages like C#/Java have a feature called Reflection, which can look at a class at runtime to see its attributes/functions, but it's (1) generally inefficient and (2) easily abusable, which is why most people recommend only using it as a last resort or for things like unit testing.]
Last edited on
Pointer is a good option for this but if the number of variable is too many using conditional becomes too tedious.
You hadn't mentioned that it needed to scale. You also said that you needed to map to an "already created variable" which made me think you meant variable, not heap-created object.

'map' is good in your exmple but for my program map would make it a bit too complicated.
what could be easier than input(mymap[validated_input_char])?

The most common ways to map a key to a value are map<>, array, and vector<>. If the keys aren't integral and sequential, then use map. Otherwise use array or vector, depending on whether you know the size at compile time.

Honestly, you're trying to reinvent the wheel. Just use the excellent tools that already exist for precisely this problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef vector<vector<int>> vvi;

int main() {
	vvi v={{1,2,3}, {4,5,6}};
	map<char,vvi> m;
	
	m.insert(make_pair('a', v));
	m.insert(make_pair('b', v));
	
	char c ='b';
	
	cout << m[c].at(1).at(2); //6
	
return 0;
}
Topic archived. No new replies allowed.