如何使用迭代器在向量中导航?(C++)

目标是访问字符串向量的第 n 个"元素,而不是使用 [] 运算符或at"方法.据我了解,迭代器可用于在容器中导航,但我以前从未使用过迭代器,而且我正在阅读的内容令人困惑.

如果有人能给我一些有关如何实现这一目标的信息,我将不胜感激.谢谢.

liu0659222 回答:如何使用迭代器在向量中导航?(C++)

你需要使用 begin<vectorend方法> 类,它返回分别引用第一个和最后一个元素的迭代器.

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.

这篇关于如何使用迭代器在向量中导航?(C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持前端之家!

本文链接:https://www.f2er.com/3186422.html

大家都在问