Hello everyone.
I have tried to convert the following c program into c++ but my problem now is to change array in the program into vector.please help
[c code]
/* Convert this program to C++
* change to C++ io
* change to one line comments
* change defines of constants to const
* change array to vector<>
* inline any short function
*/
#include <stdio.h>
#define N 40
void sum(int*p, int n, int d[])
{
int i;
*p = 0;
for(i = 0; i < n; ++i)
*p = *p + d[i];
}
int main()
{
int i;
int accum = 0;
int data[N];
for(i = 0; i < N; ++i)
data[i] = i;
sum(&accum, N, data);
printf("sum is %d\n", accum);
return 0;
}
This is my c++ code :
// Convert this program to C++
// change to C++ io
//change to one line comments
// change defines of constants to const
// change array to vector<>
// inline any short function
#include <iostream>
#include<vector>
const int N =40;
void sum(int*p, int n, int d[])
{
int i;
*p = 0;
for(i = 0; i < n; ++i)
*p = *p + d[i];
}
int main()
{
int i;
int accum = 0;
int data[N];
for(i = 0; i < N; ++i)
data[i] = i;
sum(&accum, N, data);
cout<<" sum is "<< accum<<endl;
return 0;
}
#include <iostream>
#include <vector>
usingnamespace std;
constint N = 40;
template <typename T>
int sum(T val)
{
int s = 0;
for(int i = 0; i < val.size(); ++i)
s += val[i];
return s;
}
int main()
{
vector<int> vec;
for(int i = 0; i < N; ++i)
vec.push_back(i);
cout<<" sum is "<< sum(vec) << '\n';
return 0;
}
Output:
sum is 780
Using a template function you can pass many types of variables to T val, e.g. vector( like here), integer, floating, double.
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
constexprint N = 40 ;
int main()
{
std::vector<int> data(N); // vector of N integers
std::iota( std::begin(data), std::end(data), 0 ) ; // fill up with 0, 1, 2 ... N-1
std::cout << "sum is " // sum of the integers in data
<< std::accumulate( std::begin(data), std::end(data), 0 ) << '\n' ;
}