C ++ vector <struct>排序不起作用

时间:2015-05-01 05:36:40

标签: c++ sorting vector

我正在尝试编写一个对Entry项目的矢量进行排序的函数,这些函数在我的头文件中定义。

struct Entry{
    string word;
    int count;
};

基本上,每个条目都有stringint。我要做的是按每个条目的vector<Entry>值按降序排序count。我尝试在.cpp文件中使用std::sort

bool intcomp(const Entry &lhs, const Entry &rhs){
    return lhs.count < rhs.count;
}

void SortedByCount(std::ostream &out) const{
    std::sort(vocabulary.begin(), vocabulary.end(), intcomp);
}

然后编译器会发出一大堆错误,比如这个

/usr/bin/../lib/gcc/x86_64-redhat-linux/4.8.3/../../../../include/c++/4.8.3/bits/stl_heap.h:247:12: note:
  in instantiation of function template specialization
  'std::__push_heap<__gnu_cxx::__normal_iterator<Entry *const *,
  std::vector<Entry *, std::allocator<Entry *> > >, long, Entry *>'
  requested here
  std::__push_heap(__first, __holeIndex, __topIndex,
       ^

我很遗憾该怎么做,所以任何指针都会受到赞赏。

编辑: 头文件包含Entry及其构造函数的结构,以及intcompSortedByCount(std::ostream &out) const的原型,而.cpp文件包含intcompSortedByCount(std::ostream &out) const的定义。我收到这个错误:

 reference to non-static member function must
 be called
 std::sort(vocabulary.begin(), vocabulary.end(), intcomp);
                                                 ^

是因为intcomp()方法不是静态的吗?或者还有什么呢?再次感谢。

3 个答案:

答案 0 :(得分:3)

您的vocabulary向量包含指向Entry的指针,而不包含指向Entry的指针。将比较器更改为以下内容:

bool intcomp(const Entry *lhs, const Entry *rhs){
    return lhs->count < rhs->count;
}

答案 1 :(得分:0)

要使用自定义条件对矢量内容进行排序,可以使用C ++ 11 lambda:

sort(entries.begin(), entries.end(),
    [](const Entry& a, const Entry& b)
    {
        return a.Count > b.Count;
    }
);

可编辑的源代码示例如下(live here on Ideone):

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Entry 
{
    string Word;
    int Count;

    Entry(const string& word, int count)
        : Word(word), Count(count)
    {
    }
};

int main() {
    vector<Entry> entries = {{"hello", 2}, {"world", 8}, {"hi", 20}, {"connie", 10}};

    sort(entries.begin(), entries.end(),
        [](const Entry& a, const Entry& b)
        {
            return a.Count > b.Count;
        }
    );

    for (const auto& e : entries)
    {
        cout << e.Word << ": " << e.Count << '\n';
    }
}

<强>输出:

hi: 20
connie: 10
world: 8
hello: 2

答案 2 :(得分:0)

工作得很好:

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

struct Entry {
    std::string word;
    int count;

    Entry(const std::string& s, int c) : word(s), count(c) {}
};

std::vector<Entry> vocabulary;

bool intcomp(const Entry &lhs, const Entry &rhs) {
    return lhs.count < rhs.count;
}

void sortedbycount(std::ostream &out) {
    std::sort(vocabulary.begin(), vocabulary.end(), intcomp);
}

void main()
{
    vocabulary.push_back(Entry("second", 2));
    vocabulary.push_back(Entry("firs", 1));
    vocabulary.push_back(Entry("third", 3));

    sortedbycount(std::cout);

    for (const auto& e : vocabulary)
    {
        std::cout << e.word << " " << e.count << "\n";
    }
}