useful website: https://cplusplus.com
trade-off between flexibility and performance
实际的性能差异并不大,而且vector有更好的灵活性
- 作用:避免命名冲突(naming conflict),
::
称作scope operator - 注意⚠️:不要在头文件中使用using,有潜在的命名冲突风险
1
2
3
4
5
6
7
8
9
10
11
12
| #include<string>
using std::string;
int main(){
// 定义
string str1 = "hello world"; // copy construction
string str("dskjfjkds"); // direct construction
string str3(10,'c');//repeat 10 times 'c', direct construction
//
}
|
- size(),返回值是size_type(size_t),unsigned_int
- tip;cin读取终端输入到空格就停止,如何读取含有空格的字符串?使用库函数
getline()
1
2
3
4
5
6
7
8
9
| #include<string>
using std::string;
int main(){
// 定义
string input;
getline(std::cin, input);//从终端读取,赋值到input,读到回车停止
return 0;
}
|
vector<TYPE> NAME;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| #include<iostream>
#include<string>
#include<vector>
using std::string;
using std::vector;
int main(){
vector<int> vec = {1,2,3};
vector<string> vec_str = {"dsf","dsf","hthjt"};
//for loop
for(string s : vec_str){
std::cout << s << std::endl;
}
//push_back & emplace_back
for(int i = 0; i < 100; i ++){
vec.push_back(i);
vec.emplace_back(i);
}
}
|
出现原因:vector等对象可以用下标进行索引,但是诸如map、set等对象不能用下标进行索引,map和set到内存空间可能并不连续。而迭代器提供了这样一种抽象(abstract)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| #include<iostream>
#include<string>
#include<vector>
using std::string;
using std::vector;
int main(){
vector<int> vec = {1,2,3};
vector<string> vec_str = {"hello","world"}
// for(vector<int>::iterator it = vec.begin(); it != vec.end(); it ++)
for(auto it = vec.begin(); it != vec.end(); it ++){
std::cout << *it << std::endl; //解引用
}
for(auto it = vec_str.begin(); it != vec_str.end(); it ++){
std::cout << (*it).size() << std::endl; //解引用
std::cout << it->size() << std::endl; //解引用
}
}
|
注意点: