forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathex9_50.cpp
More file actions
46 lines (37 loc) · 860 Bytes
/
ex9_50.cpp
File metadata and controls
46 lines (37 loc) · 860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//! @Alan
//!
//! Exercise 9.50:
//! Write a program to process a vector<string>s whose elements represent integral values.
//! Produce the sum of all the elements in that vector.
//! Change the program so that it sums of strings that represent floating-point values.
//!
#include <iostream>
#include <string>
#include <vector>
int sum(const std::vector<std::string> &v);
float sum_f(const std::vector<std::string> &v);
int main()
{
std::vector<std::string> v = {"1","2","3","4.5"};
std::cout << sum(v)<<"\n";
std::cout << sum_f(v);
return 0;
}
int sum(const std::vector<std::string> &v)
{
int sum=0;
for(auto &s : v)
{
sum += std::stoi(s);
}
return sum;
}
float sum_f(const std::vector<std::string> &v)
{
float sum = 0.0;
for(auto &s : v)
{
sum += std::stof(s);
}
return sum;
}