0.目录

1.C++标准库

2.字符串类

3.数组操作符的重载

4.小结

1.C++标准库

有趣的重载——操作符 << 的原生意义是按位左移,例:1 << 2;,其意义是将整数1按位左移2位,即0000 0001 ——> 0000 0100

重载左移操作符,将变量或常量左移到一个对象中!

重载左移操作符:

#include <stdio.h>

const char endl = '\n';

class Console
{
public:
Console& operator << (int i)
{
printf("%d", i); return *this;
}
Console& operator << (char c)
{
printf("%c", c); return *this;
}
Console& operator << (const char* s)
{
printf("%s", s); return *this;
}
Console& operator << (double d)
{
printf("%f", d); return *this;
}
}; Console cout; int main()
{
cout << 1 << endl;
cout << "Hello World!" << endl; double a = 0.1;
double b = 0.2; cout << a + b << endl; return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
1
Hello World!
0.300000

C++标准库:

  • C++标准库并不是C++语言的一部分
  • C++标准库是由类库和函数库组成的集合
  • C++标准库中定义的类和对象都位于std命名空间中
  • C++标准库的头文件都不带.h后缀
  • C++标准库涵盖了C库的功能

C++编译环境的组成:

C++标准库预定义了多数常用的数据结构:

使用C++标准库:

#include <iostream>
#include <cmath> using namespace std; int main()
{
cout << "Hello world!" << endl; double a = 0;
double b = 0; cout << "Input a: ";
cin >> a; cout << "Input b: ";
cin >> b; double c = sqrt(a * a + b * b); cout << "c = " << c << endl; return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
Hello world!
Input a: 3
Input b: 4
c = 5

2.字符串类

历史遗留问题:

  • C语言不支持真正意义上的字符串
  • C语言用字符数组和一组函数实现字符串操作
  • C语言不支持自定义类型,因此无法获得字符串类型

解决方案:

  • 从C到C++的进化过程引入了自定义类型
  • 在C++中可以通过类完成字符串类型的定义

C++中的原生类型系统是否包含字符串类型?

标准库中的字符串类:

  • C++语言直接支持C语言的所有概念
  • C++语言中没有原生的字符串类型

C++标准库提供了string类型:

  • string直接支持字符串连接
  • string直接支持字符串的大小比较
  • string直接支持子串查找和提取
  • string直接支持字符串的插入和替换

示例——使用字符串类:

#include <iostream>
#include <string> using namespace std; void string_sort(string a[], int len)
{
for(int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
if( a[i] > a[j] )
{
swap(a[i], a[j]);
}
}
}
} string string_add(string a[], int len)
{
string ret = ""; for(int i=0; i<len; i++)
{
ret += a[i] + "; ";
} return ret;
} int main()
{
string sa[6] =
{
"Hello World",
"C#",
"Java",
"C++",
"Python",
"TypeScript"
}; string_sort(sa, 6); for(int i=0; i<6; i++)
{
cout << sa[i] << endl;
}
cout << endl; cout << string_add(sa, 6) << endl; return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
C#
C++
Hello World
Java
Python
TypeScript C#; C++; Hello World; Java; Python; TypeScript;

字符串与数字的转换——标准库中提供了相关的类对字符串和数字进行转换。

字符串流类(sstream)用于string的转换:

  • <sstream> —— 相关头文件
  • istringstream —— 字符串输入流
  • ostringstream —— 字符串输出流

使用方法(string ——> 数字):

istringstream iss("123.45");
double num;
iss >> num;

使用方法(数字 ——> string):

ostringstream oss;
oss << 543.21;
string s = oss.str();

示例——字符串与数字的转换:

#include <iostream>
#include <sstream>
#include <string> using namespace std; #define TO_NUMBER(s, n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str()) int main()
{
double n = 0; if( TO_NUMBER("234.567", n) )
{
cout << n << endl;
} string s = TO_STRING(12345); cout << s << endl; return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
234.567
12345

面试题分析——字符串循环右移

示例:abcdefg循环右移3位后得到efgabcd

#include <iostream>
#include <string> using namespace std; string operator >> (const string& s, unsigned int n)
{
string ret = "";
unsigned int pos = 0; n = n % s.length();
pos = s.length() - n;
ret = s.substr(pos); // s.substr(4) ==> efg
ret += s.substr(0, pos); // s.substr(0, 4) ==> abcd return ret;
} int main()
{
string s = "abcdefg";
string r = (s >> 3); cout << r << endl; return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
efgabcd

3.数组操作符的重载

string类对象还具备C方式字符串的灵活性吗?还能直接访问单个字符吗?

字符串类的兼容性:

  • string类最大限度的考虑了C字符串的兼容性
  • 可以按照使用C字符串的方式使用string对象

示例:

#include <iostream>
#include <string> using namespace std; int main()
{
string s = "a1b2c3d4e";
int n = 0; for(int i = 0; i<s.length(); i++)
{
if( isdigit(s[i]) )
{
n++;
}
} cout << n << endl; return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
4

类的对象怎么支持数组的下标访问?

重载数组访问操作符:

  • 数组访问符是C/C++中的内置操作符
  • 数组访问符的原生意义是数组访问和指针运算

数组访问操作符([]):

  • 只能通过类的成员函数重载
  • 重载函数能且仅能使用一个参数
  • 可以定义不同参数的多个重载函数

示例:

#include <iostream>
#include <string> using namespace std; class Test
{
int a[5];
public:
int& operator [] (int i)
{
return a[i];
} int& operator [] (const string& s)
{
if( s == "1st" )
{
return a[0];
}
else if( s == "2nd" )
{
return a[1];
}
else if( s == "3rd" )
{
return a[2];
}
else if( s == "4th" )
{
return a[3];
}
else if( s == "5th" )
{
return a[4];
} return a[0];
} int length()
{
return 5;
}
}; int main()
{
Test t; for(int i=0; i<t.length(); i++)
{
t[i] = i;
} for(int i=0; i<t.length(); i++)
{
cout << t[i] << endl;
} cout << t["5th"] << endl;
cout << t["4th"] << endl;
cout << t["3rd"] << endl;
cout << t["2nd"] << endl;
cout << t["1st"] << endl; return 0;
}

运行结果为:

[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
0
1
2
3
4
4
3
2
1
0

4.小结

  • C++标准库是由类库和函数库组成的集合
  • C++标准库包含经典算法和数据结构的实现
  • C++标准库涵盖了C库的功能
  • C++标准库位于std命名空间中
  • 应用开发中大多数的情况都在进行字符串处理
  • C++中没有直接支持原生的字符串类型
  • 标准库中通过string类支持字符串的概念
  • string类支持字符串和数字的相互转换
  • string类的应用使得问题的求解变得简单
  • string类最大限度的兼容了C字符串的用法
  • 数组访问符的重载能够使得对象模拟数组的行为
  • 只能通过类的成员函数重载数组访问符
  • 重载函数能且仅能使用一个参数

C++解析(18):C++标准库与字符串类的更多相关文章

  1. C 和 C++ 的标准库分别有自己的 locale 操作方法,C 标准库的 locale 设定函数是 setlocale(),而 C++ 标准库有 locale 类和流对象的 imbue() 方法(gcc使用zh_CN.GBK,或者zh_CN.UTF-8,VC++使用Chinese_People's Republic of China.936或者65001.)

    转自:http://zyxhome.org/wp/cc-prog-lang/c-stdlib-setlocale-usage-note/ [在此向原文作者说声谢谢!若有读者看到文章转载时请写该转载地址 ...

  2. C语言的本质(22)——C标准库之字符串操作

    编译器.浏览器.Office套件等程序的主要功能都是符号处理,符号处理功能在程序中占相当大的比例,无论多复杂的符号处理都是由各种基本的字符串操作组成的,下面介绍如何用C语言的库函数做字符串初始化.取长 ...

  3. C标准库-数值字符串转换与内存分配函数

    原文链接:http://www.orlion.ga/977/ 一.数值字符串转换函数 #include <stdlib.h> int atoi(const char *nptr); dou ...

  4. C++ 标准库string字符串的截取

    标准库的string有一个substr函数用来截取子字符串.一般使用时传入两个参数,第一个是开始的坐标(第一个字符是0),第二个是截取的长度. #include <iostream> #i ...

  5. python基础教程_学习笔记18:标准库:一些最爱——shelve

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/signjing/article/details/36029981 标准库:一些最爱 shelve S ...

  6. 基于标准库的string类实现简单的字符串替换

    感觉基本功还是不扎实,虽然能做些程序但是现在看来我还是个初学者(primer),试着完成习题结果还得修修改改. 废话不多说,实现功能很简单,<C++ Primer>9.5.2节习题. // ...

  7. Python学习笔记18:标准库之多进程(multiprocessing包)

    我们能够使用subprocess包来创建子进程.但这个包有两个非常大的局限性: 1) 我们总是让subprocess执行外部的程序,而不是执行一个Python脚本内部编写的函数. 2) 进程间仅仅通过 ...

  8. C++标准库删除字符串中指定字符,比如空格

    参见:https://zh.cppreference.com/w/cpp/algorithm/remove 使用 erase 和 remove 配合. #include <algorithm&g ...

  9. Python - 标准库部分函数、类的大致实现(持续更新)

    all() def all(iterable): for element in iterbale: if not element: return False return True any() def ...

随机推荐

  1. Mac 必备工具之 brew

    brew 是 Mac 下的一个包管理工具,类似于 centos 下的 yum,可以很方便地进行安装/卸载/更新各种软件包,例如:nodejs, elasticsearch, kibana, mysql ...

  2. 列出连通集(mooc)

    给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集.假设顶点从0到N−1编号.进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点. 输入格式: 输入第1 ...

  3. 用Python爬下今日头条所有美女,美滋滋!

      我们的学习爬虫的动力是什么? 有人可能会说:如果我学好了,我可以找一个高薪的工作. 有人可能会说:我学习编程希望能够为社会做贡献(手动滑稽) 有人可能会说:为了妹子! ..... 其实我们会发现妹 ...

  4. nginx main函数

    源代码: int ngx_cdecl main(int argc, char *const *argv) { ngx_int_t i; ngx_log_t *log; ngx_cycle_t *cyc ...

  5. 洛谷【P1057】传球游戏

    https://www.luogu.org/problemnew/show/P1057 题目描述 在体育课上, 老师带着同学们一起做传球游戏. 游戏规则是这样的: n 个同学站成一个圆圈, 其中的一个 ...

  6. SPP-net论文总结

    SPPNet方法来自<Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition> ,是大神 ...

  7. K-means + PCA + T-SNE 实现高维数据的聚类与可视化

    使用matlab完成高维数据的聚类与可视化 [idx,Centers]=kmeans(qy,) [COEFF,SCORE,latent] = pca(qy); SCORE = SCORE(:,:); ...

  8. Qt绘图

    Qt绘图的设置 QPainter::Antialiasing // 反锯齿 QPainter::TextAntialiasing // 文字反锯齿 QPainter::SmoothPixmapTran ...

  9. 只执行一次的js 函数。

    function runOnce(fn, context) { //控制让函数只触发一次 return function () { try { fn.apply(context || this, ar ...

  10. Scrum立会报告+燃尽图 01

    此作业要求:[https://edu.cnblogs.com/campus/nenu/2018fall/homework/2190] 一.小组介绍 组长:王一可 组员:范靖旋,王硕,赵佳璐,范洪达,祁 ...