gpt4 book ai didi

c++ - 创建 vector 集

转载 作者:行者123 更新时间:2023-11-30 02:14:32 24 4
gpt4 key购买 nike

我正在尝试用 C++ 创建一组 vector 。我希望 vector [1,2][2,1] 在集合中被视为相等。所以两者都不应该存在于集合中。此外, vector 可以多次包含相同的元素,因此 [1,2][1,2,2] 不应该相等。

我尝试了以下代码:

int main() {
vector<int> vt1{1,2};
vector<int> vt2{2,1};
set<vector<int>> st;
st.insert(vt1);
st.insert(vt2);
}

但是运行这段代码后,我发现集合中同时包含了[1,2][2,1]

最佳答案

如果您不能使用内部 std::multi_set 而确实需要 std::vector (并保持 std::vector 的原始顺序),您可以提供自定义比较器:

#include <algorithm>
#include <iostream>
#include <set>
#include <vector>

struct compare_as_set
{
template <typename T>
bool operator()(std::vector<T> rhs, std::vector<T> lhs) const
{
std::sort(rhs.begin(), rhs.end());
std::sort(lhs.begin(), lhs.end());

return rhs < lhs;
}
};

int main() {
std::vector<int> vt1{ 1,2 };
std::vector<int> vt2{ 2,1 };
std::set<std::vector<int>, compare_as_set> st;
st.insert(vt1);
st.insert(vt2); // insertion would fail as vt2 is equivalent to vt1
std::cout << st.size() << std::endl; // So output is 1
}

Demo

关于c++ - 创建 vector 集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57670122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com