使用二进制谓词和 std::sort
进行排序
我需要这个 sample ...
最佳答案
这是使用两种不同类型谓词的示例的另一种改编。指定的谓词可以是函数指针或仿函数,仿函数是定义 operator() 的类,以便对象在实例化时可以像函数一样使用。请注意,我必须向功能 header 添加一个 header 包含。这是因为仿函数继承自 std 库中定义的 binary_function。
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class MyData
{
public:
static bool compareMyDataPredicate(MyData lhs, MyData rhs) { return (lhs.m_iData < rhs.m_iData); }
// declare the functor nested within MyData.
struct compareMyDataFunctor : public binary_function<MyData, MyData, bool>
{
bool operator()( MyData lhs, MyData rhs)
{
return (lhs.m_iData < rhs.m_iData);
}
};
int m_iData;
string m_strSomeOtherData;
};
int main()
{
// Create a vector that contents elements of type MyData
vector<MyData> myvector;
// Add data to the vector
MyData data;
for(unsigned int i = 0; i < 10; ++i)
{
data.m_iData = i;
myvector.push_back(data);
}
// shuffle the elements randomly
std::random_shuffle(myvector.begin(), myvector.end());
// Sort the vector using predicate and std::sort. In this case the predicate is a static
// member function.
std::sort(myvector.begin(), myvector.end(), MyData::compareMyDataPredicate);
// Dump the vector to check the result
for (vector<MyData>::const_iterator citer = myvector.begin();
citer != myvector.end(); ++citer)
{
cout << (*citer).m_iData << endl;
}
// Now shuffle and sort using a functor. It has the same effect but is just a different
// way of doing it which is more object oriented.
std::random_shuffle(myvector.begin(), myvector.end());
// Sort the vector using predicate and std::sort. In this case the predicate is a functor.
// the functor is a type of struct so you have to call its constructor as the third argument.
std::sort(myvector.begin(), myvector.end(), MyData::compareMyDataFunctor());
// Dump the vector to check the result
for (vector<MyData>::const_iterator citer = myvector.begin();
citer != myvector.end(); ++citer)
{
cout << (*citer).m_iData << endl;
}
return 1;
}
关于c++ - 对包含类的 'std::vector' 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5468194/