here's my code
Code:
1 //sum all elements at v[2*i]
2 //test on ints and doubles
3
4 #include <iostream>
5 #include <vector>
6 #include <cstdlib>
7 #include <ctime>
8
9 using namespace std;
10
11 template <typename foo_t>
12 foo_t sum_elements(vector<foo_t>& the_array){
13
14 foo_t sum = 0;
15 vector<foo_t>::iterator x;
16
17 for(x = the_array.begin(); x != the_array.end(); x+=2)
18 sum+=*x;
19
20 return sum;
21 }
22
23 int main(void){
24
25 const int vector_size = 20;
26 const int rand_range = 1001;
27 srand(time(nullptr));
28
29 vector<int> v1 = {};
30 vector<double> v2 = {};
31 vector<int>::iterator v1_iter;
32 vector<double>::iterator v2_iter;
33
34 //populate vectors with data
35 int i = 0;
36 for(v1_iter = v1.begin(); v1_iter != v1.end(); ++v1_iter){
37 int j = rand() % rand_range;
38 v1.push_back(j);
39 cout << "vector<int>["<<i<<"] = " << j << "\n";
40 i++;
41 }
42
43 for(v2_iter = v2.begin(); v2_iter !=v2.end(); ++v2_iter){
44 int i = rand() % rand_range;
45 v2.push_back(i);
46 }
47
48 //operate on data...sum elements...output results
49 cout << "the sum of vector<int> is " << sum_elements(v1) << endl;
50 cout << "the sum of vector<double> is " << sum_elements(v2) << endl;
51
52 return 0;
53 }
here's my compiler error
Code:
p345no3.cpp: In function ‘foo_t sum_elements(std::vector<foo_t>&)’:
p345no3.cpp:15:4: error: need ‘typename’ before ‘std::vector<foo_t>::iterator’ because ‘std::vector<foo_t>’ is a dependent scope
p345no3.cpp:15:28: error: expected ‘;’ before ‘x’
p345no3.cpp:17:8: error: ‘x’ was not declared in this scope
p345no3.cpp: In instantiation of ‘foo_t sum_elements(std::vector<foo_t>&) [with foo_t = int]’:
p345no3.cpp:49:59: required from here
p345no3.cpp:15:4: error: dependent-name ‘std::vector<foo_t>::iterator’ is parsed as a non-type, but instantiation yields a type
p345no3.cpp:15:4: note: say ‘typename std::vector<foo_t>::iterator’ if a type is meant
p345no3.cpp: In instantiation of ‘foo_t sum_elements(std::vector<foo_t>&) [with foo_t = double]’:
p345no3.cpp:50:62: required from here
p345no3.cpp:15:4: error: dependent-name ‘std::vector<foo_t>::iterator’ is parsed as a non-type, but instantiation yields a type
p345no3.cpp:15:4: note: say ‘typename std::vector<foo_t>::iterator’ if a type is meant
now I made the necessary changes and incude the typename keyword but my question is why exactly is it needed. what does that mean std::vector<foo_t> is a dependant scope. I thought the typename syntax before the function definition took care of that and allowed the type instantiation at compile time.
also for some reason my vectors aren't initializing with the random values.