gpt4 book ai didi

c++ - 在 C++ 98 中优化 vector 过滤

转载 作者:行者123 更新时间:2023-11-28 04:40:27 25 4
gpt4 key购买 nike

我被赋予了以下任务:创建一个包含男性、女性和未知姓名的文本文件。尝试实现一个过滤器,将这些姓名与真实姓名进行比较(因此总共输入 3 个文件:男性、女性,比方说租房者)。过滤时将匹配的名称放入适当的容器中。在我看来,这非常简单,所以我按照下面提供的方式进行了操作。

我的问题是:有没有办法优化这段代码?

我尝试使用抽象类并基于抽象实体创建 4 个不同的对象(男人、女人、已知、未知)。但是对于这样一个简单的任务来说,代码量仍然很大。另一个想法是使用 lambda 表达式,但我仅限于 C++ 98。

我想我想多了......

#include <fstream>
#include <iostream>
#include <vector>
#include <string>

int main()
{
std::ifstream men("resources/men_names.txt");
std::ifstream women("resources/women_names.txt");
std::ifstream renters("resources/renter_names.txt");

std::vector<std::string> menNames;
std::vector<std::string> womenNames;
std::vector<std::string> renterNames;
std::vector<std::string> knownRenters;
std::vector<std::string> unknownRenters;

std::string name;

while (men >> name)
menNames.push_back(name);

men.close();

while (women >> name)
womenNames.push_back(name);

women.close();

while (renters >> name)
renterNames.push_back(name);

renters.close();

std::vector<std::string>::iterator itMen;
std::vector<std::string>::iterator itWomen;
std::vector<std::string>::iterator itRenters;

for (itRenters = renterNames.begin(); itRenters != renterNames.end(); itRenters++)
{
bool found = false;

for (itMen = menNames.begin(); itMen != menNames.end(); itMen++)
{
if ((*itMen) == (*itRenters))
{
found = true;
knownRenters.push_back((*itMen));
}
}
if (!found)
{
for (itWomen = womenNames.begin(); itWomen != womenNames.end(); itWomen++)
{
if ((*itWomen) == (*itRenters))
{
found = true;
knownRenters.push_back((*itWomen));
}
}
}
if (!found)
unknownRenters.push_back((*itRenters));
}

std::cout << knownRenters.size() << '\n';
std::cout << unknownRenters.size() << '\n';

std::cin.get();

return 0;
}

最佳答案

缩短您现有的代码。这应该都是C++98

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <iterator>

int main()
{
std::ifstream men("resources/men_names.txt");
std::ifstream women("resources/women_names.txt");
std::set<std::string> peopleNames;

peopleNames.insert(std::istream_iterator<std::string>(men), std::istream_iterator<std::string>());
peopleNames.insert(std::istream_iterator<std::string>(women), std::istream_iterator<std::string>());

std::ifstream renters("resources/renter_names.txt");
std::vector<std::string> knownRenters;
std::vector<std::string> unknownRenters;

for (std::string name; renters >> name; )
{
if (peopleNames.count(name))
knownRenters.push_back(name);
else
unknownRenters.push_back(name);
}

std::cout << knownRenters.size() << '\n';
std::cout << unknownRenters.size() << '\n';

std::cin.get();

return 0;
}

关于c++ - 在 C++ 98 中优化 vector 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com