标签:lse ios font compare size namespace and cloc map
map和set的区别在于,前者key和value是分开的,前者的key不会重复,value可以重复;后者的key即为value,后者的value不允许重复。还有,map在插入时可以使用 [ ]进行(看插入时代码),其采用了看起来像是数组插值的方法进行元素的插入。
例程
#include<stdexcept>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<ctime>
#include<map>
using namespace std;
long get_a_target_long()
{
long target = 0;
cout<<"target(0~"<<RAND_MAX<<"):";
cin>>target;
return target;
}
string get_a_target_string()
{
long target = 0;
char buf[10];
cout<<"target(0~"<<RAND_MAX<<"):";
cin>>target;
snprintf(buf, 10, "%ld", target);
return string(buf);
}
int compareLongs(const void* a, const void* b)
{
return (*(long*)a - *(long*)b);
}
int compareStrings(const void *a, const void *b)
{
if(*(string*)a > *(string*)b)
return 1;
else if(*(string*)a < *(string*)b)
return -1;
else
return 0;
}
void test_map(long& value)
{
cout << "\ntest_map().......... \n";
map<long, string> c;
char buf[10];
clock_t timeStart = clock();
for(long i=0; i< value; ++i)
{
try
{
snprintf(buf, 10, "%d", rand());
c[i] = string(buf); //表现上像是数组插入值,实际上在其内部会自动将i 和 buf 合成为一个pair进行插入
}
catch(exception& p)
{
cout << "i=" << i << " " << p.what() << endl;
abort();
}
}
cout << "milli-seconds : " << (clock()-timeStart) << endl;
cout << "map.size()= " << c.size() << endl; //元素个数
cout << "map.max_size()= " << c.max_size() << endl;
long target = get_a_target_long();
timeStart = clock();
auto pItem = c.find(target);
cout << "c.find(), milli-seconds : " << (clock()-timeStart) << endl;
if (pItem != c.end())
cout << "found, value=" << (*pItem).second << endl;
else
cout << "not found! " << endl;
}
int main()
{
long int value;
cout<<"how many elements: ";
cin>>value;
test_map(value);
return 0;
}
运行结果
标签:lse ios font compare size namespace and cloc map
原文地址:https://www.cnblogs.com/area-h-p/p/12015932.html