如何声明std map常量ie,
int a[10] = { 1, 2, 3 ,4 };
std::map <int, int> MapType[5] = { };
int main()
{
}
Run Code Online (Sandbox Code Playgroud)
在about片段中,可以给整数数组a赋值1,2,3,4 ,类似地如何声明一些常量MapType值而不是在main()函数中添加值.
更新:使用C++ 11以后你可以......
std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };
Run Code Online (Sandbox Code Playgroud)
......或类似的,其中每对值 - 例如{1, 5}- 编码一个键1- 和一个映射到的值 - 5.同样适用于unordered_map(哈希表版本).
仅使用C++ 03标准例程,请考虑:
#include <iostream>
#include <map>
typedef std::map<int, std::string> Map;
const Map::value_type x[] = { std::make_pair(3, "three"),
std::make_pair(6, "six"),
std::make_pair(-2, "minus two"),
std::make_pair(4, "four") };
const Map m(x, x + sizeof x / sizeof x[0]);
int main()
{
// print it out to show it works...
for (Map::const_iterator i = m.begin();
i != m.end(); ++i)
std::cout << i->first << " -> " << i->second << '\n';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19741 次 |
| 最近记录: |