c++示例大全

2014-08-28 00:53  2869人阅读  评论 (0)
Tags: c++

map

#require <map>

// map 创建
map<int, int> m;

// 添加
for (int i=0; i<10; i++) {
    m[i] = i*i;
}

// map遍历 并修改
for (auto it=m.begin(); it!=m.end(); ++it) {
    cout << it->first << ":" << it->second << endl;
}

// map遍历 并修改
for (auto it=m.begin(); it!=m.end();) {
    cout << it->first << ":" << it->second << endl;
    m.erase(it++);
}

time

#require <time.h>

// 当前时间戳
time_t tt = time(nullptr);
printf("%ld\n", tt);

// 获取当前时间毫秒


// 格式化时间

string memory

// 字符串copy
char str1[] = "hello hello";
char str2[] = "world";
strcpy(str1+6, str2);
printf("%s\n", str1);

// hello world

// 字符串copyN
char str1[] = "xxxxxxxxxxx";
char str2[] = "hello world";
str2[5] = 0;
strncpy(str1, str2, sizeof(str2));
for (int i=0; i<sizeof(str1); i++) {
    printf("%2x ", str1[i]);
}
printf("\n");

// 68 65 6c 6c 6f 0 0 0 0 0 0 0

// 内存copy
char str1[] = "xxxxxxxxxxx";
char str2[] = "hello world";
str2[5] = 0;
memcpy(str1, str2, sizeof(str2));
for (int i=0; i<sizeof(str1); i++) {
    printf("%2x ", str1[i]);
}
printf("\n");

// 68 65 6c 6c 6f  0 77 6f 72 6c 64  0 

// 内存移动 左移
char str1[] = "0123456789";
memmove(str1, str1+7, 4);
for (int i=0; i<sizeof(str1); i++) {
    printf("%2x ", str1[i]);
}
printf("\n");

// 37 38 39  0 34 35 36 37 38 39  0

// 内存移动 右移
char str2[] = "0123456789";
memmove(str2+4, str2, 7);
for (int i=0; i<sizeof(str2); i++) {
    printf("%2x ", str2[i]);
}
printf("\n");

// 30 31 32 33 30 31 32 33 34 35 36
豫ICP备09035262号-1