【问题标题】:For exC++ inserting into a list the object being pointed to by an iterator对于 exC++ 将迭代器指向的对象插入到列表中
【发布时间】:2015-10-05 21:09:53
【问题描述】:

假设您有一个迭代器指向列表中的一个对象,并且您想编写一个函数,将迭代器指向的任何对象复制到另一个指定的列表中。这可能吗?

例如

 std::list<Customer> customer;
 for (customer=customers.begin(); customer!=customers.end(); ++customer){
     std::list<Inventory>::iterator tool;
     for (tool=inventory.begin(); tool!=inventory.end(); ++tool){
          tool->addToWaitlist( customer );
      }
 }

在哪里

 void addToWaitlist(std::list<Customer>::iterator customer){ 
            std::list<Customer>::iterator person;
            if (!wait_list.empty()){
                    for (person=wait_list.begin(); person!=wait_list.end(); ++person){
                            // Add customer with respect to time stamp
                            //if ( customer.getTime() <= person->getTime() ){
                            //      wait_list.insert( person, customer );
                            }
                    }
            } else {
                    // Add first person to wait list
                    wait_list.push_back( customer );
            }
    }

【问题讨论】:

  • 是的。请出示您的代码。
  • “这可能吗?” 是的,有可能。你这样做有没有遇到什么特别的问题?请逐字显示相关的问题代码和所有错误消息。

标签: c++ list iterator


【解决方案1】:

这很简单:

// given some T and the following lists
list<T> l1, l2;
list<T>::iterator objit=l1.begin();    // picked the first item in l1 since it's easy

// copy the item to l2
l2.push_back(*objit);

【讨论】:

  • 在处理指针列表时并不那么直接。
  • 如果你这么说。结果是一样的。而且 OP 中没有人提到指针,所以我不确定你到底是什么意思。
  • 不一样。如果您有一个指针列表,那么直接指针副本只会采用浅拷贝,因此您最终会拥有两个指向同一个对象的指针,而不是采用深拷贝。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 2014-04-29
  • 1970-01-01
相关资源
最近更新 更多