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

前端 未结 5 1301
太阳男子
太阳男子 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:46

    Vector's iterators are random access iterators which means they look and feel like plain pointers.

    You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [].

    std::vector<int> vec(10);
    std::vector<int>::iterator it = vec.begin();
    
    int sixth = *(it + 5);
    int third = *(2 + it);
    int second = it[1];
    

    Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)

    std::vector<int> vec(10);
    std::vector<int>::iterator it = vec.begin();
    
    std::advance(it, 5);
    int sixth = *it;
    
    0 讨论(0)
  • 2020-11-29 16:51

    Here is an example of accessing the ith index of a std::vector using an std::iterator within a loop which does not require incrementing two iterators.

    std::vector<std::string> strs = {"sigma" "alpha", "beta", "rho", "nova"};
    int nth = 2;
    std::vector<std::string>::iterator it;
    for(it = strs.begin(); it != strs.end(); it++) {
        int ith = it - strs.begin();
        if(ith == nth) {
            printf("Iterator within  a for-loop: strs[%d] = %s\n", ith, (*it).c_str());
        }
    }
    

    Without a for-loop

    it = strs.begin() + nth;
    printf("Iterator without a for-loop: strs[%d] = %s\n", nth, (*it).c_str());
    

    and using at method:

    printf("Using at position: strs[%d] = %s\n", nth, strs.at(nth).c_str());
    
    0 讨论(0)
  • 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<string> 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<string>::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<<myvector[n]<<endl;  // prints d.
    
    // using the at method
    cout << myvector.at(n) << endl;  // prints d.
    
    0 讨论(0)
  • 2020-11-29 17:00

    In C++-11 you can do:

    std::vector<int> v = {0, 1, 2, 3, 4, 5};
    for (auto i : v)
    {
       // access by value, the type of i is int
       std::cout << i << ' ';
    }
    std::cout << '\n';
    

    See here for variations: https://en.cppreference.com/w/cpp/language/range-for

    0 讨论(0)
  • 2020-11-29 17:06

    Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[].

    To access arbitrary elements in a vector vec, you can use the following:

    vec.begin()                  // 1st
    vec.begin()+1                // 2nd
    // ...
    vec.begin()+(i-1)            // ith
    // ...
    vec.begin()+(vec.size()-1)   // last
    

    The following is an example of a typical access pattern (earlier versions of C++):

    int sum = 0;
    using Iter = std::vector<int>::const_iterator;
    for (Iter it = vec.begin(); it!=vec.end(); ++it) {
        sum += *it;
    }
    

    The advantage of using iterator is that you can apply the same pattern with other containers:

    sum = 0;
    for (Iter it = lst.begin(); it!=lst.end(); ++it) {
        sum += *it;
    }
    

    For this reason, it is really easy to create template code that will work the same regardless of the container type. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).

    Another option using std::for_each and lambdas:

    sum = 0;
    std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });
    

    Since C++11 you can use auto to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):

    sum = 0;
    for (auto it = vec.begin(); it!=vec.end(); ++it) {
        sum += *it;
    }
    

    And, in addition, there is a simpler for-each variant:

    sum = 0;
    for (auto value : vec) {
        sum += value;
    }
    

    And finally there is also std::accumulate where you have to be careful whether you are adding integer or floating point numbers.

    0 讨论(0)
提交回复
热议问题