Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ map array key auto increase

Tags:

c++

arrays

In php when you want to create array, by using this:

$Data[] = "Val1";
$Data[] = "Val1";
$Data[] = "Val1";

php set auto key 0, 1, 2 for this array. I want to know what should I do in c++ in map types or other array types to set int keys auto from 0 to unlimited?

In c++ is something like this:

map<int, string> Data;

Data[0] = "val1";
Data[1] = "val1";
Data[2] = "val1";

I have to set key myself!

Is there any way to create struct or template and using that with map?

like image 742
user216085 Avatar asked Jun 24 '26 16:06

user216085


2 Answers

IIUC, you want to use vector:

#include <vector>
#include <string>

...

using namespace std;

...

vector<string> Data;
Data.push_back("val1");
Data.push_back("val1");
Data.push_back("val1");

// Now you can access the inserted elements via Data[i]

See a full example to using this container on this page.

like image 159
Ami Tavory Avatar answered Jun 26 '26 07:06

Ami Tavory


You can use variable:

map<int, string> Data;
int counter = 0;
Data[counter++] = "val1";
Data[counter++] = "val1";
Data[counter++] = "val1";
like image 44
marcinj Avatar answered Jun 26 '26 06:06

marcinj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!