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?