学习C++的基本使用,对于竞赛同学来说,是非常好的助力。
尤其是后面提到的STL部分,可以使用现成的数据结构帮助我们解决一些具体算法问题。
#include <iostream>//C++的输入输出头文件
using namespace std;//引入命名空间
int main(){
cout << "Hello World" << endl;//输出
std::cout<<"Hello World"<< std::endl;
return 0;
}
看看会输出什么?!猜测一下他们的作用吧。
引入头文件:#include
引入命名空间:using namespace std;
C++考虑到有可能出现重名的标识符、变量等,为了处理这样的情况,引入namespace的概念,将重名的内容分别放入不同的namespace中,在使用时具体指明它们的namespace即可!如:三个b变量
#include<iostream>
namespace a
{
int b=5;
}
namespace c
{
int b=8;
}
int main()
{
int b=9;
std::cout<<b<<" "<<a::b<<" "<<c::b<<std::endl;
return 0;
}
using namespace 命令:可以将某个命名空间中的所有标识在到当前作用域中直接使用
std:这是C++中的一个命名空间(存放许多标识,包括cin/cout)
那么使用using namespace std后,std空间中的标识符就可以被直接使用了,不必再写各种std::来具体指明。
cin/cout:在C++中用于输入和输出,位于std中
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
#include <iostream>
using namespace std;
int main( )
{
char name[50];
cout << "请输入您的名称: ";
cin >> name;
cout << "您的名称是: " << name << endl;
}
模仿以上代码可以尝试各种类型变量的输入,感受一下cin/cout与printf/scanf的优劣之处!
先掌握以上部分,就可以尝试用C++写一些基础题啦!!
想要了解更多,可以深入学习一下C++的STL部分。
定义时自动推断类型 ,简化复杂定义中的类型部分(如STL中的迭代器)
数字传为字符串
字符串转数字
#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\n", (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