Given the C++ vector as below:
vector<double> weight;
weight.resize(128, 0);
Can weight be u开发者_开发百科sed 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?
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.
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.
So I understand that char literals are turned into Integers. Does C++ support extended ASCII table ?? For example if I had a
char * blah = 'z'+'z';
what would happen ??? eg.
'z' = 122 in ASCII
therefore
'z'+'z' = 244 ?? or ??
You should not.
Use std::map
for that purpose
For example
std::map<char,double> Weight;
Weight.insert(std::make_pair('A',500.98)); //include <algorithm>
Weight.insert(std::make_pair('P',455.49));
std::cout<< Weight['A']; //prints 500.98
You can also iterate over the map
using std::map<char,double>::iterator
For example
std::map<char,double>::iterator i = Weight.begin();
for(; i != Weight.end(); ++i)
std::cout << "Weight[" << i->first << "] : " << i->second << std::endl;
/*prints
Weight['A'] : 500.98
Weight['P'] : 455.49
*/
If you want this, you could use a std::map<char, double>
. Technically, it would also be possible using a std::vector<double>
, but there'd be all sorts of integral conversions from characters to integers and the program would just be confusing.
精彩评论