处理矢量集时出错

时间:2016-01-29 11:29:14

标签: c++ vector stl set

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

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的新手,我无法理解我做错了什么。请帮忙。

3 个答案:

答案 0 :(得分:0)

错误消息显示错误:

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>的类型不同,这就是为什么它不起作用。要修复它,请始终使用相同类型的向量。

答案 1 :(得分:0)

该错误表示“无法从vector<**long long**, allocator<long long>>转换为const vector<**int**, allocator<int>>

看起来你正试图在一个应该包含整数向量的集合中插入一个long long的向量。

答案 2 :(得分:0)

鉴于错误,您很可能宣布std::vector<long, long>,并认为这与std::vector<int>兼容。事实并非如此。

如果TU的类型不同,则std::vector<T>std::vector<U>也是不同的类型。在您的情况下,TintUlong 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;
//...