c++ - 如何将一对向量中一对的第一个元素(字符串)与另一个字符串进行比较?
问题描述
我正在尝试实施我所学到std::vector
的解决问题的方法。用户将输入动物名称列表(未指定有多少),我需要在用户输入中记录动物名称及其出现。起初,我尝试使用数组,但由于它是静态的,我转向std::vector
. 同样,起初,我尝试使用两个std::vector
,一个带有 type int
,另一个带有 typestring
来存储动物名称和出现次数。但是,稍后对这两个向量进行排序似乎有点困难,并且在我看来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
其用作容器类型,因为它已经排序,具有易于使用的操作符 [] 访问接口。在这里,我们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;
}
推荐阅读
- javascript - 如何在节点 js 中将 TCP 套接字数据包发送到网页
- julia - 在 Julia 中解决 DDE 的问题
- python - 如何在 Pandas 中将具有 Null 值的浮点数据类型转换为整数?
- javascript - 将值/变量从 HTML 传递到 JS 文件
- python - 如何在我的脚本中添加这个 url 而不会使用 selenium python 中断当前循环
- javascript - 尝试列出数据库 postgres TypeError [ERR_INVALID_ARG_TYPE] 的表时收到错误
- python - Python:如何删除一行?
- javascript - 为什么 Google Calendar Freebusy 查询在忙数组中的时间与实际日历中的时间不同?
- facebook - Instagram Creator Studio 未加载要发布的视频
- javascript - 从复杂的物化路径类别层次结构数据中获取一个数组