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
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 −
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.
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.
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.
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);
});
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With