看c++ primer,测试了几条语法,保存一下代码~
1.初始化string
注:字符串字面量不能直接相加
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main(){
string f5(5, 'f');
string g5(5, 'g');
//string test="hello"+"!"; 错误!字符串字面量不能直接相加
string str1 = f5 + g5;
string str2(g5 + f5);
if (str1 > str2)
cout << str1;
else
cout << str2;
system("pause");
return 0;
}
2.修改string中的值
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main(){
string str("abc abc");
for (decltype(str.size()) i = 0; i < str.size() &&
!isspace(str[i]); i++)
str[i] = toupper(str[i]);
//运用range for语句改变str中的值时,记得把定义的变量设置为引用,否则无用
for (auto &c : str){
c = tolower(c);
}
for (auto c : str){
cout << c << " ";
}
system("pause");
return 0;
}
3.初始化vector
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> vint;
typedef vector<char> vchar;
int main(){
vint v{ 1, 2, 3 }; //输出1 2 3
vint v1(10); //输出0 0 0...
vint v2{ 10 };//输出10
vint v3(10, -1);//输出-1 -1 -1...
vint v4{ 10, -1 };//输出10 -1
vchar vc{ 'a' ,'b','c'};//输出a b c
vint v5;
for (int i = 0; i < 5; i++)
v5.push_back(i);//输出0 1 2 3 4
vint v6(5);//v6已经压入5个0
for (int i = 0; i < 5; i++)
v6.push_back(5);//输出0 0 0 0 0 5 5 5 5 5
v5 = { 9, 9, 9 };//v5输出9 9 9
v6 = v5;//v6输出9 9 9
vint v7;
/*v7为空,此声明严重错误,程序会崩
for (int i = 0; i < 5; i++){
v7[i] = i;
}*/
for (int t; cin>>t;v7.push_back(t));//自行初始化,ctrl+Z结束
for (auto c : v7)
cout << c << endl;
//使用迭代器访问,迭代器和!=是良配
for (auto it = v7.begin(); it != v7.end(); ++it)
cout << *it << " ";
system("pause");
return 0;
}