在向量中计算相同字符串的更容易的方法? [英] Easier way to count identical strings in a vector?
问题描述
我正在尝试在矢量中获得所有相同字符串数量的输出,作为更大程序的一部分。经过大量的研究,我已经设法把东西放在一起,但它似乎凌乱,我想知道是否有更好的方法。
I am trying to get an output of the number of all the identical strings in a vector as part of a much larger program. After a lot of research I have managed to put something together that works but it seems messy and I was wondering if there was a better way to do it.
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <iostream>
using namespace std;
void setMap(string i);
void addMap(string i);
map<string, int> myMap;
int main()
{
vector<string> myVector;
string myArray[6]={"foo","foo","bar","roo","foo","bar"};
for (int i=0; i<6; i++)
{
myVector.push_back(myArray[i]);
}
for_each (myVector.begin(), myVector.end(), setMap);
for_each (myVector.begin(), myVector.end(), addMap);
for (map<string, int, less< string >>::const_iterator iter = myMap.begin();
iter != myMap.end(); ++iter )
cout <<iter->first<<'\t'<<iter->second<<endl;
return 0;
}
void setMap(string i)
{
myMap[i]=0;
}
void addMap(string i)
{
myMap[i]++;
}
此代码工作正常,并给出了我以后的输出,但我不是热衷于添加2个额外的功能使其工作或不得不使地图全局。
This code works fine and gives me the output I was after but I'm not that keen on having to add 2 extra functions to make it work or having to make the map global. Any hints would be gratefully received.
推荐答案
最简单的方法是没有额外的功能,没有地图作为全局的不要使用for_each。
Well the simplest way to not have the extra functions and not have the map as global would be to not use for_each.
for_each (myVector.begin(), myVector.end(), setMap);
for_each (myVector.begin(), myVector.end(), addMap);
成为
map<string, int> myMap;
for (vector<string>::iterator i = myVector.begin(); i != myVector.end(); ++i)
myMap[*i]=0;
for (vector<string>::iterator i = myVector.begin(); i != myVector.end(); ++i)
++myMap[*i];
一旦你这样做,你也可以删除第一个循环
Once you done that you could also remove the first loop
map<string, int> myMap;
for (vector<string>::iterator i = myVector.begin(); i != myVector.end(); ++i)
++myMap[*i];
由于地图值将被初始化为零。
since the map values will be initialised to zero anyway.
有什么让你认为你必须使用for_each吗?
What made you think you had to use for_each anyway?
这篇关于在向量中计算相同字符串的更容易的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!