How in C ++ to create a constant array of numbers with symbolic indices, for example, from 'a' to 'f'? Desirable simpler. :) That is, in Delphi it would be so
a : array['a'..'f'] of longint = (1, 2, 3, 4, 5, 6);
How in C ++ to create a constant array of numbers with symbolic indices, for example, from 'a' to 'f'? Desirable simpler. :) That is, in Delphi it would be so
a : array['a'..'f'] of longint = (1, 2, 3, 4, 5, 6);
I will add the answer given by @ cy6erGn0m
enum { RESULT_ERROR; } int start; int end; int* makeArray( char first, char second) { start = (int)first; end = (int)second; return new int[second-first+1]; } int get( int *array, char ch){ int index = (int)ch; if (first > index || index > end) return RESULT_ERROR; return array[index-first]; }
If your example is right, then no array is needed. Just instead of a [idx] is necessary (idx - 'a')
If you really need to associate characters with numbers, then there will be something like this:
const int a[] = {1, 2, 3}; const char a_max_idx = 'a' + sizeof(a) / sizeof(int); int get(char idx) { if (idx < 'a' || idx >= a_max_idx) die("....."); return a[idx - 'a']; }
You can use std :: map. For example, something in the spirit of this . The advantage is the compactness of the code and its storage in the memory in case some non-continuous subset of ASCII or Unicode is required. At the same time easy to alter the lines.
#include <iostream> using namespace std; enum abc {a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, v, w, x, y, z}; int name[j]; int main(){ name[f]=2; cout << name[f] << endl; return 0; }
If I understand you correctly. This option works, but it is not convenient, it will be easier for you to use the usual name index [3], and the program will work faster.
Agree with comrade gecube. For this, std: map is best suited. Of course, to initialize it also compactly and elegantly fail.
For the future, for questions on containers I recommend: http://www.cplusplus.com/reference/stl/
Source: https://ru.stackoverflow.com/questions/21413/
All Articles