Вы уже были на полпути. Я написал комментированную замену для read_weights()
; вы сможете взять его оттуда.
#include <vector>
#include <limits>
#include <iostream>
// Use return values instead of working on global variables.
// Avoid using global variables whenever possible, they are a
// maintenance pain.
std::vector< double > read_weights()
{
std::vector< double > weights;
double weight;
// You can embed the \n right in the string, no need to put it as a
// separate character.
std::cout << "Input weights; enter a non-number to terminate input.\n";
// If anything not double is entered, cin goes into fail state --
// that is our terminating condition right there, so use it!
while ( std::cin >> weight )
{
weights.push_back( weight );
}
// Clean up cin
std::cin.clear();
// Use the correct type for max(); you had 'double' here...
cin.ignore( numeric_limits< std::streamsize >::max(), '\n' );
// Don't worry about the apparent copying of the vector upon return.
// Any modern compiler should be able to optimize this away.
return weigths;
}
Простой main () для тестирования:
int main()
{
std::vector< double > weights = read_weights();
std::cout << "Vector contents:\n";
for ( auto & v : weights )
{
std::cout << v << "\n";
}
}
Теперь все, что вам нужно добавить, это read_price()
... теперь подожди, не так ли? Потому что все, что вы на самом деле делаете, это то же самое, что и в read_weights()
, вводя двойные числа! Так что переместите приглашение ввода из read_weights()
и сделайте его одной функцией, read_values()
, которую вы вызываете дважды, один раз для получения weights
и один раз для получения prices
...
int main()
{
std::cout << "Enter weights; enter a non-number to terminate input.\n";
std::vector< double > weights = read_values();
std::cout << "Enter prices; enter a non-number to terminate input.\n";
std::vector< double > prices = read_values();
// ...
}
Для функции calculate
используйте ссылки на параметры, чтобы векторы не нужно было копировать:
void calculate( std::vector<double> & weights, std::vector<double> & prices )
И как только вы все это запустите, имейте в виду что позже вы (или, по крайней мере, должен ) будете изучать <algorithm>
, функторы и лямбды ... которые должны устранить необходимость в calculate
и заменить его элегантным - лайнер ... но это еще не все, и сейчас я не хочу вас этим путать.