Я читал о потоках, но когда я пытаюсь отклониться от книг, чтобы выполнить задачу, мне кажется, что я делаю что-то не так.В любом случае вот начало моего кода.Если этот код может работать с небольшими изменениями, пожалуйста, дайте мне знать, в противном случае, если бы вы могли предоставить лучший «более похожий на C ++» маршрут, я был бы очень признателен.
#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
std::multimap<std::string,float> _map;
istream& operator>>(istream& stream, pair<string,float> in ) {
return stream >> in.first >> in.second;
}
int main( int argc, char *argv[ ] ) {
istream is( );
do {
pair<string,float> input;
is >> input;
_map.insert(input);
} while( is );
}
Ошибки компилятора:
[mehoggan@desktop bjarne_stroustrup]$ g++ -o map -Wall ./key_value_stats.cpp
./key_value_stats.cpp: In function ‘int main(int, char**)’:
./key_value_stats.cpp:20:15: error: no match for ‘operator>>’ in ‘is >> input’
./key_value_stats.cpp:12:10: note: candidate is: std::istream& operator>>(std::istream&, std::pair<std::basic_string<char>, float>)
./key_value_stats.cpp:22:14: warning: the address of ‘std::istream is()’ will always evaluate as ‘true’
ОБНОВЛЕНИЕ [0]:
После удаления () и изменения:
istream& operator>>(istream& stream, pair<string,float> in ) {
на
istream& operator>>(istream& stream, pair<string,float> &in ) {
Я получаю другой наборошибок компилятора:
/usr/lib/gcc/i686-redhat-linux/4.5.1/../../../../include/c++/4.5.1/istream: In function ‘int main(int, char**)’:
/usr/lib/gcc/i686-redhat-linux/4.5.1/../../../../include/c++/4.5.1/istream:582:7: error: ‘std::basic_istream<_CharT, _Traits>::basic_istream() [with _CharT = char, _Traits = std::char_traits<char>]’ is protected
./key_value_stats.cpp:17:13: error: within this context
со следующим кодом:
#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
std::multimap<std::string,float> _map;
istream& operator>>(istream& stream, pair<string,float> &in ) {
return stream >> in.first >> in.second;
}
int main( int argc, char *argv[ ] ) {
istream is;
do {
pair<string,float> input;
is >> input;
_map.insert(input);
} while( is );
}
ОБНОВЛЕНИЕ [1]
Хорошо, я решил проблему, я думаю.Возвращаясь к примеру Струструпа desk_calculator, у меня есть следующий код, который по крайней мере компилируется, я добавлю в него последние функции, а затем повторно опубликую окончательный продукт для всех, кто заинтересован.
#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
std::multimap<std::string,float> _map;
istream& operator>>(istream& stream, pair<string,float> &in ) {
return stream >> in.first >> in.second;
}
//void print_pair( pair<string,float>
int main( int argc, char *argv[ ] ) {
istream *is = &cin;
do {
pair<string,float> input;
(*is) >> input;
_map.insert(input);
} while( is );
}
ОБНОВЛЕНИЕ [2]
Не думаю, что я выполнил требования проблемы, но я получил технические вещи для работы.
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
/********************************************************************
* Read a sequence of possibly whitespace-separated (name,value)
* pairs, where the name is a single whitespaace-separated word and
* the value is an integer or floating-point value. Compute and print
* the sum and mean for each name and the sum and mean for all names
* ******************************************************************/
using namespace std;
std::multimap<string,float> _map;
istream& operator>>(istream& stream, pair<string,float> &in ) {
return stream >> in.first >> in.second;
}
ostream& operator<<(ostream& stream, pair<string,float> &out ) {
return stream << "(" << out.first
<< ", " << out.second << ")" << endl;
}
int main( int argc, char *argv[ ] ) {
istream *is = &cin;
do {
pair<string,float> input;
(*is) >> input;
_map.insert(input);
} while( is->peek( ) != EOF );
ostream *os = &cout;
multimap<string,float>::iterator mit = _map.begin( );
float sum = 0.0;
while( mit != _map.end( ) ) {
pair<string,float> p_pair = (*mit);
(*os) << p_pair;
sum+=p_pair.second;
mit++;
}
float mean = static_cast<float>( sum/_map.size( ) );
(*os) << "Sum: " << sum << " Mean: " << mean << endl;
}