c++ - 使用模板函数和迭代器显示vector中的元素

查看:337
本文介绍了c++ - 使用模板函数和迭代器显示vector中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

template<typename T>
void factorial(vector<T> ivec, vector<T>::iterator iter) {
    while (iter != ivec.end()) {
        cout << *iter << endl;
        ++iter;
    }
}

int main() {

    vector<int> ivec = { 1,2,3,4,5,6,7 };
    factorial(ivec, ivec.begin());

    return 0;
}

在VS 2017中他的报错信息如下:

警告    C4346    std::vector<T,std::allocator<_Ty>>::iterator: 依赖名称不是类型    practice_needForCpp11    d:\practice_needforcpp11\practice_needforcpp11\源.cpp    8    
错误    C2061    语法错误: 标识符iterator    practice_needForCpp11    d:\practice_needforcpp11\practice_needforcpp11\源.cpp    8    
错误    C2672    factorial: 未找到匹配的重载函数    practice_needForCpp11    d:\practice_needforcpp11\practice_needforcpp11\源.cpp    18    
错误    C2780    void factorial(std::vector<T,std::allocator<_Ty>>): 应输入 1 个参数,却提供了 2 个    practice_needForCpp11    d:\practice_needforcpp11\practice_needforcpp11\源.cpp    18    

请教各位一下这里出了什么问题~谢谢了~~

解决方案

在Vs2008上运行,会报错。
错误的原因有:
(1)vector<int> ivec = { 1,2,3,4,5,6,7 }; vector不能直接这样初始化赋值。可以用这样来替换

vector<int> ivec;
    for(int i=1;i<8;i++){
        ivec.push_back(i);
    }

(2)函数写的很不好,直接用这样写就行了,根本没必要传ivec.begin()给函数。因为你已经传了ivec给函数,函数就会得到ivec的所有信息,不必画蛇添足。

#include "iostream"
#include <vector>
using namespace std;
void factorial(vector<int> ivec) {
    vector<int>::iterator it;
    for(it=ivec.begin();it!=ivec.end();it++)
    cout<<*it<<endl;
}

int main()
{
    vector<int> ivec;
    for(int i=1;i<8;i++){
        ivec.push_back(i);
    }
    factorial(ivec);

    return 0;
}

如果你非要画蛇添足的做法,可以这样写,至于为什么要加个&符号,是因为不引用的的话就会新建个vector,那么新建的vector里面是没有数据的,所以就肯定错了。

#include "iostream"
#include <vector>
using namespace std;
void factorial(vector<int> &ivec,vector<int>::iterator iter) {
    vector<int>::iterator it;
    for(it=iter;it!=ivec.end();it++)
    cout<<*it<<endl;
}

int main()
{
    vector<int> ivec;
    for(int i=1;i<8;i++){
        ivec.push_back(i);
    }
    factorial(ivec,ivec.begin());
    
    return 0;
}

这篇关于c++ - 使用模板函数和迭代器显示vector中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆