Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need examples on C++ vector usage

Tags:

c++

vector

Given the C++ vector as below:

vector<double> weight;
weight.resize(128, 0);      

Can weight be used as:

weight['A'] = 500.98;
weight['P'] = 455.49;

What does this mean, and how does one use these values? Could anyone give me an example?

like image 322
ladyfafa Avatar asked Aug 14 '10 13:08

ladyfafa


2 Answers

Character literals (like 'A' and 'P') can be automatically converted to integers using their ASCII values. So 'A' is 65, 'B' is 66, etc.

So your code is the same as:

weight[65] = 500.98;
weight[80] = 455.49;

The reason you'd ever want to do this is if the weight array has something to do with characters. If it does, then assigning weights to a character literal makes the code more readable than assigning to an integer. But it's just for "documentation", the compiler sees it as integers either way.

like image 87
SoapBox Avatar answered Nov 14 '22 06:11

SoapBox


The code is equivalent to:

weight[65] = 500.98;
weight[80] = 455.49;

Which of course only works if the vector holds at least 81 elements.

like image 4
sepp2k Avatar answered Nov 14 '22 07:11

sepp2k