简体   繁体   English

如何访问 C++ 中的链表中的对象

[英]How do I access objects in a linked-list in C++

I'm very use to working with arrays and vectors, but now I'm playing with some STD::lists, as well as a custom list class I made.我非常习惯使用 arrays 和向量,但现在我正在使用一些 STD::lists,以及我制作的自定义列表 class。

Let's say I have a simple class, Stock.假设我有一个简单的 class,库存。

//stock.h
class Stock{
public:
    Stock(); //default constructor
    Stock(string, double); //overloaded constructor
    void setSymbol(string); //sets stock symbol
    void setPrice(double);
    string getSymbol();
    double getPrice();        
private:
    string symbol;
    double price;
};

Now in a separate file I have my int main to test.现在在一个单独的文件中,我有我的 int main 来测试。

#include "stock.h"
#include <list>

int main(){
    list<Stock> portfolio;

    Stock Google("GOOG", 500);
    Stock Apple("APPL", 300);
    Stock Chipotle("CMG", 200);

    portfolio.push_back(Google);
    portfolio.push_back(Apple);
    portfolio.push_back(Chipotle);
}

Now if this was a vector or array, I would have no problem, I'm just completely loss on the linked-list equivalent of the following:现在,如果这是一个向量或数组,我不会有任何问题,我只是完全失去了以下等价的链表:

for(int i=0; i <portfolio.size(); i++){
    portfolio[i].getSymbol();
    portfolio[i].getPrice();
 }

Or something along those lines...I have no lecture/training in Linked-Lists so I'm really trying to do my best in teaching myself--but I'm stuck on basic manipulation.或者类似的东西......我没有在链接列表方面进行讲座/培训,所以我真的在尽力自学 - 但我坚持基本操作。 I'm using STL::list right now, but really trying to make my own class as well.我现在正在使用 STL::list,但我也确实在尝试制作自己的 class。

for(int i= portfolio.begin(); i <portfolio.size(); i++)

If this worked for a std::vector, it was only by sheer accident.如果这适用于 std::vector,那纯属偶然。 I have no idea how that might have worked for a vector.我不知道这可能对向量起作用。

std::any_stl_container::begin() returns an object called an "iterator". std::any_stl_container::begin()返回一个称为“迭代器”的 object。 Specifically, an object of type std::any_stl_container::iterator .具体来说,一个类型为std::any_stl_container::iterator的 object 。 An iterator is kind of like a generalized pointer: it refers to an element in an STL container.迭代器有点像通用指针:它引用 STL 容器中的元素。

The iterator returned by begin is the iterator that references the first element in the list. begin返回的迭代器是引用列表中第一个元素的迭代器。 You can move iterators around like pointers.您可以像指针一样移动迭代器。 For example:例如:

std::list<Stock> portfolio;
...
std::list<Stock>::iterator currElem = portfolio.begin();
++currElem; //Now points to the second element in the list.
Stock &secondStock = *currElem;

In order to iterate over all of the elements in a list, you need two iterators: the first one, and the iterator for the element after the last element in the list.为了迭代列表中的所有元素,您需要两个迭代器:第一个迭代器和列表中最后一个元素之后的元素的迭代器。 Fortunately, this is returned by the std::any_stl_container::end() function.幸运的是,这是由std::any_stl_container::end() function 返回的。 So, your loop should look like:因此,您的循环应如下所示:

typedef std::list<Stock>::iterator StockIt;
for(StockIt i = portfolio.begin(); i != portfolio.end(); ++i) /* Prefer pre-increment with iterators */
{
    i->getSymbol();
    i->getPrice();
}

This will work for any of the usual STL containers.这适用于任何常用的 STL 容器。

You have iterators as begin() and end() for std::list also:您还有迭代器作为std::listbegin()end()

for (list<stock>::iterator it = portfolio.begin() ; it != portfolio.end(); it++)
{
  // use 'it' to access the current element (i.e. *it)
}

You have to use iterators .你必须使用迭代器 Every STL container has them, even vector.每个 STL 容器都有它们,甚至是向量。 They behave similarly to pointers;它们的行为类似于指针; they can be dereferenced with * or ->, they can be incremented, they can be compared.它们可以用 * 或 -> 取消引用,它们可以递增,可以进行比较。

for( list<Stock>::iterator it = portfolio.begin(); it != portfolio.end(); it++ ){
    it->getSymbol();
    it->getPrice();
}

An object of type std::list is very inefficient if you try to compute its length, because such an operation would have linear time.如果您尝试计算其长度,则std::list类型的 object 效率非常低,因为这样的操作将具有线性时间。

Therefore with lists, you cannot compare iterators with the < and > operators.因此,对于列表,您无法将迭代器与<>运算符进行比较。 It is also ill-advised to try to get the nth element with the operator [] .尝试使用运算符[]获取第 n 个元素也是不明智的。

Also, you should not mix begin() and size() which are respectively an iterator and an integer.此外,您不应将分别作为迭代器和 integer 的begin()size()混合使用。

The proper way to iterate over an std::list is to use the pair of iterators begin() and end() and to increment your iterator until it reaches the end() .迭代std::list的正确方法是使用一对迭代器begin()end()并递增迭代器直到它到达end()

So, two ways:所以,有两种方法:

for(std::list<stock>::const_iterator i = my_list.cbegin(); i != my_list.cend(); ++i)
{
    // access a “const stock &” object via *i
}

or或者

for(std.:list<stock>::iterator i = my_list.begin(); i != my_list.end(); ++i)
{
    // access a “stock &” object via *i
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM