7

我有一个指向类 A 的指针向量,我想使用 STL 按 int 键对其进行排序。为此,我operator <在 A 类中定义了一个

bool operator< (const A &lhs, const A &rhs){
    return (lhs.key < rhs.key);
};

在我的插入函数中,它看起来像

vector<A*>::iterator it = lower_bound(vec.begin(), vec.end(), element);
vec.insert(it, element);

我希望lower_bound返回可以放置新元素的第一个位置,但它不起作用。插入带有键 0,1,2,3 的 A 对象将导致向量的顺序不正确 (2,3,1,0)。这是为什么 ?

可能我也可以对这个对象使用比较器:

upper_bound / lower_bound 的比较函数

但我的代码有什么问题?

4

2 回答 2

6

从您的示例中,您正在使用指针向量:std::vector<A*>。因此,您需要为传入的指针定义一个比较std::lower_bound

bool less_A_pointer (const A* lhs, const A* rhs)
{
    return (lhs->key < rhs->key);
}

auto it = std::lower_bound(vec.begin(), vec.end(), element, less_A_pointer);
//...

当然,问题是你为什么首先使用指针——A除非你真的需要,否则只存储对象。如果您确实需要存储指针,请查看 std::shared_ptr哪个会为您处理:

std::vector<std::shared_ptr<A>> v;
std::shared_ptr<A> element(new A(...));
auto it = std::lower_bound(v.begin(), v.end(), element); //Will work properly

您也可以使用 lambda 而不必编写自由函数:

auto it = std::lower_bound(v.begin(), v.end(), 
                          [](const A* lhs, const A* rhs)
                          { return lhs->key < rhs->key; });
于 2013-05-06T09:12:17.270 回答
1

如果您真的想要 a std::vectorof 指针,您可能需要考虑使用智能指针,例如std::shared_ptr.
如果原始指针正在观察指针,则它们是可以的,但通常您不应该使用原始拥有 指针(除非在某些特殊情况下)。

您可以将 lambda 传递给std::lower_bound(), 以指定排序标准(在这种情况下,比较关键数据成员)。

此外,您可以只使用 C++11 的关键字,而不是显式编写std::vector<std::shared_ptr<A>>::iterator的返回值,这使得代码在这种情况下更具可读性。std::lower_bound()auto

下面是一个可编译的代码示例(使用 g++ 4.8.0 编译):

#include <algorithm>    // for std::lower_bound
#include <iostream>     // for console output
#include <memory>       // for std::make_shared, std::shared_ptr
#include <string>       // for std::string
#include <vector>       // for std::vector
using namespace std;

// Test data structure
struct A
{
    int Key;
    string Data;

    A()
        : Key(0)
    {}

    A(int key, const string& data)
        : Key(key), Data(data)
    {}
};

ostream& operator<<(ostream& os, const A& a)
{
    os << "(key=" << a.Key << ", data=\"" << a.Data << "\")";
    return os;
}

void Print(const vector<shared_ptr<A>> & v)
{
    cout << "[ ";
    for (const auto & p : v)
    {
        cout << *p << " ";
    }
    cout << " ]\n";
}

int main()
{
    // Test container
    vector<shared_ptr<A>> v;

    // Test data
    const char* data[] = {
        "hello",
        "world",
        "hi",
        nullptr
    };

    // Index in data array
    int i = 0;

    // Insertion loop
    while (data[i] != nullptr)
    {
        // Create new element on the heap
        auto elem = make_shared<A>(i, data[i]);

        // Find ordered insertion position
        auto it = lower_bound(v.begin(), v.end(), elem,
            [](const shared_ptr<A>& lhs, const shared_ptr<A>& rhs)
            {
                return lhs->Key < rhs->Key;
            }
        );

        // Insert in vector
        v.insert(it, elem);

        // Move to next data
        i++;
    }

    // Show the result
    Print(v);
}

这是输出:

[ (key=2, data="hi") (key=1, data="world") (key=0, data="hello")  ]
于 2013-05-06T10:52:41.097 回答