C++ 如何使用 std::sort 在 C++ 中对对象数组进行排序

标签 c++ sorting

我有模板类和指向对象的指针数组以及我的对象的重载逻辑运算符。我的冒泡排序正在工作。所以它知道如何比较我的对象 我想用标准排序替换它 声明

实现列表.tem

#include <stdio.h>
#include <stdlib.h>
#include <vector>
///////////////
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;

template <class Type>
List<Type>::List()
{
    itemPtr = NULL;
    used = 0;
    size = 0;
}


template <class Type>
List<Type>::List(const List<Type>& source)
{
    itemPtr = NULL;
    used = 0;
    size = source.size;
    itemPtr = new Type[size];
    for(int i = 0; i < source.used; i++)
        addItem(source.itemPtr[i]);
}

template <class Type>
List<Type>& List<Type>::operator = (const List<Type>& source)
{
    used = 0;
    if(this == &source)
        return(*this);  
    free();

    size = source.size;
    itemPtr = new Type[size];

    for(int i = 0; i < source.used; i++)
        addItem(source.itemPtr[i]);
    return(*this);
}    

template <class Type>
List<Type>::~List()
{
    free();
}

template <class Type>
void List<Type>::free() 
{
    if(itemPtr != NULL)
    {
        delete [] itemPtr;
        itemPtr = NULL;
    }
}

template <class Type>
void List<Type>::alloc(int sizeIcrease) 
{
    Type* tmpPtr = NULL;
    size += sizeIcrease;
    tmpPtr = new Type[size];
    copy(itemPtr, itemPtr+used, tmpPtr);
    free();
    itemPtr = tmpPtr;
}

template <class Type>
Type List<Type>::getItem(int index) const
{
    Type item;
    if(index >= 0 && index < used)
        item = itemPtr[index];
    return (item);
}    

template <class Type>
int List<Type>::findItem(Type itemIn)
{
    int i = 0;
    for(i = 0; i < used; i++)
        if(itemPtr[i] == itemIn)
            break;
    if (i == used)  i = -1;
    return (i);
}

template <class Type>
void List<Type>::addItem(Type itemIn)
{
    if(used == size) alloc(10);
    itemPtr[used++] = itemIn;
    bubbles();
}

template <class Type>
void List<Type>::removeItem(Type itemIn)
{
    int index = findItem(itemIn);
    removeItem(index);
}

template <class Type>
void List<Type>::removeItem(int index)
{
    if(index >= 0 && index < used)
        itemPtr[index] = itemPtr[--used];
    bubbles();
}

template <class Type>
void List<Type>::readFile(Field fileName)
{
    Type itemTmp;   
    ifstream inFile(fileName.c_str());
    if(!inFile)
        cout << "Error opening file\n";
    do
    {
        inFile >> itemTmp;
        if(!inFile.fail())
            addItem(itemTmp);

    } while (!inFile.fail());
    //bubbles();
    vector<Type*> myvector; //(itemPtr, itemPtr+used);

    vector<Type>::iterator it;
    sort (myvector.begin(), myvector.end(), sort_by_pointee<Type>());
    inFile.close();
}


template <class Type>
void List<Type>::writeFile(Field fileName)
{
    ofstream outFile;
    outFile.open(fileName.c_str());
    if(!outFile)
        cout << "Error opening file\n";

    for(int i = 0; i < used; i++)
    {
        outFile << itemPtr[i] << "\n";
    }

    outFile.close();
}
    template <class Type>
void List<Type>::print()
{
//////Coded
}

template <class Type>
void List<Type>::bubbles()
{
////// Coded
}

template <class Type>
ostream& operator<<(ostream& os, const List<Type>& ad)
{
    for(int i = 0; i < ab.used; i++)    
        os << ab.getItem(i) << endl;
    return os;
}
template <class Type>
ofstream& operator<<(ofstream& ofs, const List<Type>& ad)
{
    for(int i = 0; i < ab.used; i++)            
        ofs << ab.getItem(i) << ",";
    return ofs;
}

template<class Type>
struct sort_by_pointee 
{
    bool operator() (const Type* lhs, const Type* rhs) const
    {
        return (*lhs < *rhs);
    }
};

最佳答案

如果 std::sort() 的第三个参数未提供,对象使用 operator< 排序喜欢:

if (a < b) {
   // ...
}

所以你只需要对 Foo 类型的对象进行排序是有:

bool Foo::operator< (const Foo& rhs) const;

bool operator< (const Foo& lhs, const Foo& rhs);

也就是说,如果你有一个指针数组,那么你将需要提供一个自定义谓词,除非你想按对象的内存地址对对象进行排序(我非常怀疑这就是你想要的).你可以这样做:

template<class T>
struct sort_by_pointee {
    bool operator() (const T* lhs, const T* rhs) const
    {
        return (*lhs < *rhs);
    }
};

像这样使用它:

std::vector<Foo*> foos;
// ...
std::sort(foos.begin(), foos.end(), sort_by_pointee<Foo>());

编辑:您发布的示例可以正常工作并对数据进行排序,但 vector 不会充当存储在 itemPtr 中的数据的代理。大批。再读一遍我的注释:

{ 
    vector<Type> myvector (itemPtr, itemPtr+8);
    // 'myvector' holds a copy of the first 8 elements in the 'itemPtr' array.

    sort (myvector.begin(), myvector.end());
    // contents of 'myvector' are sorted, but this is a copy of 'itemPtr''s
    // contents, so items in 'itemPtr' are still in their original order.
}

如果要对[itemPtr,itemPtr+8)的内容进行排序就地,你可以这样做:

std::sort(itemPtr, itemPtr+8); // use custom predicate if required.

编辑:好的,按照您发布的代码,我会修复 readFile()方法从其原始定义到:

template <class Type>
void List<Type>::readFile(Field path)
{
    ifstream file(path.c_str());
    if(!file.is_open()) {
        cout << "Error opening file\n";
    }
    for (Type item; file >> item;) {
        addItem(item);
    }
    sort (itemPtr, itemPtr+used);
}

关于C++ 如何使用 std::sort 在 C++ 中对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9862410/

相关文章:

c++ - 在 Visual Studio C++ 2008 Pro 中对 MFC 对话框进行额外的初始化

c++ - 共享内存系统性能上的消息传递接口(interface)

java - 在java中对数组的ArrayList进行排序

在 SQL CE(精简版)版本 3.5 中对字母数字字段进行排序

c++ - 如何访问其中有一对的 map

c++ - 从 C/C++ 程序 ping

C++11 强制转换const迭代器指向shared_ptr对象的容器

c++ - 智能指针的排序 vector : mysterious crash

python - 如何提高 python 中的合并排序速度

database - 内部排序,使用两个堆解释的锦标赛排序算法