Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract values from elements in a vector C++

Tags:

c++

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

std::vector<double> data1, vector<double> data2, vector<double> result;
std::cout << "Enter in data#1 ";
std::cin >> data1;

std::cout << "Enter in data#2 ";
std::cin >> data2;

for (int i=0;i<data1.size();i++){
    //start subtracting the values from each other and have them stored in another Vector
like image 626
Kara Avatar asked Jan 21 '14 18:01

Kara


People also ask

How to subtract all values in a vector from another vector?

To subtract all values in a vector from all values in another vector in R, we can use sapply function with subtraction sign. For Example, if we have two vectors say X and Y and we want to subtract all values in Y from all values in X then we can use the command given below −

What is subtraction in R programming?

R programming to subtract all values in a vector from all values in another vector. R programming to subtract all values in a vector from all values in another vector.

How do you subtract a number from an array in Python?

Subtraction in the Array Given an integer k and an array arr [], the task is to repeat the following operation exactly k times: Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0.

How do you find the sum of elements in an array?

Taking arr [] = {3, 6, 4, 2} and initially sum = 0 after sorting the array, it becomes arr [] = {2, 3, 4, 6} . Now sum = 0, and we print first nonzero element i.e. 2 and assign sum = 2 . In the next iteration, pick second element i.e. 3 and print 3 – sum i.e. 1 as 2 has already been subtracted from all the other non-zero elements.


2 Answers

Assuming they are both the same size:

std::vector<double> a;
std::vector<double> b;
// fill in a and b
std::vector<double> result;
std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(result), [&](double l, double r)
{
    return std::abs(l - r);
});
like image 105
Zac Howland Avatar answered Oct 02 '22 16:10

Zac Howland


You'd probably (at least normally) want to do this with std::transform:

std::vector<double> a{2.123, 2.111, 9.222}, 
                    b{1.22, 4.33, 2.133}, 
                    c;

std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(c),
    [](double a, double b) { return fabs(a-b); });
like image 24
Jerry Coffin Avatar answered Oct 02 '22 17:10

Jerry Coffin