Joe96
Joe96

Reputation: 17

Add name to an array location in C++

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.

Upvotes: 0

Views: 1273

Answers (4)

comingstorm
comingstorm

Reputation: 26097

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;

Upvotes: 0

iksemyonov
iksemyonov

Reputation: 4196

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.

Upvotes: 0

tkausl
tkausl

Reputation: 14269

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>

Upvotes: 0

user197015
user197015

Reputation:

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.

Upvotes: 1

Related Questions