How to navigate through a vector using iterators? (C++)

前端 未结 5 1320
太阳男子
太阳男子 2020-11-29 16:27

The goal is to access the \"nth\" element of a vector of strings instead of the [] operator or the \"at\" method. From what I understand, iterators can be used to navigate t

5条回答
  •  清歌不尽
    2020-11-29 16:58

    You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively.

    using namespace std;  
    
    vector myvector;  // a vector of stings.
    
    
    // push some strings in the vector.
    myvector.push_back("a");
    myvector.push_back("b");
    myvector.push_back("c");
    myvector.push_back("d");
    
    
    vector::iterator it;  // declare an iterator to a vector of strings
    int n = 3;  // nth element to be found.
    int i = 0;  // counter.
    
    // now start at from the beginning
    // and keep iterating over the element till you find
    // nth element...or reach the end of vector.
    for(it = myvector.begin(); it != myvector.end(); it++,i++ )    {
        // found nth element..print and break.
        if(i == n) {
            cout<< *it << endl;  // prints d.
            break;
        }
    }
    
    // other easier ways of doing the same.
    // using operator[]
    cout<

提交回复
热议问题