0

in PHP i can give names to values inside an array, so instead of calling the values with a pointer, i can call them with a name. Is something similar possible in C++?

My goal is to take user input, and to return text according to the input, some sort of Q&A.

1

4 Answers 4

1

You could use a std::map or std::unordered_map.

You can use it directly, mapping from "name" (as a std::string probably) to whatever resulting value (sounds like another string, in your case).

std::map<std::string, std::string> stuff;

Or you can use it indirectly, using the maps to map from name to array index.

std::vector<std::string> stuff;
std::map<std::string, std::size_t> stuffIndices;

The latter option is more complex, because you may need to update the map if you rearrange the array or whatnot, but it also lets you keep the contiguous storage of the array if you need to use that property elsewhere in your program.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, it is, but not with an array. In fact, what PHP calls an array is not an array but a (hash)map internally.

In c++ you can use std::map<std::string, T>

Comments

0

While I'm unfamiliar with PHP and the abovementioned mechanism, I can see at least two possible ways to do in C++.

First would be to assign different pointer variables to certain elements in the array like this:

int a[10];
int *myInt = &a[5];

The other possibility is to use a std::map<std::string, T> associative container with T being the type of data you want to store. That gives you labeled items, but at the cost of certain slowdown when accessing elements compared to a plain array.

Comments

0

If I understand your question correctly, yes: you can store a pointer or declare a reference to an array cell.

float my_array[ARRAY_LENGTH];

int index = ARRAY_LENGTH / 2;

float* cell_pointer = &(my_array[index]);
float& cell_reference = my_array[index];

// now you can mutate the cell conveniently
*cell_pointer += 0.6;
cell_reference *= 5.3;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.