首页 > 解决方案 > 如何将一对向量中一对的第一个元素(字符串)与另一个字符串进行比较?

问题描述

我正在尝试实施我所学到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;
}

标签: c++vector

解决方案


您只需将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;
}  

推荐阅读