输出对象中唯一字符的数量

Output the number of unique characters in an object

本文关键字:字符 唯一 对象 输出      更新时间:2023-10-16

我需要调用该方法以从 Person 对象返回一个人访问过的城市列表,并遍历该列表并逐个打印出来(我已经这样做了)。现在,我必须打印出该人访问过的独特城市的数量,但不知道如何访问。我如何简单地做到这一点(我只是理工学院的年级)?到目前为止,我有这个。

Person *person1 = new Person(listOfCities);
for (int i = 1; i <= 5; i++)
{
    cout << "Please enter name of city: ";
    cin >> cityName; 
    cout << "Please enter size of city: "; 
    cin >> citySize; 
    cout << "Please enter postal code of city: "; 
    cin >> postalCode; 
    cout << " " << endl;
    City myCity(cityName, citySize, postalCode); 
    person1->addCity(myCity);
}
for (int k = 0; k < person1->returnListOfCities().size(); k++) 
{
    cout << person1->returnListOfCities()[k].toString() << endl; 
}

toString() 方法显示城市的名称、大小和邮政编码。列表城市存储在向量中。

假设城市是一个 std::string,你可以从以下代码片段中获取指南:

#include <string>
#include <set>
#include <iostream>
using std::set;
using std::string;
using std::cout;
using std::cin;
int main()
{
    string s;
    set<string> cities;
    char response = 'y';
    while (response == 'y')
    {
        cout << "Enter name of city:t";
        cin >> s;
        cities.insert(s);
        cout << "Continue (y/n): ";
        cin >> response;
    }
    cout << "Total cities travelled:t" << cities.size();
}

好吧,我使用一个名为"set"的容器来存储访问的城市。足以给你想法。

更多关于片场的信息: http://www.cplusplus.com/reference/set/set/

只是忘了补充:它区分大小写,所以多伦多和多伦多将受到不同的对待。

我假设你被困在std::vector上,无法使用std::set.在下面的矢量中打印独特元素的示例

#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
    std::vector<int> v = { 1, 4, 1, 1, 2 };
    //std::unique works with sorted array only 
    std::sort( v.begin(), v.end() );
    //size of vector is not modified. But duplicate elements are overwritten with non duplicates
    // { 1, 2, 4, ?, ? }
    std::vector< int >::iterator endLocation;
    endLocation = std::unique( v.begin(), v.end() );
    //print unique elements
    std::ostream_iterator< int > output( std::cout, " " );
    std::copy( v.begin(), endLocation, output );
    return 0;
}

注 1:std::unique 更改现有数组。因此,如果必须再次使用矢量,请创建一个副本

注2:这涉及对单独在O( n log n )工作std::vector进行排序。如果std::vector中的元素数量很大,则最好创建仅保留唯一元素的std::set,并且对于std::set中使用的哈希算法O( log n )插入复杂性。但这会创建所有独特元素的副本(更多的空间限制)。具体如下。

std::set<int> uniqueElements( v.begin(), v.end() );