C++ primer 5th 第1章 开始
=====================================================================
第1章 开始 002页
=====================================================================
//QQ108201645编写
#include <iostream>//包含预处理文件
int main()//主函数main
{
//退出并返回一个0
return 0;
}
=====================================================================
第1章 开始 005页(求2个数和)
=====================================================================
//QQ108201645编写
#include <iostream>//包含预处理文件
int main()//主函数main
{
//前缀std::指出名字cout和endl是定义在std的命名空间的 ::代表是作用域
std::cout << "Enter two numbers:" << std::endl;//显示:请输入两个数
int v1 = 0, v2 = 0;//定义2个int 整形变量并初始为0
std::cin >> v1 >> v2;//接受2个int 整形变量
std::cout << "The Sum of " << v1 << " and " << v2//打印并把v1+v2的结果计算输出
<< " is " << v1 + v2 << std::endl;
//system("pause");//暂停
//退出并返回一个0
return 0;
}
=====================================================================
第1章 开始 010页(while循环求和)
=====================================================================
//QQ108201645编写
#include <iostream>//包含预处理文件
int main()//主函数main
{
int sum = 0, val = 1;
//只要val的值小等于10,while就会循环执行
while (val <= 10)//条件:val<=10循环
{
sum += val;//将sum+val的结果赋值sum
++val;//将val自加1(前置++)
}
std::cout << "Sum of 1 to 10 inclusive is"
<< sum << std::endl;//打印输出
//system("pause");//暂停
//退出并返回一个0
return 0;
}
=====================================================================
第1章 开始 011页(for循环求和)
=====================================================================
//QQ108201645编写
#include <iostream>//包含预处理文件
int main()//主函数main
{
int sum = 0;
//从1加到10
for (int val = 1; val <= 10; ++val)//初始val变量等于1,当val小于10,val自加1
{
sum += val;//可以看成sum=sum+val
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;//打印输出
//system("pause");//暂停
//退出并返回一个0
return 0;
}
=====================================================================
第1章 开始 013页(while循环输入求和)
=====================================================================
//QQ108201645编写
#include <iostream>
int main()
{
int sum = 0, value = 0;
//读取数据直到遇到文件尾,计算所有读入的值 的和
while (std::cin >> value)//连续输入数字,中间空格,vs2017用ctrl+z回车结束
{
sum += value;//等价于sum=sum+val
}
std::cout << "Sum is " << sum << std::endl;//std::cout为输出语句,std::endl为换行
//前缀std::指出名字cout与endl定义在名为std的命名空间namespace,可以避免不经义的名字定义冲突
system("pause");//暂停
return 0;
}
=====================================================================
第1章 开始 015页(while循环输入统计个数) // 用ctrl+z回车结束
=====================================================================
//QQ108201645编写
#include <iostream>
int main()
{
//currVal是我们正在统计的数;我们将读入的新值存入val
int currVal = 0, val = 0;
//读入第一个数,并确保确实有数据可以处理
if (std::cin >> currVal)
{
int cnt = 1;//保存我们正在处理的当前个数(计数器)
while (std::cin>>val)//接收读取下一个数
{
if (val==currVal)//如果相同
{
++cnt;//将cnt+1
}
else
{
//否则打印前一个值出现的个数
std::cout << currVal << " occurs "
<< cnt << " times " << std::endl;
currVal = val;//记住新值
cnt = 1;//计数器置1
}
}//while循环在这里结束
//打印最后一个值的个数
std::cout << currVal << " occurs "
<< cnt << " times " << std::endl;
}//最外层的if结束
system("pause");//暂停
return 0;
}
=====================================================================
//QQ108201645编写
//保存为Version_test.h头文件
#ifndef VERSION_TEST_H
#define VERSION_TEST_H
/* As of the first printing of C++ Primer, 5th Edition (July 2012),
* the Microsoft Complier did not yet support a number of C++ 11 features.
*
* The code we distribute contains both normal C++ code and
* workarounds for missing features. We use a series of CPP variables to
* determine whether a given features is implemented in a given release
* of the MS compiler. The base version we used to test the code in the book
* is Compiler Version 17.00.50522.1 for x86.
*
* When new releases are available we will update this file which will
* #define the features implmented in that release.
*/
#if _MSC_FULL_VER == 170050522 || _MSC_FULL_VER == 170050727
// base version, future releases will #define those features as they are
// implemented by Microsoft
/* Code in this delivery use the following variables to control compilation
Variable tests C++ 11 Feature
CONSTEXPR_VARS constexpr variables
CONSTEXPR_FCNS constexpr functions
CONSTEXPR_CTORS constexpr constructors and other member functions
DEFAULT_FCNS = default
DELETED_FCNS = delete
FUNC_CPP __func__ local static
FUNCTION_PTRMEM function template with pointer to member function
IN_CLASS_INITS in class initializers
INITIALIZER_LIST library initializer_list<T> template
LIST_INIT list initialization of ordinary variables
LROUND lround function in cmath
NOEXCEPT noexcept specifier and noexcept operator
SIZEOF_MEMBER sizeof class_name::member_name
TEMPLATE_FCN_DEFAULT_ARGS default template arguments for function templates
TYPE_ALIAS_DECLS type alias declarations
UNION_CLASS_MEMS unions members that have constructors or copy control
VARIADICS variadic templates
*/
#endif // ends compiler version check
#ifndef LROUND
inline long lround(double d)
{
return (d >= 0) ? long(d + 0.5) : long(d - 0.5);
}
#endif
#endif // ends header guard
―――――――――――――――――――――――――――――――――――――――
//定义为Sales_item.h头文件
#ifndef SALESITEM_H//未定义SALESITEM_H则继续向下执义
// we're here only if SALESITEM_H has not yet been defined
#define SALESITEM_H
#include "Version_test.h"
// Definition of Sales_item class and related functions goes here
#include <iostream>
#include <string>
class Sales_item {
// these declarations are explained section 7.2.1, p. 270
// and in chapter 14, pages 557, 558, 561
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&, const Sales_item&);
friend bool
operator==(const Sales_item&, const Sales_item&);
public:
// constructors are explained in section 7.1.4, pages 262 - 265
// default constructor needed to initialize members of built-in type
#if defined(IN_CLASS_INITS) && defined(DEFAULT_FCNS)
Sales_item() = default;
#else
Sales_item() : units_sold(0), revenue(0.0) { }
#endif
Sales_item(const std::string &book) :
bookNo(book), units_sold(0), revenue(0.0) { }
Sales_item(std::istream &is) { is >> *this; }
public:
// operations on Sales_item objects
// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& operator+=(const Sales_item&);
// operations on Sales_item objects
std::string isbn() const { return bookNo; }
double avg_price() const;
// private members as before
private:
std::string bookNo; // implicitly initialized to the empty string
#ifdef IN_CLASS_INITS
unsigned units_sold = 0; // explicitly initialized
double revenue = 0.0;
#else
unsigned units_sold;
double revenue;
#endif
};
// used in chapter 10
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs)
{
return lhs.isbn() == rhs.isbn();
}
// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);
inline bool
operator==(const Sales_item &lhs, const Sales_item &rhs)//==运算符重载
{
// must be made a friend of Sales_item
return lhs.units_sold == rhs.units_sold &&
lhs.revenue == rhs.revenue &&
lhs.isbn() == rhs.isbn();
}
inline bool
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
return !(lhs == rhs); // != defined in terms of operator==
}
// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)//'+='重载
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)//'+'重载
{
Sales_item ret(lhs); // copy (|lhs|) into a local object that we'll return
ret += rhs; // add in the contents of (|rhs|) 调用+=重载
return ret; // return (|ret|) by value 返回临时对象
}
std::istream&
operator>>(std::istream& in, Sales_item& s)//重载输入运算符
{
double price;
in >> s.bookNo >> s.units_sold >> price;//接受书的编号、数量、价格
// check that the inputs succeeded
if (in)//输入不等于空、比如输入ctrl+z再回车
s.revenue = s.units_sold * price;//收入等于数量乘价格
else
s = Sales_item(); // input failed: reset object to default state
//调用构造函数重置为默认。
return in;
}
std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{
out << s.isbn() << " " << s.units_sold << " "
<< s.revenue << " " << s.avg_price();
return out;
}
double Sales_item::avg_price() const
{
if (units_sold)//除数不等于0
return revenue / units_sold;
else
return 0;
}
#endif
=====================================================================
第1章 开始 018页(读写Sales_item.h)
=====================================================================
//QQ108201645编写
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item book;
//读入ISBN号、售出的册数以销售的价格
std::cin >> book;
//写入ISBN、售出的册数、总销售额和平均价格
std::cout << book << std::endl;
system("pause");
return 0;
}
//如果输入 0-201-70353-x 4 24.99
//则输出 0 - 201 - 70353 - x 4 99.96 24.99
=====================================================================
第1章 开始 019页(Sales_item.h对象的加法)
=====================================================================
//QQ108201645编写
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;//重载输入运算符(调用)
std::cout << item1 + item2 << std::endl;//调用'+'运算符重载
system("pause");//暂停
return 0;
}
//如果输入 0-201-78345-x 3 20.00
// 0-201-78345-x 2 25.00
//则输出 0-201-78345-x 5 110 22
=====================================================================
第1章 开始 020页(检查Sales_item.h对象的书名是否一样,是就输出相加结果)
=====================================================================
//QQ108201645编写
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
//首先检查item1与item2是否是相同的书
if (item1.isbn()==item2.isbn())
{
std::cout << item1 + item2 << std::endl;
return 0;//表示成功
}
else
{
std::cerr << " Data must refer to same ISBN"
<< std::endl;
return -1;//表示失败
}
}
=====================================================================
第1章 开始 021页(Sales_item.h书店程序)
=====================================================================
//QQ108201645编写
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item total;//保存下一条交易记录的变量
//读入第一条交易记,并确保有数据可以处理
if (std::cin>>total)
{
Sales_item trans;//保存和的变量
//读入并处理剩余的交易记录
while (std::cin>>trans)
{
if (total.isbn()==trans.isbn())
{
total += trans;//更新总销售额
}
//打印前一本的情况
else
{
std::cout << total << std::endl;
total = trans;
}
}
std::cout << total << std::endl;
}
else
{
//没有输入!警告读者
std::cerr << " No data?!" << std::endl;
return -1;
}
system("pause");
return 0;
}
=====================================================================
追加内容(要记住的东西)
=====================================================================
//QQ108201645编写
前缀符号表
前缀 | 数据类型(基本单位) |
c | 字符 |
by | 字节 |
n | 短整数和整数 |
i | 整数 |
b | 布尔型 |
w | 无符号字 |
l | 长整数 |
dw | 无符号长整数 |
fn | 函数指针 |
s | 串 |
sz | 以0为结束的字符串 |
lp | 32位长整数指针 |
h | 句柄 |
msg | 消息 |
C++基本数据类型
数据类型 | 类型描述 | 占字节数 | 取值 |
char | 字符型 | 1 | -128~127 |
unsigned char | 无符号字符型 | 1 | 0~255 |
signed char | 有符号字符型 | 1 | -128~127 |
int | 整型 | 4 | -231~231-1 |
unsigned[int] | 无符号短整型 | 4 | 0~231-1 |
short[int] | 短整型 | 2 | -32768~32767 |
unsigned short[int] | 无符号短整形 | 2 | 0~65535 |
unsigned long[int] | 无符号长整型 | 4 | 0~231-1 |
signed long[int] | 有符号长整型 | 4 | -231~231-1 |
float | 单精度浮点型 | 4 | -3.4e38~3.4e38 |
double | 双精度浮点型 | 8 | -1.7e308~1.7e308 |
long double | 长双精度浮点型 | 10 | -1.1e4932~1.1e4932 |
void | 无值型 | 0 | {} |
bool | 逻辑型 | 1 | {false,true} |
//QQ108201645编写
算术运算符
运算符 | 运算符名称 | 功能 | 实例 | 结果 |
+ | 加法运算符 | 表示两个数相加 | a+b | 14 |
- | 减法运算符 | 表示两个数相减 | a-b | 6 |
* | 乘法运算符 | 表示两个数相乘 | a*b | 40 |
/ | 除法运算符 | 表示两个数相除 | a/b | 2.5 |
% | 模运算符 | 表示取模 | a%b | 2 |
++ | 增量运算符 | 表示数自身加1 | a++ | 11 |
-- | 减量运算符 | 表示数自身减1 | a-- | 9 |
复合赋值运算符
&,|,^记住一下口诀就可以了
& 见0出0,全1出1
| 见1出1,全0出0
^ 相同出0,不同出1
运算符 | 使用方法 | 附加说明 | 等效形式 | 说明 |
+= | a+=b | Empty | a=a+b | 将a+b的值赋给a |
-= | a-=b | Empty | a=a-b | 将a-b的值赋给a |
*= | a*=b | Empty | a=a*b | 将a*b的值赋给a |
/= | a/=b | Empty | a=a/b | 将a/b的值赋给a |
%= | a%=b | a等于a除b的余数 | a=(a%b) | 将a除b的余数赋给a |
<<= | a<<=b | Empty | a=(a<<b) | 将a左移b位的值赋给a |
>>= | a>>=b | Empty | a=(a>>b) | 将a右移b位的值赋给a |
&= | a&=b | a与b转二进制,见0出0,全1出1,结果赋值给a | a=(a&b) | 将a与b位逐位与的值赋给a |
|= | a|=b | a与b转二进制,见1出1,全0出0,结果赋值给a | a=a|b | 将a与b位逐位或的值赋给a |
^= | a^=b | a与b转二进制,二进制相同出0,不同出1,结果赋值给a | a=a^b | 将a与b位逐位异或的值赋给a |
关系运算符
运算符 | 运算符名称 | 功能 | 实例 | 结果 |
< | 小于 | 若a<b,结果为true,否则为false | 2<3 | true |
<= | 小等于 | 若a<=b,结果为true,否则为false | 7<=3 | false |
> | 大于 | 若a>b,结果为true,否则为false | 7>3 | true |
>= | 大等于 | 若a>=b,结果为true,否则为false | 3>=3 | true |
== | 相等于 | 若a==b,结果为true,否则为false | 7==3 | false |
!= | 不等于 | 若a!=b,结果为true,否则为false | 7!=3 | true |
//QQ108201645编写
逻辑运算符
运算符 | 运算符名称 | 功能 | 实例 | 结果 |
! | 逻辑非 | 当运算分量为false时,结果为true 当运算分量为true时,结果为false | !0 !1 | true false |
&& | 逻辑与 | 当两个运算分量都为true时,结果为true | 0&&0 0&&1 1&&1 | false false true |
|| | 逻辑或 | 当两个运算分量有一个为true时,结果为true | 0||0 0||1 1||1 | false true true |
位运算符
运算符 | 运算符名称 | 功能 | 实例 | 结果 |
& | 按位与 | 表示a与b按位与 | 二进制1001&0101 | 二进制0001 |
| | 按位或 | 表示a与b按位或 | 二进制1001|0101 | 二进制1101 |
^ | 按位异或 | 表示a与b按位异或 | 二进制1001^0101 | 二进制1100 |
>> | 右移位 | 表示a右移b位 | 二进制1001>>2 | 二进制0010 |
<< | 左移位 | 表示a左移b位 | 二进制1001<<1 | 二进制0010 |
~ | 按位取反 | 表示a按位取反 | 二进制~1001 | 二进制0110 |
说明:按位取反1001取反后是0110
另一个是一个数9转二进制1001取反0110-1=0101,再取反加负号1010=10
//QQ108201645编写
运算符优先级
优先级 | 运算符 | 功能说明 | 结合性 |
1 | () | 改变优先级 | 从左至右 |
:: | 作用域运算符 | ||
[] | 数组下标 | ||
. ,-> | 成员选择 | ||
.* , ->* | 成员指针选择 | ||
2 | ++,-- | 增1减1运算符 | 从右至左 |
& | 取地址 | ||
* | 取内容 | ||
! | 逻辑求反 | ||
~ | 按位求反 | ||
+,- | 取正数,取负数 | ||
() | 强制类型 | ||
sizeof | 取所占内存字节数 | ||
new 和delete | 动态存储分配 | ||
3 | * , / , % | 乘法,除法,取余 | 从左至右 |
4 | +,- | 加法,减法 |
|
5 | <,<= | 小于,小等于 |
|
6 | >,>= | 大于,大等于 |
|
7 | ==,!= | 相等于,不等于 |
|
8 | & | 按位与 |
|
9 | ^ | 按位异或 |
|
10 | | | 按位或 |
|
11 | && | 逻辑与 |
|
12 | || | 逻辑或 |
|
13 | ?: | 三目运算法 | 从右至左 |
14 | =,+=,-=,*=,/=,%=, &=,^=,|=,<<=,>>= | 赋值运算法 | 从右至左 |
15 | , | 逗号运算符 | 从左至右 |
//QQ108201645编写
常用I/O流控制符
包含文件头include<iomanip>
控制符 | 描述 | 等同于 |
dec | 置基数为10 |
|
hex | 置基数为16 |
|
oct | 置基数为8 |
|
setfill(c) | 设填充字符为c | cout.fill(n) |
setprecision(n) | 设显示小数精度为n位 | cout.precision |
setw(n) | 设域宽为n个字符 | cout.width(n) |
setiosflags(ios::fixed) | 固定浮点显示 |
|
setiosflags(ios::scientific) | 指数显示 |
|
setiosflags(ios::left) | 左对齐 |
|
setiosflags(ios::right) | 右对齐 | cout.flags(ios::right) |
setiosflags(ios::skipws) | 忽略前导空白 |
|
setiosflags(ios::uppercase) | 十六进制大写输出 |
|
setiosflags(ios::lowercase) | 十六进制小写输出 |
|
浅析递归调用
//QQ108201645编写
=====================================================================
#include <iostream>
using namespace std;
int Fac(int n)
{
if (n < 0)
{
cout << "error" << endl;
return -1;
}
else if (n <= 1)//当n小等于1时终止调用自身并回归原数
{
return 1;
}
else
return (n*Fac(n - 1));//当n大于1时调用自身
}
int main()
{
int Fac(int i);//声明函数
int n;//定义整型变量n
cout<<"input n:"<<endl;
cin >> n;
cout << "n!=" << Fac(n) << endl;
return 0;
}
=====================================================================
//QQ108201645编写
分析:假设输入是5
当5>1时都是调用
else
return (n*Fac(n - 1));//当n大于1时调用自身
那流程就是
递推流程 | 回归流程 |
Fac(5)=5*Fac(5-1)=5*Fac(4) | Fac(1)=1 |
Fac(4)=4*Fac(4-1)=4*Fac(3) | Fac(2)=2*Fac(1)=2 |
Fac(3)=3*Fac(3-1)=3*Fac(2) | Fac(3)=3*Fac(1)=6 |
Fac(2)=2*Fac(2-1)=2*Fac(1) | Fac(4)=4*Fac(1)=24 |
Fac(1)=1 | Fac(5)=5*Fac(1)=120 |
5*Fac(5-1)
5*(4*(Fac(4-1))
5*(4*(3*( Fac(3-1)))
5*(4*(3*( 2*( Fac -1))))
5*(4*(3*( 2*(当是1时直接返回1))))
那就是5*(4*(3*(2*1)))
5*(4*(3*2))
5*(4*6)
5*24
结果=120
=====================================================================
//递归练习
#include<iostream>
using namespace std;
int power_(int num, int frequency)
{
if (frequency < 0)
return -1;
else if (frequency == 0)
return 1;
else
return num * power_(num, frequency - 1);
}
int main()
{
int num, frequency;
cout << "输入一个数与多少次幂" << endl;
cin >> num >> frequency;
for (int i = 1; i <= frequency; ++i)
cout << "输出" << i << "次幂结果:" << power_(num, i) << endl;
return 0;
}
=====================================================================
//QQ108201645编写
编译预处理
编译预处理命令 | 说明 |
#define | 宏定义 |
#error | 在编译中遇到#error就停止 |
#if | 判定标识符是否为true |
#else | 当#if,为false时执行这个else |
#elif |
|
#endif | 结束if相关的判定 |
#ifdef | 已定义标识符则继续 |
#ifndef | 未定义标识符则继续 |
#undef | 取消宏定义 |
#line | 控制行号,提示出错信息位置 |
#pragma | 布局控制 |
=====================================================================
char字符串处理
包含文件头include<string>
strcpy(a,b) //把b的字符串复制到a
strncpy(a,b,size) //把b的字符串复制到a,长度为size
strcmp(a,b) //比较a与b内的字符串是否相同,比b大则返回1,比b小则返回-1,相同返回0
strcat(a,b) //把b的字符串与a相连,a=a+b的字符串
strlen(a) //得到a字符串的长度
strupr(a) //小写转大写
strlwr(a) //大写转小写
注:memcpy(a,b,size)功能与strncpy相似,但属于内存操作,功能更强大
memset(a,0,size)//表示a字符串起始位置,长度为size的全部填充为0
memcpy(a+locat,b+locat,2) //表示b字符串+位置偏移值开始读取,从a字符串+位置偏移值开始写入,长度为2字节。
函数原形strtod(const char* nptr,char **endptr)
假设string s1=”123456abc”;
char *p;
int number=strtod(&s1[0],&p)
number中的数将等于123456,p指针将指向’a’的位置
=====================================================================
冒泡,插入排序
=====================================================================
//QQ108201645编写
#include <iostream>
#include <ctime>
#include <string>
//冒泡排序
int* Bubble_sort(int data[], int len)
{
std::cout << "顺序从小到大:";
for (int i = 0; i < len - 1; i++)//i初始化0,循环到长度减1
for (int j = i + 1; j < len; ++j)//j初始化等于下一个位置,到长度相等结束
if (data[i] > data[j])//如果当前比下一个位置大则进入对调//经过不断对调,i位置的值最小
{
int t = data[i];
data[i] = data[j];
data[j] = t;
}
return data;
}
//插入排序
int *Insert_Sort(int data[], int len)
{
std::cout << "顺序从大到小:";
for (int i = 1; i < len; ++i)
{
int temp = data[i];//初始化等于i当前位置
int j = i - 1;//j等于前一个位置
while (data[j] < temp&&j >= 0)//当上一个小于当前位置的值,并且j>=0则进入循环
//直到找到当前最大值或者j<0
{
data[j + 1] = data[j];//当前等于上一个位置的值
j--;
}
data[j + 1] = temp;//j--后跳出的j+1是等于这个小于temp的位置
//如果进入while循环,则最前面小于temp的值替换成这个值
//如果未进入,则i位置自己赋值
}
return data;
}
int main()
{
void Display(int data[], int len);
int data[] = { 11,44,2,35,68,94,14,20 };
int len = sizeof(data) / sizeof(int);
int data1[8];
memcpy(data1, data, 4 * 8);
clock_t start_, end_;//定义2个clock_t对象
start_ = clock();//初始时间
Display(Bubble_sort(data, len), len);//调用冒泡排序
end_ = clock();//结束时间
std::cout << "调用冒泡排序用了" << (double)(end_ - start_) / CLOCKS_PER_SEC << "秒" << std::endl;
memcpy(data, data1, 4 * 8);
start_ = clock();//初始时间
Display(Insert_Sort(data, len), len);//调用插入排序
end_ = clock();//结束时间
std::cout << "调用插入排序用了" << (double)(end_ - start_) / CLOCKS_PER_SEC << "秒" << std::endl;
system("pause");
return 0;
}
void Display(int data[], int len)
{
for (int i = 0; i < len; i++)
{
std::cout << data[i] << " ";
}
std::cout << std::endl;
}
=====================================================================
二分法查找
//QQ108201645编写
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main()
{//数组如果是无序的就要进行大小排序
int num[15] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
cout << "please input the number"<<endl;
int key;//输入查找的值
cin >> key;
int low = 0;//表示第一个元素位置
int high = 14;//表示最后一个元素的位置
while (low<=high)
{
int mid = (low + high) / 2;//mid等于最低位+最高位置的和除一半
if (key==num[mid])
{
cout << "The location is: " << mid + 1 << endl;//因为数组偏移值从0开始所以+1显示
break;//找到后退出
}
else if (key<num[mid])//key的值比num的一半mid当前值小的话,说明mid值还太大
{
high = mid - 1;//把一半的数减1赋值给最大的数,到下次就是一半的一半
}//如果没有减1加1操作,输入查找的数如果大于或小于本身的数的话会进入死循环
else//key的值比num的一半mid当前值大的话,说明mid值还太小
{
low = mid+1 + 1;//把最小值+1赋值给最小的数
}
}
if (low>=high)//如果大于high表示没找到
{
cout<<"It's not in the array"<<endl;
}
system("pause");
return 0;
}
=====================================================================
数字字符串转十六进制
//QQ108201645编写
#include <iostream>
#include <string>
#include<cctype>
using namespace std;
void SetHexToStr(char* hex_, string str)
{
for (string::iterator ix=str.begin();ix!=str.end();ix=ix+2)
{
basic_string<char> tmp = str.substr(ix-str.begin(), 2);//截取两个字符给tmp
char* s = NULL;
char i = (char)(strtol(tmp.c_str(), &s, 16));//转十六进制赋给i
memcpy(hex_, &i, 1);//再把i复制一个字符转给hex_
hex_++;//地址自加一
}
}
int main()
{
char p[256] = { "123456" };//数字转十六进制
char *newstr = new char[1024]{ 0 };
SetHexToStr(newstr, p);
cout << newstr << endl;
}
=====================================================================
#include <string>
#include <time.h>
#include <iostream>
using namespace std;
#pragma warning(disable:4996)
string getTime()
{//获取系统时间
time_t timep;//创建timep对象
time(&timep);//获取系统时间,返回一个指针
/*time_t time(time_t *seconds) 返回自纪元 Epoch(1970-01-01 00:00:00 UTC)起经过的时间,
以秒为单位。如果 seconds 不为空,则返回值也存储在变量 seconds 中。
seconds -- 这是指向类型为 time_t 的对象的指针,用来存储 seconds 的值。*/
char tmp[64];
struct tm * p = localtime(&timep);
cout<<asctime(p)<<endl;//把时间转成字符串
strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S", p);
//格式化结构 *p 表示的时间,并把它存储在 tmp 中。最大字符数为sizeof(tmp)
return tmp;
}
int main()
{
string time = getTime();
cout << time << endl;
system("pause");
return 0;
}
=====================================================================
字符串转十六进制字符串
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
const string Hex = "0123456789abcdef";
string HexToStr(string& s)//十六进制转字符
{
size_t i = 0;
string buf;
for (auto c : s)
{
buf.push_back(Hex[(c & 0xf0) >> 4]);//提取高位对应字符
buf.push_back(Hex[(c & 0xf)]);//提取低位对应字符
}
return buf;
}
string StrToHex(string& s)//字符转十六进制
{
string buf,str;
int num;
for (size_t i = 0; i < s.size(); i += 2)
{
string buf = s.substr(i, 2);//每次截取两个字符
num = stoi(buf,0,16);//把当前的两个字符以十六进制输出并赋值给num
str.push_back(num);
}
return str;
}
void ShowStr(const string& s)
{
size_t i = 0;
for_each(s.begin(), s.end(), [=](char a)mutable {cout << a; i++; if (i & 2) { cout << " "; i = 0; } });
cout << endl;
}
void ShowInt(const string& s)
{
for_each(s.begin(), s.end(), [](char a) {cout << hex << (int)a << " "; });
cout << endl;
}
int main()
{
string s = "0123456789abcdefj";
cout <<"s ="<< s << endl;
string buf=HexToStr(s);
cout << "buf =" << buf << endl;
ShowStr(buf);
buf = StrToHex(buf);
ShowInt(buf);
cout << "buf =" << buf << endl;
system("pause");
return 0;
}