更新さて、ここでの私の最初の答え(以下を参照)はやや冗談でした。
したがって、 、 、および のみを使用した簡単なアプローチは次のvector
とおりiostream
ですfind_if
。
IdeOneでライブを見る
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
using namespace std;
struct entry {
string name;
unsigned quantity;
};
vector<entry> readData()
{
vector<entry> data;
string line, name;
unsigned quantity;
while (getline(cin, line) &&
istringstream(line) >> name >> quantity)
{
auto found = find_if(begin(data), end(data), [&](entry const& a) { return a.name == name; });
if (end(data) == found)
data.push_back({name, quantity});
else
found->quantity += quantity;
}
return data;
}
int main()
{
vector<entry> const data = readData();
for (auto it = data.begin(); it != data.end(); ++it)
cout << it->name << " " << it->quantity << "\n";
}
古い答え:
前回の質問がboost-spiritタグに投稿されてから途方もなく長い時間が経過しているため、この機会にこの回答をやり過ぎないようにしてください。
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;
namespace phx = boost::phoenix;
int main()
{
std::map<std::string, unsigned> data;
std::cin.unsetf(std::ios::skipws);
{
using namespace boost::spirit::qi;
phrase_parse(
boost::spirit::istream_iterator(std::cin), {},
(as_string[+alpha] >> uint_) [ phx::ref(data)[_1] += _2 ]
% eol,
blank);
}
std::cout << "Got #" << data.size() << " unique fruits\n";
{
using namespace boost::spirit::karma;
std::cout << format(delimit(' ') [auto_] % eol, data);
}
}
入力あり
apple 5
pear 2
grape 6
mangoes 3
apple 2
mangoes 9
版画
Got #4 unique fruits
apple 7
grape 6
mangoes 12
pear 2