C++求两个向量的差

ljo96ir5  于 2023-03-09  发布在  其他
关注(0)|答案(2)|浏览(244)

假设你有两个向量

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}
k3fezbri

k3fezbri1#

//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
    //but you can sort with:
    //std::sort(std::begin(v1), std::end(v1))

    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';
}
2ul0zpep

2ul0zpep2#

The accepted answer仅适用于已排序向量的类型,而<运算符已重载。
如果你有一个重载了<运算符的类型,但是向量没有排序,你需要先排序它们:

#include <algorithm>
#include <vector>

std::vector<int> v1 {3,1,3,2,4,1,5,5,6};
std::vector<int> v2 {6,1,4,5,2,3};
std::vector<int> diff;
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::inserter(diff, diff.begin()));

如果<运算符没有被重载,你可以编写自己的比较器:

#include <algorithm>
#include <vector>

std::vector<SomeType> v1 {...};
std::vector<SomeType> v2 {...};
std::vector<SomeType> diff;
const auto cmp = [](const SomeType &a, const SomeType &b){
    //Should return true if a is considered strictly less than b
};
std::sort(v1.begin(), v1.end(), cmp);
std::sort(v2.begin(), v2.end(), cmp);
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::inserter(diff, diff.begin()), cmp);

但是,如果编写自己的比较器并非易事,那么编写自己的函数来查找向量之间的差异可能会更容易:

#include <algorithm>
#include <vector>

template<typename T>
std::vector<T> vectorDifference(const std::vector<T> &v1, const std::vector<T> &v2){
    //Make the result initially equal to v1
    std::vector<T> result = v1;

    //Remove the elements in v2 from the result
    for(const T &element: v2){
        const auto it = std::find(result.begin(), result.end(), element);
        if(it != result.end()){
            result.erase(it);
        }
    }
    return result;
}

相关问题