所以我有一个网络刮板,可以从新闻网站上刮掉大量文章。目前,我正在编写一个函数,以按月过滤掉文章。 (代码如下所示)我已经在地图上存储了帖子的月份和数量。但是,当我打印出地图时,键和值不是顺序吗?
CODE
#include "Source.cpp"
#include <map>
int main() {
std::map<std::string, int> numberOfPost;
int janCounter = 0;
int febCounter = 0;
int marCounter = 0;
int aprCounter = 0;
int mayCounter = 0;
int juneCounter = 0;
int julyCounter = 0;
int augCounter = 0;
int septCounter = 0;
int octCounter = 0;
int novCounter = 0;
int decCounter = 0;
//Calling STScraper and load into Vector
std::vector<STPost>stposts = STScraper();
for (auto i = stposts.begin(); i != stposts.end(); ++i) {
std::tm dt = (*i).getTime();
//std::wcout << dt.tm_mon << std::endl;
if (dt.tm_mon == 0)
{
janCounter++;
}
else if (dt.tm_mon == 1)
{
febCounter++;
}
else if (dt.tm_mon == 2)
{
marCounter++;
}
else if (dt.tm_mon == 3)
{
aprCounter++;
}
else if (dt.tm_mon == 4)
{
mayCounter++;
}
else if (dt.tm_mon == 5)
{
juneCounter++;
}
else if (dt.tm_mon == 6)
{
julyCounter++;
}
else if (dt.tm_mon == 7)
{
augCounter++;
}
else if (dt.tm_mon == 8)
{
septCounter++;
}
else if (dt.tm_mon == 9)
{
octCounter++;
}
else if (dt.tm_mon == 10)
{
novCounter++;
}
else if (dt.tm_mon == 11)
{
decCounter++;
}
}
numberOfPost.insert(std::pair<std::string, int>("January", janCounter));
numberOfPost.insert(std::pair<std::string, int>("Feburary", febCounter));
numberOfPost.insert(std::pair<std::string, int>("March", marCounter));
numberOfPost.insert(std::pair<std::string, int>("April", aprCounter));
numberOfPost.insert(std::pair<std::string, int>("May", mayCounter));
numberOfPost.insert(std::pair<std::string, int>("June", juneCounter));
numberOfPost.insert(std::pair<std::string, int>("July", julyCounter));
numberOfPost.insert(std::pair<std::string, int>("August", augCounter));
numberOfPost.insert(std::pair<std::string, int>("September", septCounter));
numberOfPost.insert(std::pair<std::string, int>("October", octCounter));
numberOfPost.insert(std::pair<std::string, int>("November", novCounter));
numberOfPost.insert(std::pair<std::string, int>("December", decCounter));
std::map<std::string, int>::iterator itr;
std::cout << "\tKEY\tELEMENT\n";
for (auto& p : numberOfPost) {
std::cout << '\t' << p.first
<< '\t' << p.second << '\n';
}
std::cout << std::endl;
return 0;
}
您可以从我的代码中看到,我创建了一个循环,以按月数计算帖子数,并将其存储在地图中。但是,当我打印出地图时,输出未显示从1月到12月的顺序。那么,如何编辑代码,以便在打印地图时显示从1月到12月的地图?
输出
对地图使用自定义排序,您可以执行以下操作:
struct customSort {
bool operator()( const std::string &a, const std::string &b ) const {
static const std::unordered_map<std::string, int> months = {
{ "January", 1 },
{ "Feburary", 2 },
{ "March", 3 },
{ "April", 4 },
{ "May", 5 },
{ "June", 6 },
{ "July", 7 },
{ "August", 8 },
{ "September", 9 },
{ "October", 10 },
{ "November", 11 },
{ "December", 12 },
};
return months.at( a ) < months.at( b );
}
};
std::map<std::string, int, customSort> numberOfPost;
这将按月份对您的地图进行排序。如果您尝试输入不是有效月份的内容,也会引发异常。