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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2395275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:19:37  来源:igfitidea点击:

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

c++iteratorvector

提问by kevin

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 through containers, but I've never used iterators before, and what I'm reading is confusing.

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

If anyone could give me some information on how to achieve this, I would appreciate it. Thank you.

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

回答by codaddict

You need to make use of the beginand endmethod of the vectorclass, which return the iterator referring to the first and the last element respectively.

您需要使用该类的beginandend方法vector,它分别返回引用第一个和最后一个元素的迭代器。

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.

回答by Michael Aaron Safyan

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[].

通常,迭代器用于以线性方式访问容器的元素;但是,使用“随机访问迭代器”,可以以与operator[].

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

访问 vector 中的任意元素vec,您可以使用以下命令:

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++):

以下是典型访问模式的示例(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_eachand lambdas:

使用std::for_each和 lambdas 的另一种选择:

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

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

从 C++11 开始,您可以使用auto来避免指定非常长、复杂的迭代器类型名称,如之前所见(甚至更复杂):

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

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

此外,还有一个更简单的 for-each 变体:

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

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

最后,std::accumulate无论是添加整数还是浮点数,您都必须小心。

回答by lashgar

In C++-11 you can do:

在 C++-11 中,您可以执行以下操作:

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

请参阅此处了解变化:https: //en.cppreference.com/w/cpp/language/range-for

回答by UncleBens

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

Vector 的迭代器是随机访问迭代器,这意味着它们的外观和感觉就像普通指针。

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

您可以通过将 n 添加到从容器的begin()方法返回的迭代器中来访问第 n 个元素,或者您可以使用 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 advancefunction 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;

回答by hmofrad

Here is an example of accessing the ithindex of a std::vectorusing an std::iteratorwithin a loop which does not require incrementing two iterators.

下面是一个在不需要递增两个迭代器的循环中使用 an访问itha 索引的示例。std::vectorstd::iterator

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

没有 for 循环

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

and using atmethod:

和使用at方法:

printf("Using at position: strs[%d] = %s\n", nth, strs.at(nth).c_str());