Hi guys, as you know we can get a value from array by giving an index:

int x[10];
int i;
for(i=0; i<10; i++)
    x[i]=i;
print(x[1]);

// output is: 1

but how can I change this code to this:

int x[10];
int i;
x['a']=0;
x['b']=1;
x['c']=2;
.
.
.
x['z']=23;

print(x['c']);

//output is: 2

as you see the code above I can give a char to the array as an index and print its value....
Can I?

thanx

Recommended Answers

All 4 Replies

You can do that but I would ask why you want to do that. ZWhat are you trying to accomplish with this? A char is basically a 1 byte unsigned integer so if you use 'a' than it gets interperted to 97.

Or instead of using an int array you could use a map (or unordered_map if you have a compiler that supports C++11).

Accessing the values would be exactly the same but instead of having an array with a size of 97 + 26 (because 'a' is 97 (as said above) and then you need room up until 'z') you would have a map with 26 entries. Obviously maps have overhead that a normal array does not, but I think it would be good to play around with some of the STL containers so that you know how to use them and what each of them can and cannot do.

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<char, int> myMap;

    for( int i = 0; i < 26; i++ )
        myMap['a'+i] = i;

    cout << myMap['c'] << endl;

    cin.get();
}

By the way (I'm sure you just wrote it out and didn't actually test it) you defined an int array of size 10 but assigned/accessed out of bounds (in your second example).

commented: While NathanOliver and AncientDragon give "correct" answers, this is probably the most useful. +5

x['a']=0;

Yes it can be done, but the array must be large enough for 'a' to be a valid index value. That may be useful when you need to count the frequency that each letter occurs in a sentence or other text document. You need to declar the array like this: int x[255] = {0};

In c++ it would be better to use a map as previously suggested.

Thanx sfuo you have solved my problemm :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.