Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;循环内部变量的引用与指针?_C++_For Loop_Iterator_Reference - Fatal编程技术网

C++ C++;循环内部变量的引用与指针?

C++ C++;循环内部变量的引用与指针?,c++,for-loop,iterator,reference,C++,For Loop,Iterator,Reference,我可以为c(例如,Customer&c)使用参考变量吗?如果是,怎么做?这比使用指针变量更可取吗 for(std::vector<Customer*>::const_iterator it = customers_.begin(); it != customers_.end() ; it ++) { Customer *c = (*it); c->PrintName(); ... } fo

我可以为
c
(例如,
Customer&c
)使用参考变量吗?如果是,怎么做?这比使用指针变量更可取吗

    for(std::vector<Customer*>::const_iterator it = customers_.begin();
        it != customers_.end() ; it ++)
    {
        Customer *c = (*it);
        c->PrintName();
        ...
    }
for(std::vector::const_iterator it=customers_uu.begin();
it!=客户u.end();it++)
{
客户*c=(*it);
c->PrintName();
...
}
是:

for(std::vector::const_iterator it=customers_uu.begin();
it!=客户u.end();it++)
{
客户与成本=*(*it);
c、 PrintName();
...
}
(括号不是必需的,但可能会更清楚。)

您可以:

for(std::vector<Customer*>::const_iterator it = customers_.begin();
    it != customers_.end() ; it ++)
{
    Customer const &c = **it;
    c.PrintName();
    ...
}

为什么不直接使用迭代器呢?它->PrintName()@Ferruccio:因为迭代器引用的是指针,而不是对象。您必须执行
(*it)->
请注意,虽然指针可以处于无效或空状态(即它们是空指针),但引用不能。当然,情况似乎并非如此,因为您也没有在自己的代码中执行任何检查,但指向指针的向量实际上并没有传递对其内容的承诺。如果它是一个对象的向量,你可以确定它们都是有效的对象。它应该是
const Customer&c
,我认为,因为
它是
const\u迭代器
@OliCharlesworth:不,它是
指针对象
,它是常量。另外,想想如果
客户
常量向量&
+1的话会怎么样。我已经阅读了我的大部分代码,并从引用语义转换为值语义。我正在查看的特定代码我不确定这是否可行,但我会记住它。也开始学习算法的使用,尽管它们是否有助于或损害可读性并不总是很明显。@用户:在C++03中,这经常是有争议的(尤其是从
for_each
调用成员函数与使用显式循环)。在C++11中,我很少看到算法运行得不好的情况(我怀疑一旦我了解了lambdas和其他更好的算法,即使很少有人坚持会消失)。您添加到引用变量中的
const
是否使调用Customer的非const方法变得不可能?如果是这样,这与我的原始代码不同,尽管我可以在其他循环中使用这一事实。
for(std::vector<Customer*>::const_iterator it = customers_.begin();
    it != customers_.end() ; it ++)
{
    Customer const &c = **it;
    c.PrintName();
    ...
}
std::copy(customers_.begin(), customers.end(), 
          std::ostream_iterator<Customer>(std::cout, "\n"));