can std :: unique可用于确定自定义类的对象是否具有相同的值?

dme*_*ine 0 c++ algorithm stl vector c++11

我有一个帧率列表和一个相关的屏幕分辨率列表.问题是我的resoltuions列表中有大量重复项.实际上,我也在帧率列表中获得了大量的重复项(非常感谢,Windows!),但是当我对原始列表进行排序时,通过简单的比较消除了这些重复项.我想我想用它std::algorithm来帮助我消除我的重复,但我无法让它工作.

码:

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

struct resolution {
    int w;
    int h;
};

int main(void) {

    std::vector<std::pair<int, std::vector<resolution>>> vec;
    for (int i = 0; i < 5; i++) {
        std::pair<int, std::vector<resolution>> p;
        p.first = i;
        for (int j = 0; j < 5; j++) {
            resolution res;
            res.w = j;
            res.h = j;
            p.second.push_back(res);
        }
        vec.push_back(p);
    }

    for (std::vector<std::pair<int, std::vector<resolution>>>::iterator it = vec.begin();
        it != vec.end();
        ++it) {
        it->second.erase(std::unique(it->second.begin(), it->second.end()), it->second.end());
    }

    for (std::vector<std::pair<int, std::vector<resolution>>>::iterator it1 = vec.begin();
        it1 != vec.end();
        ++it1) {
        for (std::vector<resolution>::iterator it2 = it1->second.begin();
            it2 != it1->second.end();
            ++it2) {
            std::cout << it1->first << ": " << it2->w << " x " << it2->h << std::endl;
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我从算法中得到以下编译器错误:

Error   C2672   'operator __surrogate_func': no matching overloaded function found  dummy_erase c:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm    1503    
Error   C2893   Failed to specialize function template 'unknown-type std::equal_to<void>::operator ()(_Ty1 &&,_Ty2 &&) const'   dummy_erase c:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm    1503    
Error   C2672   'operator __surrogate_func': no matching overloaded function found  dummy_erase c:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm    1506    
Error   C2893   Failed to specialize function template 'unknown-type std::equal_to<void>::operator ()(_Ty1 &&,_Ty2 &&) const'   dummy_erase c:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm    1506    
Run Code Online (Sandbox Code Playgroud)

我没有多少经验,<algorithm>但我怀疑问题是std::unique不明白如何比较我的resolution对象.如果事实上是这样的话,我可以在resolution课堂上添加一些内容以使它更好std::unique吗?或者,还有其他方法可以优雅地做到这一点吗?

我总是可以手动完成列表和一些条件的另一个传递,但避免做那种事情正是使用C++而不是C的一个原因.如果有一个技巧,我会喜欢知道.

max*_*x66 6

你必须添加一个比较器.

尝试添加

bool operator == (resolution const & r1, resolution const & r2)
 { return (r1.w == r2.w) && (r1.h == r2.h); }
Run Code Online (Sandbox Code Playgroud)

你可以把它resolution作为friend函数写在体内

struct resolution {
    int w;
    int h;

    friend bool operator == (resolution const & r1, resolution const & r2)
     { return (r1.w == r2.w) && (r1.h == r2.h); }
};
Run Code Online (Sandbox Code Playgroud)