C ++获得两个向量之间的差异

时间:2014-11-28 16:44:52

标签: c++ vector

想象你有2个向量:

vector<int> ar1, a2;

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

如何以一种好的方式做这样的事情(使用C ++)?

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

1 个答案:

答案 0 :(得分:9)

//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;
    //not need to sort since it 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';
}