algorithm to add values of two ranges and place them into a third one

前端 未结 4 2003
说谎
说谎 2021-01-18 05:03

I was just wondering if there was anything (either in c++11 or boost) that could help me do something like this:

std::vector v1 = {1, 2, 3};
std::         


        
4条回答
  •  感情败类
    2021-01-18 05:56

    Just for fun, I'll point to an alternative to std::vector and std::transform. You could use std::valarray instead.

    #include 
    #include 
    
    int main() { 
        std::valarray a = {1, 2, 3};
        std::valarray b = {2, 5, 4};
    
        std::valarray c = a + b;    // look ma, no transform!
    
        for (int i=0; i<3; i++)
            std::cout << c[i] << "\t";
    }
    

    Result:

    3       7       7
    

    Unfortunately, even though the code for adding the valarrays together is simple and clean, valarray has never gained much popularity. As such, we're left with this rather strange situation where even code like that above that strikes me as very clean, straightforward and readable still almost qualifies as obfuscated, simply because so few people are accustomed to it.

提交回复
热议问题