我需要调用该方法返回一个人从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()方法显示城市的名称,大小和邮政编码。 listOfCities存储在向量中。
答案 0 :(得分:0)
假设cities是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();
}
好吧,我使用了一个名为&#39; set&#39;存储访问过的城市。足以给你提供想法。
有关此处设置的详细信息:http://www.cplusplus.com/reference/set/set/
只是忘了添加:它区分大小写,所以多伦多和多伦多将被区别对待。
答案 1 :(得分:0)
我认为你被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改变现有数组。因此,如果必须再次使用vector,则创建一个副本
注意2:这涉及对std::vector
进行排序,单独在O( n log n )
处工作。如果std::vector
中的元素数量很大,则可能更好地创建std::set
,它只保留唯一元素,并且插入复杂度为O( log n )
用于散列std::set
中使用的算法。但这将创建所有独特元素的副本(更多空间限制)。它将如下所示。
std::set<int> uniqueElements( v.begin(), v.end() );