堆——动态内存分配
循环应用无法释放指针计数
用weak-ptr解决这种问题shared-ptr双向引用的问题
使用auto声明变量时,变量的类型将根据初始化表达式的类型进行推导
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<string, int>wCount;
//变量word记录输入的字符串
string word;
while (cin >> word) {
++wCount[word];
}
for (auto& w : wCount) {
cout << w.first << " " << w.second << endl;
//通过first访问key值,通过second访问value值
}
}
//创建一个map对象记录每一科目的成绩
#include <iostream>
#include<map>
#include<algorithm>
using namespace std;
struct DisPlay {
void operator()(pair<string, double > info) {
cout << "Subject:" <<info.first << " Score: " <<info.second << endl;
}
};
int main()
{
map<string, double> SubScore;
SubScore["php"] = 90.5;
SubScore["python"] = 95.0;
SubScore["java"] = 88.5;
SubScore.insert(map<string, double>::value_type("go", 89.5));
//for (it = SubScore.begin(); it != SubScore.end(); ++it)
//{
// cout << "Subject:" << it->first << " Score: " << it->second << endl;
//}
//
//
// 查找某个值的数据
//it = SubScore.find("python");
//if (it != SubScore.end()) {
// cout << it->second << endl;
//}
//else {
// cout << "not found" << endl;
//}
map<string,double>::iterator it = SubScore.begin();
for (; it != SubScore.end(); )
{
if (it->second < 90.0) {
it = SubScore.erase(it);
}
else {
++it;
}
}
for_each(SubScore.begin(), SubScore.end(), DisPlay());
}
用for-each(算法主要包含在头文件<algorithm>
)
可以遍历容器
for_each(vec.begin(), vec.end(), function)
string中find返回查找的索引
string中replace(索引位置,被替换的长度,“换成的内容”)
实例for_example
#include <iostream>
#include<string>
using namespace std;
void replaceString(string& str, const string& oldStr, const string& newStr)
{
int p = 0;
while ((p=str.find(oldStr,p)) !=string::npos )
{
str.replace(p, oldStr.size(), newStr);
p += newStr.size();
}
}
int main() {
string s = "thu tho thu";
//int p = s.find("thu", 0);
//cout << p << endl;
//s.replace(4, 3, "through");
replaceString(s, "thu", "through");
replaceString(s, "tho", "though");
cout << s << endl;
return 0;
}
示例:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fout;
fout.open("buffer.txt");
fout << "hello world" << endl;
fout << "开始计数:" << endl;
for (int index = 0; index < 10; ++index) {
fout << index << endl;
}
char ch = 'a';
fout << ch << endl;
fout.close();
}
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
// 函数声明
void readLinesToVector(const std::string& filename);
// 函数定义
void readLinesToVector(const string& filename) {
ifstream file(filename); // 打开文件
vector<string> lines; // 创建一个字符串向量来存储每一行
if (!file.is_open()) {
cout << "无法打开文件: " << filename << endl;
return;
}
string line;
// 逐行读取文件内容
while (getline(file, line)) {
lines.push_back(line); // 将读取的行添加到向量中
}
file.close(); // 关闭文件
// 遍历向量并输出每一行
for (const auto& line : lines) {
cout << line << endl;
}
}
int main() {
string filename = "books.txt"; // 假设文本文件名为 example.txt
readLinesToVector(filename);
return 0;
}
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
// 函数声明
void readLinesToVector(const string& filename);
// 函数定义
void readLinesToVector(const string& filename) {
ifstream file(filename); // 打开文件
vector<string> lines; // 创建一个字符串向量来存储每一行
if (!file.is_open()) {
cout << "无法打开文件: " << filename << endl;
return;
}
string line;
// 逐行读取文件内容
while (getline(file, line)) {
lines.push_back(line); // 将读取的行添加到向量中
}
file.close(); // 关闭文件
// 遍历向量并输出每一行
for (const auto& line : lines) {
cout << line << endl;
}
}
int main() {
string filename = "books.txt"; // 假设文本文件名为
readLinesToVector(filename);
return 0;
}
现代C++中的范围基于的for循环(range-based for loop)是C++11引入的一项特性,旨在简化对容器或范围的迭代过程。这种循环语法不仅使代码更清晰易读,还减少了迭代时的错误。以下是范围基于的for循环的详细介绍:
1.基本用法
范围基于的for循环可以遍历任何提供迭代器的容器。
#include <vector>
#include <iostream>
void basicExample() {
std::vector<int> vec = {1, 2, 3, 4, 5};
for (int num : vec) {
std::cout << num << " ";
}
// 输出: 1 2 3 4 5
}
2.使用引用遍历
#include <vector>
#include <iostream>
void referenceExample() {
std::vector<int> vec = {1, 2, 3, 4, 5};
for (int& num : vec) {
num *= 2; // 修改元素
}
for (const int& num : vec) {
std::cout << num << " "; // 读取元素
}
// 输出: 2 4 6 8 10
}
#include <map>
#include <iostream>
void mapExample() {
std::map<std::string, int> wordCount = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};
for (const auto& pair : wordCount) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 输出:
// apple: 1
// banana: 2
// cherry: 3
}
4.结合自动类型推导(auto
)
#include <vector>
#include <iostream>
void autoExample() {
std::vector<double> vec = {1.1, 2.2, 3.3, 4.4, 5.5};
for (auto num : vec) {
std::cout << num << " ";
}
// 输出: 1.1 2.2 3.3 4.4 5.5
}
1.正则表达式功能很强大
2.正则表达式,搜索、修改字符序列的高效手段
3.规则是通用的,和程序语言没有关系
4.不太容易读懂一个正则表达式。(Ip地址192.168.1.201)
5.写一个正则表达式匹配结果数据不困难,但容易出问题
6.如何精准定位??
\\w 匹配数字、字母、下划线
\\d 匹配数字
\\s 匹配空格
[]匹配括号中的任意字符:
regex reg("[a-zA-Z0-9]");
(\\W,D,S)则表示不匹配....
*匹配0个或多个
+匹配1个或多个
.任意字符除了换行符
^字符串需要匹配开始的地方 [ ^ x]表示不能匹配x字符
$字符串匹配结束的位置
? 匹配0个或一个
可以设置匹配的字符个数{n,m} n~m个
regex reg("\\d{3,6}");
regex_match() 从头到尾都需要匹配
regex_search() 从目标字符中去查找匹配成功的字符
正则表达式分组
#include<iostream>
#include<regex>
#include<vector>
using namespace std;
int main()
{
vector<string>vt = { "12356","19572290951","18816645621","19572290957","19577720134"};
regex reg("^1\\d{9}[^47]$");
smatch results;
for (int i = 0; i < vt.size(); i++) {
bool x;
x= regex_search(vt[i], results, reg);
if(x)
{cout << results.str() << endl;}
}
}
#include<iostream>
#include<regex>
#include<vector>
using namespace std;
int main()
{
string str = "python 90.55 scores php 80.0 java 95";
regex reg("\\d+[.\\d+]?\\d+");
//迭代器遍历
sregex_iterator it(str.begin(), str.end(), reg);
auto end_it = sregex_iterator();
smatch result;
while (it != end_it)
{
result = *it;
cout << result.str() << endl;
it++;
}
}
#include<iostream>
#include<regex>
#include<vector>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string filename = "email.txt";
ifstream file(filename); // 打开文件
vector<string> lines; // 创建一个字符串向量来存储每一行
if (!file.is_open()) {
cout << "无法打开文件: " << filename << endl;
return -1;
}
string line;
string str = "";
// 逐行读取文件内容
while (getline(file, line)) {
str+= line; // 将读取的每行拼接到一个字符串里
}
file.close(); // 关闭文件
regex reg("[\\w. ]*@\\w+\\.\\w+");
sregex_iterator it(str.begin(), str.end(), reg);
auto end_it = sregex_iterator();
smatch result;
while (it != end_it)
{
result = *it;
cout << result.str() << endl;
it++;
}
return 0;
}
#include<iostream>
#include<regex>
#include<string>
using namespace std;
int main()
{
string str;
while (true)
{
getline(cin, str);
if (str == "q") {
break;
}
regex reg("([a-zA-Z]*ie[a-zA-Z]*)|([a-zA-Z]*cei[a-zA-Z]*)");
bool a;
a =regex_search(str, reg);
if (a) {
cout << "yes!" << endl;
}
else
cout << "No!" << endl;
}
}
curl发起http请求,获得服务端的响应
前端知识预热
vector<string> getImageUrl(const string& html)
{
//如何获取??正则表达式获取所有的image的链接
regex reg("./img\\w.(jpg|png)");
auto end_it = sregex_iterator();
vector<string> it;
sregex_iterator it(html.begin(), html.end(), reg);
//如何删除重复的IMAGEURL
for (; it != end_it; ++it)
{
if (!(find(vt.begin(), vt.end(), it->str()) != vt.end()))
{
cout<<it->str()<<endl;
vt.push_back(it->str());
}
}
}
(又称网域,是由一串用点分隔的名字组成的互联网上某一台计算机或计算机组的名称,用于在数据传输时对计算机的定位标识)
由于IP地址不方便记忆并且不能显示地址组织的名称和性质,人们设计出了域名,并通过域名系统(DNS,Domain Name System)来将域名和IP地址相互映射,使人更方便地访问互联网,而不用去记住能够被机器直接读取的IP地址数串。
统一资源定位系统(uniform resource locator;URL)是因特网的万维网服务程序上用于指定信息位置的表示方法。它最初是由蒂姆·伯纳斯·李发明用来作为万维网的地址。
爬虫爬取一个网页,并且获取其中URL
提取相关信息,存放在map,最后制成txt文件导出
#include<curl/curl.h>
#include<iostream>
#include<regex>
#include<filesystem>
#include <string>
#include<map>
#include<vector>
#include<sstream>
#include<filesystem>
#include<fstream>
using namespace std;
const string URL = "https://ssr1.scrape.center/"; //爬取站点
const int Page = 10; //爬取的电影数目
vector <string> URL_VT = vector<string>(); //存储所有电影URL的容器
//以此类推还可以存储名字信息之类的数据,分类包装
const static string PATH = "./movies";
size_t writeCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
size_t totalSize = size * nmemb;
output->append(static_cast<char*>(contents), totalSize);
return totalSize;
}
string request_get(const string& url, map< string, string > headers = map<string, string>()) {
CURL* curl;
CURLcode res;
string htmlData;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "https://ssr1.scrape.center");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &htmlData);
res = curl_easy_perform(curl);
///* if (res != CURLE_OK) {
// cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
// }
// else {
// cout << htmlData << endl;
// }*/
curl_easy_cleanup(curl);
}
else {
cerr << "curl_easy_init() failed." << endl;
return 0;
}
// 清理libcurl
curl_easy_cleanup(curl);
return htmlData;
}
bool contains(vector<string>& vt, const string& value)
{
return find(vt.begin(), vt.end(), value) != vt.end();
}//获取所有电影的URL,并存储在动态数组URL_VT中
void getURL()
{
string htmlData = "https://ssr1.scrape.center/detail/2";
string url;
string html;
regex reg("/detail/\\d+");
smatch result;
for (int page = 1; page <= Page; page++)
{
url= URL + "/page/" + to_string(page);
html = request_get(url);
auto end_it = sregex_iterator();
sregex_iterator it(htmlData.begin(), htmlData.end(), reg);
cout << url<<endl;
for (; it != end_it; it++)
{
result = *it;
if (!contains(URL_VT, result.str()))
{
URL_VT.push_back(result.str());
}
/* cout << result.str() << endl;*/
}
}
}
//在html页面中查找同类元素
vector<string>findAll(const string html, regex reg,int group =0)
{
auto end_it = sregex_iterator();
vector<string>vt;
smatch result;
sregex_iterator it(html.begin(), html.end(), reg);
for (; it != end_it; it++)
{
result = *it;
cout << result[group].str() << endl;
vt.push_back(result[group].str());
}
return vt;
}
//(工具函数)将vector中的字符串连接到一起
string vectostring(vector<string>& vt)
{
ostringstream ostr;
for (auto& w : vt)
{
ostr << w<<" ";
}
return ostr.str();
}
//解析电影详细信息的函数,返回一个保存电影信息的map数组
map<string,string> parseDatailPage(const string& url)
{
string html = request_get(url);
smatch resultTitle, resultCatogories, ResultArea, resulttime, resultpubulish,resultdrama,resultscore;
map<string, string> resultmap;
regex regtitle(">(.*)</h2>");
regex_search(html, resultTitle, regtitle);
cout << resultTitle.str() << endl;
regex regcategories("<span>(.*)</span>");
vector<string> vt=findAll(html, regcategories,1);
vt.pop_back();
regex RegArea("\">([^x00-xff^/]+)</span>");
regex_search(html, ResultArea, RegArea);
cout << ResultArea[1].str() << endl;
regex regtime(">(\\d+).*</span>");
regex_search(html, resulttime, regtime);
cout << resulttime[1].str() << endl;
regex regpubish("\\d+-\\d+-\\d+");
regex_search(html,resultpubulish, regpubish);
cout << resultpubulish.str() << endl;
regex regdrama(">\\s+(.*)\\s+</p>");
regex_search(html, resultdrama, regdrama);
cout << resultdrama[1].str() << endl;
regex regscore("\\d+\\.\\d+");
regex_search(html, resultscore, regscore);
cout << resultscore.str() << endl;
resultmap["title"] = resultTitle[1].str();
resultmap["categories"] = vectostring(vt);
resultmap["area"] = ResultArea[1].str();
resultmap["time"] = resulttime[1].str();
resultmap["publish"] = resultpubulish[1].str();
resultmap["score"] = resultscore.str();
return resultmap;
}
//UTF转换为
string ConvertUTF8toGBK(const string& str) {
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
std::wstring wstr(len, L'\0');
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &wstr[0], len);
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL
);
std::string ret(len, '\0');
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &ret[0], len, NULL, NULL)
;
return ret;
}
int main()
{
SetConsoleOutputCP(65001);
if (!filesystem::exists(PATH))
{
filesystem::create_directory(PATH);
}
getURL();
string url;
string fileName;
map<string, string>resultmap;
while (!URL_VT.empty())
{
url = URL_VT.back();
URL_VT.pop_back();
resultmap = parseDatailPage(url);
fileName = ConvertUTF8toGBK(PATH + "/" + resultmap["title"] + ".txt");
fstream fout(fileName,ios::out);
for (auto& m : resultmap)
{
fout<< m.first <<" " << m.second << endl;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。