C++ get the difference between two vectors

放肆的年华 提交于 2021-02-07 06:17:07

问题


imagine you got 2 vectors:

vector<int> ar1, a2;

ar1 = {1,1,2,3,3,4,5,5,6};
ar2 = {1,2,3,4,5,6};

how to do something like this in a good way (using C++) ?

b = ar1 - ar2
// b = {1,3,5}

回答1:


//from cppreference
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
 
int main() {
 
    std::vector<int> v1 {1,1,2,3,3,4,5,5,6};
    std::vector<int> v2 {1,2,3,4,5,6};
    std::vector<int> diff;
    //no need to sort since it's already sorted
    std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(),
        std::inserter(diff, diff.begin()));
 
    for (auto i : v1) std::cout << i << ' ';
    std::cout << "minus ";
    for (auto i : v2) std::cout << i << ' ';
    std::cout << "is: ";
 
    for (auto i : diff) std::cout << i << ' ';
    std::cout << '\n';
}


来源:https://stackoverflow.com/questions/27192967/c-get-the-difference-between-two-vectors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!