4

I'm looking for a C++ equivalent for the following PHP code

$obj = new stdClass();
$obj->test = "aaaa";
$var = "test";
echo $obj->{$var};

Is even possible in C? I keep looking for hours and no luck.

Thank you

user2035693
  • 193
  • 2
  • 16

1 Answers1

6

Try:

#include <unordered_map>
#include <iostream>
#include <string>

using namespace std;

int main() {
    unordered_map<string, string> obj;
    obj["test"] = "aaaa";
    string var = "test";
    cout << obj[var] << endl;
}

It's not quite the same, as test is a string in both cases here. If it's the difference between "test" and plain test that's important then the answer becomes a bit more complicated.

See also: How to choose between map and unordered_map? to explain the discussion in the comments.

Community
  • 1
  • 1
JCx
  • 2,689
  • 22
  • 32