2014-12-01 66 views
-3

我有打印列表的功能。但是,我傳遞了一個指向該列表的指針,下面的打印列表代碼不起作用;也就是說,如果它沒有被指向,那麼將打印一個列表的代碼。使用指向該列表的指針打印列表

print(std::string svar, std::list<person> *persons){ 
    for (std::list<person>::iterator it = persons.begin(); it != persons.end(); it++) { 
     std::cout << *it << " "; 
    } 
} 

我不知道如何將其改爲persons是一個指針。

+1

您需要取消引用您的指針:'persons-> begin()'等。 – 5gon12eder 2014-12-01 17:14:12

回答

1

幾種方法來解決它。

  1. 將參數的參數從指針更改爲參考。

    void print(std::string svar, std::list<person> const& persons){ 
        for (std::list<person>::const_iterator it = persons.begin(); it != persons.end(); it++) { 
         std::cout << *it << " "; 
        } 
    } 
    
  2. 改變你使用指針的方式。

    void print(std::string svar, std::list<person>* persons){ 
        for (std::list<person>::iterator it = persons->begin(); it != persons->end(); it++) { 
         std::cout << *it << " "; 
        } 
    } 
    

我會建議使用第一個選項。

1

在你的例子中persons是一個指向列表的指針,而不是列表本身。使用->運營商取消對它的引用:

void print (std::string, std::list<person> *persons) 
{ 
    for (std::list<person>::iterator it = persons->begin(); it != persons->end(); it++) 
    { 
     std::cout << *it << " "; 
    } 
} 

或者更好的是,把它作爲參考,使用基於for循環的範圍(假設C++ 11):

void print (const std::list<person>& persons) 
{ 
    for (auto&& person : persons) 
    { 
    std::cout << person << " "; 
    } 
} 

你可能會考慮命名指針變量不同,例如:person* pPerson

1

慣用的方式來傳遞一個對象而不復制它是使用一個參考,不是指針:

print(std::string const & svar, std::list<person> const & persons); 

您可以通過參考恰好訪問list的成員,你會與list對象本身,因此,如果您修復常量,正確性的代碼應工作:

for (std::list<person>::const_iterator it = persons.begin(); ... 
         ^^^^^^ 

它,因爲C++ 11,可以更方便地進行:

for (auto it = persons.begin(); ... 

for (person const & p : persons) { 
    std::cout << p << " "; 
} 

如果你真的想出於某種原因指針渣土約,然後使用list成員->而不是.

for (auto it = persons->begin(); it != persons->end(); ++it) 
         ^^ 

你也應該確保它的訪問不是第一個,因爲這樣的函數邀請人們傳遞空指針。