好的,我有一个像这样的数组:
class name {
public:
string first;
int last;
name(string a, int b){
first = a;
last = b;
}
};
name arr[] { { "John", 1 }, { "Jane", 2 }, { "Dick", 3 }, { "John", 1 }, { "Jane", 2 } };
现在我只能将它们全部打印出来:
int main() {
int icount = sizeof(arr) / sizeof(name);
for (int i = 0; i < icount; i++){
cout << arr[i].first << " " << arr[i].last << endl;
}
}
Output will be like this:
John 1
Jane 2
Dick 3
John 1
Jane 2
但是我需要合并任何类似的结果,这意味着如果名称相同,我需要将它们加在后面。所需的输出应该是这样的:
John 2
Jane 4
Dick 3
我可以使用任何功能来合并它们,或者我应该怎么做呢?
答案 0 :(得分:0)
由于您使用的是C ++,因此可以使用Map完成工作。
这是您需要的完整程序。
#include <iostream>
#include <map>
using namespace std;
map<string, int> mer;
class name
{
public:
string first;
int last;
name (string a, int b)
{
first = a;
last = b;
}
};
name arr[] { { "John", 1 }, { "Jane", 2 }, { "Dick", 3 }, { "John", 1 }, { "Jane", 2 } };
void merge()
{
int icount = sizeof(arr) / sizeof(name);
for (int i = 0; i < icount; i++)
{
if (mer.count(arr[i].first) > 0)
{
mer[arr[i].first]++;
}
else
{
mer[arr[i].first] = 1;
}
}
}
int main()
{
int icount = sizeof(arr) / sizeof(name);
merge();
map<string,int>::iterator it;
for(it = mer.begin(); it != mer.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}
这将打印出您期望的结果。当然它会以相反的顺序打印。您可以使用反向迭代器来获得所需的结果。
答案 1 :(得分:0)
这是另一种变体:
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
class name {
public:
string first;
int last;
name(string a, int b);
};
name::name(string a, int b) : first(a), last(b)
{
}
int main(int argc, char **argv)
{
string names[] =
{
"John", "Jane", "Dick", "John", "Jane"
};
int values[] =
{
1, 2, 3, 1, 2
};
vector<name> people;
for (int i = 0; i < sizeof(names) / sizeof(*names); ++i)
{
people.push_back(name(names[i], values[i]));
}
map<string, int> unique_people;
for (vector<name>::const_iterator it = people.begin(),
end = people.end(); it != end; ++it)
{
if (unique_people.count(it->first) != 0)
{
unique_people[it->first] += it->last;
}
else
{
unique_people.insert(pair<string, int>(it->first, it->last));
}
}
for (map<string, int>::const_reverse_iterator it = unique_people.rbegin(),
end = unique_people.rend(); it != end; ++it)
{
cout << it->first << " " << it->second << endl;
}
return 0;
}