New to C++. I am learning on my own using C++ Primer and I am doing one of the problems about vectors. My code runs and does what I want. All I am looking for here is some tips on whether I am doing this in an efficient way or not. Thanks in advance.
/*Read a set of integers into a vector. Print the sum of each
pair of adjacent elements. Change your program so that it prints the sum of
the first and last elements, followed by the sum of the second and second-tolast,
and so on.*/
#include <iostream>
#include <vector>
int main()
{
std::cout << "Enter a set of integers: " << std::endl;
int number;
std::vector<int> vec;
while(std::cin >> number)
vec.push_back(number);
// Perform the sum of adjacent elements
std::cout << '\n';
std::cout << "The sume of adjacent terms is: " << std::endl;
int sum_adj = 0;
for(decltype(vec.size()) index = 0; index < vec.size()-1; ++index){// the range has to be up to size -1 to avoid out-of-range sums
sum_adj = vec[index]+vec[index+1];
std::cout << sum_adj << std::endl;
}
std::cout << '\n';
std::cout << "The sume of opposite-end terms is: " << std::endl;
// Perform the sum of opposite elements
int sum_opp = 0;
if(vec.size()%2==0){
for(decltype(vec.size()) index = 0; index < vec.size()/2; ++index){
sum_opp = vec[index]+vec[vec.size()-1-index];
std::cout << sum_opp << std::endl;
}
}
else{
for(decltype(vec.size()) index = 0; index < vec.size()/2; ++index){
sum_opp = vec[index]+vec[vec.size()-1-index];
std::cout << sum_opp << std::endl;
}
std::cout << vec[vec.size()/2] << " central value" << std::endl;
}
return 0;
}
Line 14: Keep in mind that <vector> will periodically reallocate the underlying memory as you add elements. With a simple program such as this, that really is not an issue, but it is something to keep in mind as your programs get larger and more complex.
Lines 21,30,36: Are you sure you want to output the sum each time through the loop?
Generally you would output the sum after you have iterated through the array.