C++映射和unordered_map初始化为一些键及其各自的映射值。
例子:
Input :
Map : 1 -> 4, 2 -> 6, 4 -> 6
Check1 : 5, Check2 : 4
Output : 5 : Not present, 4 : Present
C++实现:
map
// CPP code to check if a
// key is present in a map
#include
using namespace std;
// Function to check if the key is present or not
string check_key(map m, int key)
{
// Key is not present
if (m.find(key) == m.end())
return "Not Present";
return "Present";
}
// Driver
int main()
{
map m;
// Initializing keys and mapped values
m[1] = 4;
m[2] = 6;
m[4] = 6;
// Keys to be checked
int check1 = 5, check2 = 4;
// Function call
cout << check1 << ": " << check_key(m, check1) << '\n';
cout << check2 << ": " << check_key(m, check2);
}
unordered_map
// CPP code to check if a key is present
// in an unordered_map
#include
using namespace std;
// Function to check if the key is present or not
string check_key(unordered_map m, int key)
{
// Key is not present
if (m.find(key) == m.end())
return "Not Present";
return "Present";
}
// Driver
int main()
{
unordered_map m;
// Initialising keys and mapped values
m[1] = 4;
m[2] = 6;
m[4] = 6;
// Keys to be checked
int check1 = 5, check2 = 4;
// Function call
cout << check1 << ": " << check_key(m, check1) << '\n';
cout << check2 << ": " << check_key(m, check2);
}
输出:
5: Not Present
4: Present
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。