2013-10-02 84 views
-3

所以我想排序向量中存储的卡片矢量。C++ STL排序向量

载体是std::vector<CUE> CUE是一个类,它代表“卡下评估”,而里面的卡是const Card*。我需要的是使用我创建的名为compareCards的函数对卡片进行排序。

不过,我产生了以下错误:

error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'CUE'

函数声明是在叫Table.h另一个文件,以及排序通话中Table.cpp。这整个事情都是为了我正在创造的一场扑克比赛,但是整理手牌产生了一个让我停下来的错误。

如何在成功分选手的同时摆脱此错误?

下面是相关代码:

排序召唤:

Table.cpp

std::sort(cardvec.begin(), cardvec.end(), compareCards); 

函数声明:

Table.h

bool compareCards(const Card* c1, const Card* c2) 
{ 
    return c1->GetPip() < c2->GetPip(); 
} 

CUE。 h

#pragma once 
#include <vector> 
#include <iostream> 
#include "card.h" 

struct CUE 
{ 
    CUE(void); 
    ~CUE(void); 
    CUE(const std::vector<const Card*>& c) : _cue(c){} 
    std::vector<const Card*> _cue; 
}; 
+2

在C++中,你不需要添加空隙参数的功能。 – RedX

+1

什么是Pip?它是否可排序? – RedX

+0

我认为你的回调函数'compareCards'有错误的原型 – Bathsheba

回答

0

作为替代亚当的答案,继承人类似的解决方案使用更现代的风格(数值代替指针,初始化器列表,比较器的lambda,基于循环的范围等)

你可以看到在这里运行:http://coliru.stacked-crooked.com/a/96a4385814c7a4e5

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

struct X { 
    int n; 
    X(int v) : n(v) {} 
}; 

void print(const std::vector<X>& container) { 
    for (const auto& value : container) { 
     std::cout << value.n << " "; 
    } 
    std::cout << "\n"; 
} 

int main() {  
    std::vector<X> v{5, 4, 6}; 
    print(v); 
    std::sort(v.begin(), v.end(), [](const X& a, const X& b){ return a.n < b.n; }); 
    print(v); 
} 
+0

如果你想完全现代化,那么你应该避免打印裸圈。你想要的东西是:'std :: copy(std :: begin(container),std :: end(container),std :: ostream_iterator (std :: cout,“”));'当然还有其他一些更改也需要支持。 –

+0

@AdamBurry的确如此 - 但我想保持简短的例子。另外,这个打印函数实际上只是表明排序在这个演示中起作用,而不是问题所困扰的排序逻辑的一部分。 – zmb

1

这是在代码的风格的工作示例,你呈现(C++ 98):

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

struct X { 
    int n; 
    X(int v) : n(v) {} 
}; 

bool compare(const X* a, const X* b) { 
    return a->n < b->n; } 

int main() { 
    std::vector<const X*> v; 
    v.push_back(new X(5)); 
    v.push_back(new X(4)); 
    v.push_back(new X(6)); 

    for (int i = 0; i < v.size(); ++i) { 
    std::cout << v[i]->n << " "; 
    } 
    std::cout << "\n"; 

    std::sort(v.begin(), v.end(), compare); 

    for (int i = 0; i < v.size(); ++i) { 
    std::cout << v[i]->n << " "; 
    } 
    std::cout << "\n"; 
} 

输出

5 4 6 
4 5 6 
+4

而且你有一个令人难以置信的无意义的内存泄漏。无论如何,你为什么要使用指针? – rubenvb

+2

@rubenvb,因为问题使用指针。 –