处理向量集时出错

error in handling set of vectors

本文关键字:出错 向量 处理      更新时间:2023-10-16

我是标准模板库的新手,我想存储重叠的子序列。因为集合忽略重复项。我有一组向量:

set<vector<int> > subsequences;

但是当我尝试插入此集合时:

sort(arr.begin(), arr.end());
subsequences.insert(arr);

我收到一个错误:

coinChange.cpp:20:18: error: no matching member function for call to 'insert'
    subsequences.insert(arr);
    ~~~~~~~~~~~~~^~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/set:596:25: note:
      candidate function not viable: no known conversion from 'vector<long long, allocator<long
      long>>' to 'const vector<int, allocator<int>>' for 1st argument
    pair<iterator,bool> insert(const value_type& __v)
                        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/set:613:14: note:
      candidate function template not viable: requires 2 arguments, but 1 was provided
        void insert(_InputIterator __f, _InputIterator __l)
             ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/set:604:14: note:
      candidate function not viable: requires 2 arguments, but 1 was provided
    iterator insert(const_iterator __p, const value_type& __v)
         ^

由于我是STL的新手,我无法理解我做错了什么。请帮忙。

鉴于错误,您很可能声明了一个std::vector<long, long>,并假设它与std::vector<int>兼容。 事实并非如此。

如果TU是不同的类型,那么std::vector<T>std::vector<U>也是不同的类型。 在您的情况下,Tint,而Ulong long

以下代码正确编译:

#include <set>
#include <vector>
#include <algorithm>
using namespace std;
int main() 
{
    std::set<vector<int> > subsequences;    
    std::vector<int> arr;
    std::sort(arr.begin(), arr.end());
    subsequences.insert(arr);
}

而以下代码会产生您看到的错误:

#include <set>
#include <vector>
#include <algorithm>
using namespace std;
int main() 
{
    std::set<vector<int> > subsequences;    
    std::vector<long long> arr;
    std::sort(arr.begin(), arr.end());
    subsequences.insert(arr);
}

因此,显而易见的解决方法是确保您使用相同的类型。 确保这一点的一种方法是使用 typedef ,并确保在代码库中使用它来表示要使用的向量类型:

//...
typedef std::vector<int> IntVector;  // change this to long long if needed
//...
std::set<IntVector> subsequences;
IntVector arr;
//...

错误消息说明了问题所在:

candidate function not viable: no known conversion from 'vector<long long, allocator<long long>>' to 'const vector<int, allocator<int>>' for 1st argument

您正在尝试将vector<long long>传递到set<vector<int>>::insertvector<long long>是与vector<int>不同的类型,这就是为什么它不起作用的原因。要修复它,请始终使用相同类型的矢量。

错误显示"没有从vector<**long long**, allocator<long long>>const vector<**int**, allocator<int>>的已知转换

看起来您正在尝试在应该包含整数向量的集合中插入一个长长的向量。