C++向量<Struct>排序不起作用

C++ vector<Struct> sorting not working

本文关键字:排序 不起作用 gt Struct lt C++ 向量      更新时间:2023-10-16

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

struct Entry{
    string word;
    int count;
};

基本上,每个条目都有一个string和一个int。我正在尝试做的是按每个条目的count值降序对vector<Entry>进行排序。我尝试在.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,
       ^

我对该怎么做感到非常迷茫,所以任何指示都将不胜感激。

编辑:头文件包含 Enter 的结构及其构造函数,以及 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()方法不是静态的吗?或者还能是什么?再次感谢。

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

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

工作正常:

#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";
    }
}

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

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

可编译的源代码示例如下( 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