问题总结
任务需要返回某个map的所有key的集合用于迭代,key值为非连续int。
Code
#include <iostream>
#include <map>
#include <vector>
using namespace std;
// 返回以对应类型的key的vector
vector<int> KeySet(map<int, float> test)
{
vector<int> keys;
for(map<int, float>::iterator it = test.begin(); it != test.end(); ++it){
keys.push_back(it->first);
}
return keys;
}
int main() {
map<int , float> test;
test[0] = 0.1;
test[2] = 0.2;
test[3] = 0.3;
for(auto key: KeySet(test)){
cout << key << endl;
}
return 0;
}
测试结果
使用CLion的运行结果
C:\Users\liangyi\CLionProjects\test\cmake-build-debug\test.exe
0
2
3
Process finished with exit code 0