访问一组指针

Accessing a set of pointers

本文关键字:一组 指针 访问      更新时间:2023-10-16

下面是我的代码:

class obj140{
    public:
     int x; 
     explicit obj140(int y):x(y){   }
     bool operator<(const obj140& rhs) const{
          return x < rhs.x;
     }
};
int main() {
     obj140 * wtf = new obj140[5] {obj140(1),obj140(1),obj140(3),obj140(4),obj140(5)};
     std::set<obj140> orm(wtf,wtf+5);
}

这可能吗?比如把指针复制到集合?我没有错误,但我不知道如何访问它。

如何打印出orm集合的值?

我稍微修改了你的代码,使发生的事情更容易看到,并作为一个例子,一种方式来查看项目存储在set

class obj140
{
public:
    int x;
    explicit obj140(int y) :x(y)
    {
    }
    bool operator<(const obj140& rhs) const
    {
        return x < rhs.x;
    }
    void print() const
    {
        std::cout << x << std::endl;
    }
};
int main()
{
    obj140 * wtf = new obj140[5]
    { obj140(1), obj140(1), obj140(3), obj140(4), obj140(5) };
    std::set<obj140> orm(wtf, wtf + 5);
    for (auto it = orm.begin(); it != orm.end(); ++it)
    {
        it->print();
    }
    delete[] wtf; //edit. Forgot to clean up the pointer.
    return 0;
}
输出:

1
3
4
5

你正在做的工作和加载set。由于set s只存储唯一值(并对它们进行排序,如果需要的话,这可以进行非常快速的排序),因此丢弃了obj140(1)的第二次添加。