鉴于C++向量如下:
vector<double> weight;
weight.resize(128, 0);
Run Code Online (Sandbox Code Playgroud)
重量可以用作:
weight['A'] = 500.98;
weight['P'] = 455.49;
Run Code Online (Sandbox Code Playgroud)
这意味着什么,以及如何使用这些值?谁能举个例子?
字符文字(如"A"和"P")可以使用ASCII值自动转换为整数.所以'A'是65,'B'是66,等等.
所以你的代码是这样的:
weight[65] = 500.98;
weight[80] = 455.49;
Run Code Online (Sandbox Code Playgroud)
你想要这样做的原因是权重数组与字符有关.如果是这样,那么为字符文字赋予权重会使代码比分配给整数更具可读性.但它只是用于"文档",编译器将其视为整数.
代码相当于:
weight[65] = 500.98;
weight[80] = 455.49;
Run Code Online (Sandbox Code Playgroud)
当然,只有当矢量至少包含81个元素时才有效.
你不应该。用于std::map该目的
例如
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
Run Code Online (Sandbox Code Playgroud)
您还可以迭代map使用std::map<char,double>::iterator
例如
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
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9721 次 |
| 最近记录: |