简体   繁体   中英

subtract values from elements in a vector C++

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

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 do not know yet standard algorithms as suggested here algorithm std::transform you can write an equivalent code using an ordinary for statement. For example

std::vector<double> a { 2.123, 2.111, 9.222 };
std::vector<double> b { 1.22, 4.33, 2.133 }; 
std::vector<double> c( a.size(), 0.0 );


for ( std::vector<double>::size_type i = 0; i < a.size(); i++ )
{
   c[i] = std::abs( a[i] - b[i] );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM