简体   繁体   English

在C ++中是否有“循环遍历”数组的最佳实践?

[英]Is there a best-practice for looping “all the way through” an array in C++?

In Python, one can compare each element of an array with the "next" element (including the last element with the first element) with the following code: 在Python中,可以使用以下代码将数组的每个元素与“ next”元素(包括最后一个元素与第一个元素)进行比较:

a = [0, 1, 2, 3]
for i in range(-1, 3):
    if a[i] + 1 >= a[i+1]:    
        print a[i], 'works'

The output: 输出:

3 works
0 works
1 works
2 works

If I want to compare the first element of an array with the second, the second with the third, etc., and finally the last with the first , I can do so with just a loop in Python. 如果我想将数组的第一个元素与第二个,第二个与第三个进行比较,等等, 最后一个与第一个进行比较 ,则可以使用Python中的一个循环进行比较。

Can I do this in C++? 我可以用C ++做到吗? Can I loop though elements in this manner whilst staying entirely in one loop? 我可以以这种方式遍历元素,同时完全停留在一个循环中吗? To further illustrate what I mean, here is some C++ code that has the same functionality as the above Python code. 为了进一步说明我的意思,这是一些具有与上述Python代码相同功能的C ++代码。

int a[] = {0, 1, 2, 3};
std::cout a[3] << std::endl;
for(int i = 0; i < 2; i++)
    std::cout << a[i] << std::endl;

It has the same output. 它具有相同的输出。 My point is, for certain algorithms, I'd have to manually duplicate the contents of my for loops for certain steps. 我的观点是,对于某些算法,对于某些步骤,我必须手动复制for循环的内容。 For example, if I want to see if the first element equals the second, the second the third, etc., and finally if the last equals the first, I'd have to manually add this step after or before my for loop. 例如,如果我想查看第一个元素是否等于第二个元素,第二个元素等于第三个元素,等等,最后如果最后一个元素等于第一个元素,则必须在for循环之后或之前手动添加此步骤。 --- if (a[0] == a[3]) foo(); --- if (a[0] == a[3]) foo();

Is this what I am supposed to do in C++? 这是我应该在C ++中执行的操作吗? I am quite new to it and I don't want to get rooted in bad practices. 我对此很陌生,我不想扎根于不良做法。

for (int i=3; i<(3 + size_of_array); ++i)
    std::cout << a[i % size_of_array] << '\n';

Use std::begin() and std::end() algorithm. 使用std::begin()std::end()算法。

int a[3]={1,2,3};
for( auto x=end(a)-1; x>=begin(a); --x){
    cout<<*x<<endl;
}

The above code outputs 3 2 1 , the revrese order of the array a . 上面的代码输出3 2 1 ,即数组a的转写顺序。 Have a look at [begin()][1] . 看看[begin()][1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM