1、容器的for循环
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
vector<int> v(5,6);
for (auto x : v)cout << x << " ";
cout << endl;
string s = "asdsdf";
for (auto c : s)cout << c;
}
2、C++的格式控制
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int a=100;
cout << setw(10) << setfill('0') << a << endl;
//setw(int n);n个宽度,右对齐 setfill(char c)用字符c补齐
//头文件#include<iomanip>
}
3、int和string型相互转换
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main() {
stringstream ss;
string s = "200";
int a = 100;
//C语言的sscanf可以实现string向int的转换,s.c_str()将string转换为字符指针
sscanf(s.c_str(), "%d", &a);
cout << a << endl;
//to_string可以实现int向string的转换
s = to_string(a);
cout << s << endl;
//可以利用ss进行转换
//int向string
ss << a;
ss >> s;//ss.str();也可以创建一个临时的string
cout << a << " " << s << endl;
//string向int
ss << s;//等价于ss.str(s);
ss >> a;
cout << a << " " << s << endl;
}
4、set和map的lower_bound和upper_bound的运用
#include<iostream>
#include<algorithm>
#include<set>
using namespace std;
int main() {
set<int> st;
set<int>::iterator it;
st.insert(1);
st.insert(2);
st.insert(4);
st.insert(5);
//lower_bound()upper_bound()用于set和map,返回一个迭代器
//lower_bound(x)返回第一个>=x的迭代器
//upper_bound(x)返回第一个>x的迭代器
it = st.lower_bound(2);
cout << *it << endl;
it = st.lower_bound(3);
cout << *it << endl;
it = st.upper_bound(2);
cout << *it << endl;
it = st.upper_bound(3);
cout << *it << endl;
}
5、multimap和multiset的运用
#include <iostream>
#include<string>
#include <set>
#include <map>
using namespace std;
int main()
{
//不会自动去重,可以有多个key值,依旧按key值自动排序,multiset同理
multimap<string, int> mp;
string s("中国"), s1("美国");
mp.insert(make_pair(s, 50));
mp.insert(make_pair(s1, 20));
mp.insert(make_pair(s1, 30));
mp.insert(make_pair(s, 55));
mp.insert(make_pair(s, 60));
mp.insert(make_pair(s1, 10));
//输出方式
//方式1
multimap<string, int>::iterator beg, end, it;
beg = mp.lower_bound(s1);
end = mp.upper_bound(s1);
for (it = beg; it != end; it++)
cout << it->first << " " << it->second << endl;
system("cls");
//方式二
int k;
it = mp.find(s);
for (k = 0; k != mp.count(s); k++, it++)
cout << it->first << "--" << it->second << endl;
return 0;
}
6、unordered_map和unorder_set
#include<iostream>
#include<unordered_map>
#include<unordered_set>
using namespace std;
int main() {
//不排序的map,插入效率比较高,用哈希表实现
unordered_map<int, int> mp;
//不排序的set,插入效率比较高,依旧可以自动去重
unordered_set<int> st;
}
7、nth_element(first,nth,last)
将第n_thn_th 元素放到它该放的位置上,左边元素都小于它,右边元素都大于它.
期望复杂度O(n)O(n),一个很号好的用途就是找中位数了……
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[100];
for (int i = 0; i<100; ++i) {
a[i] = i;
}
srand(time(0));
random_shuffle(a, a + 100);
for (int i = 0; i<100; ++i) std::cout << a[i] << ' '; std::cout << '\n';
nth_element(a, a + 10, a + 100);
for (int i = 0; i<100; ++i) std::cout << a[i] << ' '; std::cout << '\n';
return 0;
}