提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
c++基础知识的合集:`
前面讲了c++语言中的变量和常量,今天将会对c++语言中的常规语法和STL数据库进行详细介绍:
提示:以下是本篇文章正文内容,下面案例可供参考
一、c++程序基础知识
1.运算符
(1).常规运算符及其用法
代码演示:
#include<iostream>
using namespace std;
int main(void)
{
//赋值运算符:
const int a = 3;//利用关键字const表示a是常量,并将3赋值给a;
//算数运算符:
int m1 = 4, m2 = 2, m3;
m3 = m1 / m2;
cout << m3;//将会得到2
m3 = m1 % m2;
cout << m3 << endl;//将会得到0
//关系运算符;
bool elemstyle;
if (m1 > 2)
{
elemstyle = true;
}
else
{
elemstyle = false;
}
cout << elemstyle;//输出true;
//三目运算符,?:;
double x1=30, x2=20;
double x3;
x3 = x1 > x2 ? x1 : x2;
cout << x3 << endl;//输出30;
}
2.STL之string
STL是Standard Template Library的缩写,即标准模板库,主要包含容器,算法,迭代器等方面的内容,STL常用的容器包括string(字符串),vector(向量),stack(栈),queue(队列),list(表),set(集合),map(映射).
示例代码:
#include<iostream>
#include<string>
using namespace std;
int main(void)
{
string s = "Hello word!";
int size,length;
size = s.size();
length = s.length();//都为 s的长度
cout << size << " " << length << endl;
int k = s.find(' ');//查找空格;
cout << "空格所在位置:" << k << endl;
if (k != -1)
{
cout << s.substr(0, k) << endl;;//从零开始取长度为k的字符串;
}
}
3.c++中的一些常用库函数
二、程序控制结构
1.选择结构
if()else语句
switch()语句
2.循环结构
1.do…while()循环语句
2.while()循环语句
while循环语句和do…while()语句的差别在于,while的执行情况最少为一,do…while语句最少的执行情况为1.根据这个特点,可以在不同的情况下使用.
3.for()循环语句
3.跳转语句
void函数后不能返回函数值,即不能用return 返回函数值;
4.字符串和字符串流
在学习字符数组前先学习数组;
1.数组
2.数组应用——约瑟夫环
代码如下(示例):
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
const int N = 100;//全局变量;
int main(void)
{
int n;
bool a[N];
int count = 0, m;
cin >> n;
m = n;
for (int i = 0; i < n; i++)
{
a[i] = true;//作为一个标识符;
}
int i = -1;
while (m > 1)
{
i = (i + 1) % n;//往下走,如果走到尽头,则从起始位置开始走;
if (a[i] == false)//如果出列了就跳过;
{
continue;
}
count++;//报数加一;
if (count == 3)
{
a[i] = false;
m--;//人数减一;
count = 0;//从头开始报;
}
}
for (int j = 0; j < n; j++)
{
if (a[j] == true)
{
cout << "最后的人是:" <<j + 1<<"号" << endl;
break;
}
}
return 0;
}
2.字符串数组和字符串流
#include<iostream>
#include<string>
#include<sstream>//串流头文件;
using namespace std;
int main(void)
{
string s;
string t;
string sum;
getline(cin, s);
stringstream ss;//字符串流;
ss << s;//将空格隔开的字符进行串流,可以除去空格;
while (ss >> t)
{
sum += t;
}
cout << sum;
}
stringstream也可以用来将整数转换为字符串;
如果要输入大量的字符串,尽量不要用string,容易超时,可以作为数据缓冲区;
例如:
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
#include<sstream>//串流头文件;
using namespace std;
int main(void)
{
string s;
char ch[100];
scanf("%s",ch);
s = ch;
int count = 0;
for(int i=0;i<s.size();i++)
{
count++;
}
cout << count << endl;
}
总结
本文简单介绍了c++语言中的一些基本语句,后面会继续更新一些标准库函数;