我正在尝试实施我所学到的知识std::vector
来解决问题。用户将输入一个动物名称列表(未指定数量),我需要在用户输入中记录动物名称及其出现次数。起初,我尝试使用数组,但由于它是静态的,我转向std::vector
. 同样,起初,我尝试使用两个std::vector
,一个带有类型int
,另一个带有类型string
来存储动物名称和出现次数。但是,稍后对两个向量进行排序似乎有点困难,并且在我看来std::vector
,带有pair
类型的a听起来更好。现在,我被下面的代码困住了,但我不太明白:
#include <bits/stdc++.h>
#include <sstream>
using namespace std;
int position(vector< pair<string, int> > myList, string animalName) {
int pos;
for (int i = 0; i < myList.size(); i++) if (animalName.compare(myList[i].first) == 0) pos = i;
return pos;
}
int main() {
int Q;
cin >> Q;
vector< pair<string, int> > zooPair;
string animal;
for (int i = 0; i < Q; i++){
cin >> animal;
if (find_if(zooPair.begin(), zooPair.end(), animal.compare(zooPair.first) == 0) == zooPair.end())
zooPair.emplace_back(animal, 1);
else
zooPair[position(zooPair, animal)].second += 1;
}
sort(zooPair.begin(), zooPair.end());
for (vector< pair<string, int> >::iterator it = zooList.begin(); it != zooList.end(); it++)
cout << *it;
return 0;
}
您只需将其std::map
用作容器类型,因为它已经排序,并且具有带有 operator[] 的易于使用的访问接口。在这里,我们std::map
用您的动物和动物园中的动物数量创建一个。
例子:
int main() {
int Q;
std::cout << "Enter number of entries" << std::endl;
std::cin >> Q;
std::map<std::string, int> zoo;
std::string animal;
for (int i = 0; i < Q; i++){
std::cout << "Enter animal" << std::endl;
std::cin >> animal;
zoo[animal]++;
}
for ( auto& it: zoo )
{
std::cout << it.first << " " << it.second << std::endl;
}
return 0;
}
如您所见,无需额外排序,因为映射始终针对每个条目的第一部分(名为“键”)进行排序。
与 相同std::vector
。请注意,您必须为排序和查找提供运算符!
完整示例:
struct SortableElements: public std::pair< std::string, int >
{
// forward construction
using std::pair<std::string, int>::pair;
// use for sort:
bool operator < (const SortableElements& e2 ) const
{
return first < e2.first;
}
// use for find:
bool operator == ( const std::string& e2 ) const
{
return first == e2;
}
};
int main()
{
std::vector< SortableElements > zoo;
int Q;
std::cout << "Enter number of entries" << std::endl;
std::cin >> Q;
std::string animal;
for (int i = 0; i < Q; i++){
std::cout << "Enter animal" << std::endl;
std::cin >> animal;
auto it = std::find( zoo.begin(), zoo.end(), animal);
if ( it != zoo.end())
{
it->second++;
}
else
{
zoo.emplace_back( animal, 1 );
}
}
// sort:
std::sort(zoo.begin(), zoo.end());
for ( auto& it: zoo )
{
std::cout << it.first << " " << it.second << std::endl;
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句