学习vector遍历方法

假设有这样的一个vector:(注意,这种列表初始化的方法是c++11中新增语法)
vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
需要输出这个vector中的每个元素,测试原型如下:
void ShowVec(const vector<int>& valList)
{
}
int main(int argc, char* argv[])
{
    vector<int> valList = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    ShowVec(valList);
    return 0;
}
方法零,对C念念不舍的童鞋们习惯的写法:
void ShowVec(const vector<int>& valList)
{
    int count = valList.size();
    for (int i = 0; i < count;i++)
    {
        cout << valList[i] << endl;
    }
}
或者
void ShowVec(const vector<int>& valList)
{
    int count = valList.size();
    for (int i = 0; i < count;i++)
    {
        cout << valList.at(i) << endl;
    }
}
方法一,大家喜闻乐见的for循环迭代器输出
void ShowVec(const vector<int>& valList)
{
    for (vector<int>::const_iterator iter = valList.begin(); iter != valList.end(); ++iter)
    {
        cout << (*iter) << endl;
    }
}
或者使用c++新增的语义auto,与上面差不多,不过能少打几个字:
void ShowVec(const vector<int>& valList)
{
    for (auto iter = valList.cbegin(); iter != valList.cend(); iter++)
    {
        cout << (*iter) << endl;
    }
}
方法二,for_each加函数:
template<typename T>
void printer(const T& val)
{
    cout << val << endl;
}
void ShowVec(const vector<int>& valList)
{
    for_each(valList.cbegin(), valList.cend(), printer<int>);
}
方法三,for_each加仿函数:
template<typename T>
struct functor
{
    void operator()(const T& obj)
    {
        cout << obj << endl;
    }
};
void ShowVec(const vector<int>& valList)
{
    for_each(valList.cbegin(), valList.cend(), functor<int>());
}
方法四,for_each加Lambda函数:(注意:lambda为c++11中新增的语义,实则是一个匿名函数)
void ShowVec(const vector<int>& valList)
{
    for_each(valList.cbegin(), valList.cend(), [](const int& val)->void{cout << val << endl; });
}
方法五,for区间遍历:(注意,for区间遍历是c++11新增的语法,用于迭代遍历数据列表)
for (auto val : valList)
{
    cout << val << endl;

}

转自:http://www.cnblogs.com/xylc/p/3653036.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值