注册 登录
编程论坛 C++教室

请问一下vector 迭代器的用法

alfred_shi 发布于 2010-04-05 19:56, 1317 次点击
本人菜鸟一个,我的编程环境时VC++ Express 2008(免费的那个)。

我正在做c++ primer上的一道习题,其中要求输入输出vector。

我的代码如下
----------------------------------
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;

int main()
{
    vector<long> v1, v2;
    int i;
    int j;
    string yesno,verify;
    long long_verify;

    cout<<"Please enter your vector 1. Type END to finish."<<endl;

    for(i=0;;i++)  
    {
    A:;    
        cin>>verify;   
        //If type "end", finish the input.(可以输入任意数量的元素,直到输入end结束)   
        if((verify=="END")||(verify=="end")||(verify=="End"))
        {
            break;   
        }   
        //To verify if all the characters input are digital numbers.(这段代码用于检测是否输入的全部元素是数字,除非是end,否则如果不是就报错,要求重新输入。)
        for(j=0;j!=verify.size();j++)   
        {   
            if (!(isdigit(verify[j])))   
            {        
                cout<<"ERROR! You must enter an integral!"<<endl;   
                goto A;    
            }
        }

        //After then, give the value verified to vector.(检测完毕,确认全部是数字后才转成long型,输入到vector。因为我发现在VC++ Express下一旦输入个非数字给int或long就会立刻造成程序错乱。)
        long_verify = atol(verify.c_str());      //Transfer STRING to LONG
        v1.push_back(long_verify);         //Give value to vector 1
    }
    //(这段用于输出整个vector)
    cout<<"The veccor 1 is "<<endl;
    for(i=0;i!=v1.size();i++)
    {
        cout<<v1[i]<<" ";
    }
    cout<<"\n";
    return 0;
}
--------------------------------------


我想要的功能都实现了。但是,我有两个问题:

1 C++ Primer教材上说,如果可以的话,尽量使用迭代器。但我试过,一用迭代器后,可以编译,但运行后输入第一个数字元素后就出错。有谁能告诉我,这段程序改成迭代器的话应该怎么用?
2 这段程序我其中用了一个并不太受欢迎的goto(红色字标出来了),请问有没有替代方法?

谢谢

谢谢。


[ 本帖最后由 alfred_shi 于 2010-4-5 19:58 编辑 ]
1 回复
#2
yyblackyy2010-04-06 13:30
string yesno,verify; 这里的yesno 没有用到
vector<long> v1, v2;  v2 也没有用到

goto 给成continue;就可以了
vector<long>::iterator iter=v1.begin();
在输入的时候就用 v1 吧
输出时该成
for(;iter!=v1.end();iter++)           也就是简单了一点而已~~
    cout<<*iter;
1