算法:C++入门

目录

所在位置

一、C++简单使用

学C++,对竞赛帮助真的很大。

尤其是后面的STL部分,有现成的数据结构与实用的算法可以直接使用。

1.基本语法

1. Hello World!第一个C++程序

#include <iostream>//C++的输入输出头文件
using namespace std;//引入命名空间

int main(){
    cout << "Hello World" << endl;//输出等价于下一行
	//std::cout<<"Hello World"<< std::endl;
    return 0;
}

了解以下内容

  • 引入头文件:#include

    • C++中最基本的头文件(输入输出流的头文件)
    • C++和C一样:有许多头文件,我们在需要使用时引入。
    • C++中还有个"万能头",#include<bits/stdc++.h>,它包含了目前C++所有的头文件,可以以一抵多。
    • 与C语言的不同
      • C++的头文件都省略了.h(C++标准中规定头文件不使用后缀.h,当然它仍然兼容C的头文件)
  • 引入命名空间std:using namespace std;

    • 使用using namespace std后,std空间中的标识符可以直接使用了,不必再写各种std::来具体指明。
    • 详情:
  • cin/cout:在C++中用于输入和输出,位于std中

2.C++基本输入输出

标准输出流cout

#include <iostream>
using namespace std;
int main( )
{
   char str[] = "Hello C++";
 
   cout << "Value of str is : " << str << endl;
}

标准输入流cin

#include <iostream>
using namespace std;
int main( )
{
   char name[50];
 
   cout << "请输入您的名称: ";
   cin >> name;
   cout << "您的名称是: " << name << endl;
 
}

模仿以上代码可以尝试各种类型变量的输入,感受一下cin/cout与printf/scanf的优劣之处!

先掌握以上部分,就可以尝试用C++写一些基础题啦!!

想要了解更多,可以深入学习一下C++的STL部分。

二、C11特性

1.auto声明

定义时自动推断类型 ,简化复杂定义中的类型部分(如STL中的迭代器)

2.to_string

数字传为字符串

3.stoi、stod...

字符串转数字

4.代码示例:

#include<iostream>
#include <set>
#include <string>
using namespace std;
int main(void){
	//一、auto声明:自动推断类型 
	auto x = 100;
	auto y = 1.5;
	set<int> s;
	s.insert(4);
	s.insert(2);
	s.insert(5);
	for(set<int>::iterator it = s.begin(); it != s.end(); it++) {
	    cout << *it << " ";
	}
	cout << endl;
    
    //以上等同于
	for(auto it = s.begin(); it != s.end(); it++){
		cout << *it << " ";
	}
	cout << endl;
		
	//二、 to_string
	string s1 = to_string(123);
	cout << s1 << endl;
	string s2 = to_string(4.5);
	cout << s2 << endl;
	cout << s1 + s2 << endl;
	printf("%s
", (s1 + s2).c_str());//如果想用printf输出string得加一个.c_str()
	
	
	//三、stoi、stod:string转化为对应的int和double型
	string str = "123";
	int a = stoi(str);
	cout << a << endl;
	
	str = "123.44";
	double b = stod(str);
	cout << b << endl;
	//stof
	//sstold
	//stol
	//stoll
	//stoul
	//stoull
	return 0; 

}
	
原文地址:https://www.cnblogs.com/Hokkaido-JL/p/13839120.html