侯捷C++学习笔记——容器分类
本文对应侯捷C++(STL) 03-06小节
0.基本函数
#include<iostream>
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, "%d", 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;
}
几个关键知识点:
- RAND_MAX是C中stdlib.h中宏定义的一个字符常量:#define RAND_MAX Ox7FFF
- snprintf(),函数原型为
int snprintf(char *str, size_t size, const char *format, ...)
// 用法:将可变参数 “…” 按照format的格式格式化为字符串,然后再将其拷贝至str中
- 视频中所提到的qsort函数:
void qsort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*));
//base: Pointer to the first object of the array to be sorted, converted to a void*.
//num: Number of elements in the array pointed to by base. size_t is an unsigned integral type.
//size: Size in bytes of each element in the array.
//compar: Pointer to a function that compares two elements.
//This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:
//int compar (const void* p1, const void* p2);
//Taking two pointers as arguments (both converted to const void*).
//The function defines the order of the elements by returning (in a stable and transitive manner):
//<0: p1 is smaller than p2
//=0:p1 is equal to p2
//>0 p1 is larger than p2
1.Array 容器
视频中使用了 namespace-jj01 作为测试空间,主要的代码段为:
#include <array>
#include <iostream>
#include <ctime>
#include <cstdlib> //qsort, bsearch, NULL
#include <string>
#define ASIZE 100000
using namespace std;
namespace jj01
{
void test_array()
{
cout << "\ntest_array().......... \n";
array<long,ASIZE> c;
clock_t timeStart = clock();
for(long i=0; i< ASIZE; ++i) {
c[i] = rand();
}
cout << "milli-seconds : " << (clock()-timeStart) << endl; //数组初始化用时
cout << "array.size()= " << c.size() << endl; //容器第总大小
cout << "array.front()= " << c.front() << endl; //容器第一个元素
cout << "array.back()= " << c.back() << endl; //容器最后一个元素
cout << "array.data()= " << c.data() << endl; //整个容器数组存放的地址起始点
long target = get_a_target_long();
timeStart = clock();
::