### subtract values from elements in a vector

I have two vectors with the values

2.123, 2.111, 9.222
1.22, 4.33, 2.113

I want to subtract the first element of each Vector with each other, the second element of each Vector, and the third. so

abs(2.123-1.22)
abs(2.111-4.33)
abs(9.222-2.113)

I'm pretty sure you have to create a for loop but I'm not sure how to approach this problem as I am new to C++. Thank you all for your help.

The code below is a general concept of what I have

 ``12345678910`` ``````std::vector data1, vector data2, vector result; std::cout << "Enter in data#1 "; std::cin >> data1; std::cout << "Enter in data#2 "; std::cin >> data2; for (int i=0;i
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344`` ``````#include #include #include #include #include #include int main() { const double inf = 1.0 / 0.0 ; const double nan = 0.0 / 0.0 ; std::vector data1 { 2.123, 2.111, 9.222, -5.6, 6.8, 0.0, nan } ; std::vector data2 { 1.22, 4.33, 2.113, 0.0, 13.2, inf, nan } ; // 0 - infinity == -infinity, std::abs(-infinity) is +infinity // NaN - NaN == NaN // ... assert( data1.size() <= data2.size() ) ; { // algorithm (uses iterators): works with all sequence containers std::vector result ; std::transform( std::begin(data1), std::end(data1), std::begin(data2), std::back_inserter(result), []( double a, double b ) { return std::abs(a-b) ; } ) ; for( double d : result ) std::cout << d << ' ' ; std::cout << '\n' ; } { // subscript: works with sequence containers which support random access std::vector result ; for( std::size_t i = 0 ; i < data1.size() ; ++i ) result.push_back( std::abs( data1[i] - data2[i] ) ) ; for( double d : result ) std::cout << d << ' ' ; std::cout << '\n' ; } }``````

http://coliru.stacked-crooked.com/a/f343e4784b19b48a
here's a way without the C++11:

 ``12345`` ``````let's say you have: [code] typedef std::vector Data; Data data1; Data data2; ``````

You can make a function to do it for you:
 ``1234567891011`` ``````Data subtract(Data& data1, Data& data2) { Data output; for (Data::iterator it1 = data1.begin(), it2 = data2.begin(); it1 != data1.end() && it2 != data2.end(); ++it1, ++it2 ) { output.push_back( *it1 - *it2 ); } return output; }``````

or without iterators (for more simplicity):
 ``123456789`` ``````Data subtract(Data& data1, Data& data2) { Data output; for (int i = 0; i < min( data1.size(), data2.size() ); ++i) output.push_back( data1[i] - data2[i] ); return output; }``````
[/code]
Topic archived. No new replies allowed.