Here is the code:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Pair{
string name;
double val;
};
vector<Pair> pairs;
double& value(const string& s)
{
for(int i=0; i < pairs.size(); i++)
if(s == pairs[i].name)
return pairs[i].val;
Pair p = {s, 0};
pairs.push_back(p);
return pairs[pairs.size() - 1].val;
}
int main()
{
string buf;
while(cin>>buf) value(buf)++;
for(vector<Pair>::const_iterator p = pairs.begin(); p != pairs.end(); ++p)
cout << p->name << ": " << p->val << '\n';
return 0;
}
The compiler always complains that Line (Pair p = {s, 0};) is wrong:
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
….\cpp\TEST.CPP:
Warning W8012 ….\cpp\TEST.CPP 18: Comparing signed and unsigned values in fun
ction value(const string &)
Error E2291 ….\cpp\TEST.CPP 22: } expected in function value(const string &)
Error E2034 ….\cpp\TEST.CPP 22: Cannot convert ‘const string’ to ‘Pair’ in fu
nction value(const string &)
Error E2141 ….\cpp\TEST.CPP 22: Declaration syntax error in function value(co
nst string &)
Error E2139 ….\cpp\TEST.CPP 22: Declaration missing ; in function value(const
string &)
Warning W8070 ….\cpp\TEST.CPP 22: Function should return a value in function
value(const string &)
Warning W8004 ….\cpp\TEST.CPP 22: ‘p’ is assigned a value that is never used
in function value(const string &)
Error E2190 ….\cpp\TEST.CPP 22: Unexpected }
Error E2238 ….\cpp\TEST.CPP 23: Multiple declaration for ‘pairs’
Error E2344 ….\cpp\TEST.CPP 14: Earlier declaration of ‘pairs’
Error E2141 ….\cpp\TEST.CPP 23: Declaration syntax error
Error E2040 ….\cpp\TEST.CPP 25: Declaration terminated incorrectly
Error E2190 ….\cpp\TEST.CPP 26: Unexpected }
* 10 errors in Compile *
The code compiles with only a warning using an up-to-date compiler (GCC 4.6.3). Your compiler must not be fully compliant.
For a compilation with GCC 4.3.4, see here.