输出对象中唯一字符的数量
Output the number of unique characters in an object
我需要调用该方法以从 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() );
相关文章:
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 检查字符串是否仅包含使用.at(int)的唯一字符
- 生成唯一的随机字符并将其保存在数组中
- 使用哈希 C++ 查找具有 k 个不同/唯一字符的最长子字符串
- 检查字符串是否具有C++中的所有唯一字符
- 如何调整属于类的唯一指针的字符数组的大小.它必须在程序的整个生命周期中保持活力
- 字符是唯一具有强制大小的类型
- 计算数组中唯一字符的函数
- 唯一的字符代码在 Linux 中运行时不起作用,但在 Windows (C++) 中很好
- 输出对象中唯一字符的数量
- 给定一个字符串,我如何才能只添加另一个字符串中的唯一字符
- 确定std::string是否具有所有唯一字符[C++]
- c++唯一字符检查
- 实现O(n)算法来确定字符串是否所有字符都是唯一的
- 从字符串中删除两个字符以获得唯一字符的可能性
- 使用Unordered_map在c++中创建字符串中的第一个唯一字符
- 检查字符串是否有唯一字符
- 有人能解释一下这个程序来检查字符串中的唯一字符吗?
- 字符数组是唯一具有某种形式的null终止的类型吗
- 在c++中,判断unicode字符字符串是否具有唯一字符的最有效方法是什么?