C++中泛型编程风格——iterator学习,挺有难度,概念很抽象,这里主要把一些知识点和习题给过一遍!
一、前言
C++中泛型编程风格——iterator学习(Essential C++ 第三章)。
二、例题
-P222 练习 3.3
定义一个 map,以家庭姓氏为 key,value 则是家庭所有小孩的名字。令此 map 至少容纳六笔数据。允许用户根据姓氏来查询,并得以打印map内的每一笔数据。
typedef vector<string> vstring;
map<string, vstring> families;
void populate_map(ifstream& nameFile, map<string, vstring>& families)
{
string textline;
// 一行一行地读出来
while (getline(nameFile,textline))
{
string fam_name;
vector<string> child;
string::size_type pos = 0, prev_pos = 0, text_size = textline.size();
// 非常棒的循环
while ((pos = textline.find_first_of(' ', pos)) != string::npos)
{
// 获取每一个字符串的长度
string::size_type end_pos = pos - prev_pos;
// 这里面的 substr 太棒了
if (!prev_pos)
{
fam_name = textline.substr(prev_pos, end_pos);
}
else
{
child.push_back(textline.substr(prev_pos, end_pos));
}
prev_pos = ++pos;
}
// 剩下的字符串
if (prev_pos < text_size)
{
child.push_back(textline.substr(prev_pos, pos - prev_pos));
}
if (!families.count(fam_name))
{
families[fam_name] = child;
}
else
{
cerr << "Oops! We already habe a " << fam_name << "family in our map!\n";
}
}
}
void display_map(const map<string, vstring>& families, ostream& os)
{
map<string, vstring>::const_iterator it = families.begin(), end_it = families.end();
while (it != end_it)
{
os << "The " << it->first << " family";
if (it->second.empty())
{
os << "has no children.\n";
}
else
{
os << "has" << it->second.size() << " children: ";
vector<string>::const_iterator iter = it->second.begin(), end_iter = it->second.end();
while (iter != end_iter)
{
os << *iter << " ";
++iter;
}
os << endl;
}
++it;
}
}
void query_map(const string& family, const map<string, vstring>& families)
{
map<string, vstring>::const_iterator it = families.find(family);
if (it == families.end())
{
cout << "No family in our map.";
return;
}
cout << "The " << family;
if (!it->second.size())
{
cout << "has no children.\n";
}
else
{
cout << "has" << it->second.size() << " children: ";
vector<string>::const_iterator iter = it->second.begin(), end_iter = it->second.end();
while (iter != end_iter)
{
cout << *iter << " ";
++iter;
}
cout << endl;
}
}
int main()
{
map<string, vstring> families;
ifstream nameFile("C:\\Users\\13660\\Desktop\\families.txt");
if (!nameFile)
{
cerr << "No essential file exist.";
return -1;
}
populate_map(nameFile, families);
string family_name;
while (1)
{
cout << "Please enter a family name or 'q' to quit ";
cin >> family_name;
if (family_name == "q")
{
break;
}
query_map(family_name, families);
}
display_map(families, cout);
}
- 这道题太赞了,里面substr()函数的使用以及conster_iterator的使用都让我觉着非常的美丽,而且这种编码风格越看越舒服,非常值得多刷多记多体会!!!
代码是在 visual studio 中编写的,该软件还是比较好用的,我安装的是2022专业版;
共勉!