C++ array index

Discussion in 'Programming' started by webmasterplace, Sep 9, 2009.

  1. #1
    Hi,

    I'm wondering if it's possible to use a 'custom' array index in C++ like you can do with PHP.

    For example in PHP:

    $array = array('foo' => 'bar');
    echo $array['foo']; //Output: bar
    PHP:
    Can this be done in C++? I tried:
    char arary[1] = {'foo' => 'bar'};
    Code (markup):
    but I get this compile error:

    Thanks!
     
    webmasterplace, Sep 9, 2009 IP
  2. pneulameiro

    pneulameiro Peon

    Messages:
    440
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Unfortunately you can't do this in C++. Perl is an interpreted language and this is the reason that such things (as well as a dynamic index) are allowed.
     
    pneulameiro, Sep 9, 2009 IP
  3. webmasterplace

    webmasterplace Peon

    Messages:
    802
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for the info, is this possible with Java?
    I thought Java is an interpreted language or am I wrong?
     
    webmasterplace, Sep 9, 2009 IP
  4. LogicFlux

    LogicFlux Peon

    Messages:
    2,925
    Likes Received:
    102
    Best Answers:
    0
    Trophy Points:
    0
  5. pneulameiro

    pneulameiro Peon

    Messages:
    440
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    With Java too this is not possible. Java in itself is not interpreted, its bytecodes are interpreted by the java virtual machine.

    Maybe with the map said by the fellow above you can do this in C++.
     
    pneulameiro, Sep 11, 2009 IP
  6. brian65

    brian65 Active Member

    Messages:
    1,172
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    88
    #6
    It isn't possible to index a normal C++ array in the way you asked but it is possible to get quite close to the array index syntax using the C++ map class in the STL. Here's an example:

    #include <string>
    #include <map>

    using namespace std;

    int main()
    {
    map<string, string> MapValues;

    MapValues["foo"] = "bar";
    MapValues["dog"] = "rover";
    MapValues["cat"] = "felix";

    return 0;
    }

    This does allow dynamic creation of array-like structured data that can be indexed by strings.
     
    brian65, Sep 11, 2009 IP
  7. webmasterplace

    webmasterplace Peon

    Messages:
    802
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Thanks, I'll try it with this map class.
     
    webmasterplace, Sep 11, 2009 IP
  8. LogicFlux

    LogicFlux Peon

    Messages:
    2,925
    Likes Received:
    102
    Best Answers:
    0
    Trophy Points:
    0
  9. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #9
    Vooler, Sep 11, 2009 IP