map——词频统计
map并不能使用流迭代器,流迭代器仅支持*
和++
--
,并不能选择成员,从而也就不能支持建立在pair上的map容器
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<string, int> dict; string tmp;
while(cin.peek() != EOF){
cin >> tmp;
if (!isalpha(tmp[tmp.size()-1]))
tmp[tmp.size()-1] = 0;
dict[tmp]++;
}
for (auto it : dict) cout << it.first << '\t' << it.second << endl;
}
vector——平均分排序
输入忘了只能push_back
,然后输入失败;
每操作一个新元素都忘了push_back
,然后越界。
不复习的后果就是成为废人。
另外,debug的核心是寻找哪里的输入-输出映射和我们预想的不同。很基本的思想都忘掉了。
可以嵌套调用,不能嵌套定义函数。比如这个cmp()
#include <bits/stdc++.h>
using namespace std;
class Student
{
public:
string id;
double average;
vector<double> score;
};
vector<Student> a;
vector<double> weight{2.0, 3.0, 4.0};
void inp()
{
int cnt = 0;
while (cin.peek() != EOF)
{
a.push_back({});a[cnt].score.reserve(3);
cin >> a[cnt].id;
double d;
cin >> d; a[cnt].score.push_back(d);
cin >> d; a[cnt].score.push_back(d);
cin >> d; a[cnt].score.push_back(d);
#ifdef _LOC_
for (auto it : weight) cout << it << ' '; cout << endl;
for (auto it: a[cnt].score)
cout << it << endl;
#endif
a[cnt].average = inner_product(a[cnt].score.begin(), a[cnt].score.end(),
weight.begin(), 0.0) /
accumulate(weight.begin(), weight.end(), 0.0);
#ifdef _LOC_
std::clog << a[cnt].average << endl;
#endif
cnt++;
}
}
bool cmp(Student a, Student b)
{
return a.average > b.average;
}
void oup()
{
for (int i = 0; i < a.size(); i++)
cout << a[i].id << '\t'
<< a[i].average << '\t'
<< a[i].score[0] << '\t'
<< a[i].score[1] << '\t'
<< a[i].score[2] << endl;
}
int main()
{
inp();
sort(a.begin(), a.end(), cmp);
oup();
}
做oj,在快糙猛编程后,再考虑封装问题;
#include <bits/stdc++.h>
using namespace std;
class Student
{
public:
static vector<double> credit;
static void Input();
static bool cmp(Student a, Student b) { return a.Average() > b.Average(); }
static vector<Student> students;
Student(string _id, vector<double> _score): id(_id), score(_score) { Average();}
void Print();
private:
string id;
vector<double> score;
double average;
double Average(){ return average = inner_product(score.begin(), score.end(),credit.begin(), 0)
/ accumulate(credit.begin(), credit.end(), 0); };
};
vector<double>Student::credit = {2,3,4};
void Student::Input()
{
string tmp;
vector<double> score(3);
while (cin >> tmp)
{
for (int i = 0 ;i < 3; i++) cin >> score[i];
students.push_back(Student{tmp, score});
}
sort(students.begin(), students.end(), cmp);
}
void Student::Print()
{ cout << id << '\t' << average << '\t' << score[0] << '\t' << score[1] << '\t' << score[2] << endl;}
bool Student::cmp(Student a, Student b) { return a.Average() > b.Average(); }
int main()
{
Student::Input();
for (auto it: Student::students)
it.Print();
}