簡體   English   中英

使用ostream_iterator和運算符<<顯示指針向量

[英]Using ostream_iterator and operator << to display a vector of pointers

我正在嘗試使用ostream_iteratoroperator <<在對象上顯示指針向量。 因此,我覆蓋了operator << 我總是得到向量元素地址的問題。 如何使迭代器打印實際值? 我需要專門化嗎?

class A {
private:
    double x;
    long y;
public:

    A(long xx, double yy) :x(xx), y(yy){};
    ~A();
    void Display();
};

template<typename T>
std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) {
    using namespace std;
    copy(v.begin(), v.end(), ostream_iterator<T>(os, "\n"));
    return os;
}

int main()
{
    std::vector<A*> aVect;
    FillA(aVect);
    cout << accountVect;

    return 0;
}
//
output
00657990
006579D0
00657A48

您可以為A*編寫operator<<重載,但是首先取消引用指針會更好一些,例如:

template<typename T>
std::ostream &operator <<(std::ostream &os, const std::vector<T *> &v) {
    std::transform(v.begin(), v.end(),
                   ostream_iterator<T>(os, "\n"),
                   [](T const *ptr) -> T const& { return *ptr; }
                  );
    return os;
}

然后為A編寫通常的operator<<重載。


注意-正如@WhozCraig在評論中提到的那樣,您現有的代碼沒有打印vector元素的地址 ,而是按您的要求打印vector元素,並且該元素地址。 如果可能的話,最簡單的解決方法是僅使用vector<A>

但是,我假設您需要保留vector<A*> <A *>並要打印取消引用的A對象。

另外,我堅持使用您的原始模板,但是還不清楚是否使用非模板operator<<(ostream&, vector<A*> const &)是否更干凈。

我對您的代碼進行了一些修改以使其正常工作:

#include <functional>

class A {
    public:
        A(){ x = 5; y = 5;}
        A(long xx, double yy) :x(xx), y(yy){};
        ~A();

        void Display() {
            std::cout << "X: " << x << " | Y: " << y << std::endl;
        }


        double x; // made this public just not to create an accessor
        long y;
};

template<typename T>
std::ostream &operator <<(std::ostream &os, const std::vector<T*> &v) {
    std::transform(v.begin(), v.end(), std::ostream_iterator<decltype(T::x)>(os, "\n"), [](const T* t){return t->x;});

    // or use A::Display() method with std::bind
    std::for_each(v.begin(), v.end(), std::bind(&A::Display, std::placeholders::_1));

    // or with std::mem_fn
    std::for_each(v.begin(), v.end(), std::mem_fn(&A::Display));
    return os;
}

int main()
{
    std::vector<A*> aVect = {new A, new A, new A};
    std::cout << aVect;

    return 0;
}

因此,第一個問題是您需要適當地專門化:

std::ostream &operator <<(std::ostream &os, const std::vector<T*> &v) {

代替

std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) {

這是因為您具有指針數組,但是當前的專長適用於vector的非指針對象。

接下來,我修改了您的std::copy調用,因為在您為A類提供operator<<重載之前,它將永遠無法工作。 因此,我將其更改為std::transform以便能夠輸出您的值。

UPD:同樣,這是一種將std::for_each算法與A::Display()方法一起使用的方法,該算法使用std::bindstd::mem_fn功能對象。

考慮到std::ostream_iterator本身使用operator<<作為輸出,您可以通過執行另一個重載輕松解決此問題:

std::ostream& operator<<(std::ostream& os, A const* a)
{
    // Some output of `a` here
    return os;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM