简体   繁体   English

C ++向量阵列/ WhileLoop

[英]C++ Vector Array / WhileLoop

I am reading C++ Programming In Easy Steps 4th and have read in to something I am having trouble understanding. 我正在阅读Easy Steps 4th中的C ++编程,并阅读了一些我难以理解的内容。 I've only just started reading it the other day. 前几天我才刚刚开始阅读。

I had a particularly hard time getting my head around vector arrays and elements when I done that section of the book, I still don't feel confident about it despite taking a bunch of time to try and understand them, so I plan to re-visit that again. 当我完成本书的那一部分时,我特别难以理解向量数组和元素,尽管花了很多时间尝试并理解它们,但我仍然对此并不充满信心,因此我打算重新再次访问。 I'm now on a later part of the book however which is demonstrating loops and here is the code that I am having trouble with (Just one line): 我现在在这本书的下一部分,但是它演示了循环,这是我遇到麻烦的代码(仅一行):

#include <iostream>
#include <vector>       // Include vector support (Vector function library)
using namespace std;

int main()
{


    //Declaring an integer vector and an integer variable for loop counter
    vector <int> vec ( 10 );
    int i = 0;


    //Now inserting a while loop to assign a counter value to an element of the vector on each iteration
    while ( i < vec.size() )
    {
        i++;                 //Increment the counter
        vec[ i -1 ] = i;     // Assign count to element

        cout << " | " << vec.at ( i -1 );
    }


    return 0;
}

I understand everything, but this line: 我了解所有内容,但以下内容:

        vec[ i -1 ] = i;     // Assign count to element

I'm not sure what this is doing exactly particularly the i -1 part? 我不确定这到底在做什么,特别是i -1部分? Can someone break this down for me in an easy to understand way? 有人可以用一种容易理解的方式为我分解吗? I'm going to quickly re-visit the section on vector arrays and see if I can get an understanding. 我将快速重新访问向量数组部分,以了解是否可以理解。

Vector indicies start at 0 . 向量索引从0开始。 A vector of 10 elements is indexed from 0 to 9 . 10个元素的向量从09索引。 Assuming your goal is to load the array consecutively with the numbers 1 to 10 , and since you start i at 0 and increment it before using it in the index expression, you need to subtract 1 from it to get the proper index. 假设您的目标是使用数字110连续加载数组,并且由于i0开始并在索引表达式中使用它之前将其递增,因此需要从中减去1以获得正确的索引。

This piece of code does the same thing. 这段代码做同样的事情。

vector<int> vec(10);

int i = 0;
while (i < vec.size())
{
    vec[i] = i + 1;
    i++;
}

i = 0;
while (i < vec.size())
{
    cout << i << ": " << vec.at(i) << endl;
    i++;
}

It may help you if you break the code down to what the while loop is actually accomplishing by individual statements (you would see similar if you were running through the while loop with a debugger and also adding watch statements such as i-1): 如果您通过单独的语句将代码分解为while循环实际完成的工作,则可能会有所帮助(如果您使用调试器运行while循环并添加watch语句(例如i-1),将会看到类似的结果):

#include <iostream>
#include <vector>       // Include vector support (Vector function library)
using namespace std;

int main()
{


    //Declaring an integer vector and an integer variable for loop counter
    vector <int> vec ( 10 ); // vector of 10 elements: 0...9
    int i = 0; // i starts with the value of 0

    // replace while loop with the individual statements the loop accomplishes
    // note also that vec.size() = 10
    // while (i < vec.size())

    // increment i to 1 (started as 0, from above)
    i++;                 //Increment the counter
    vec[ 0 ] = i;     // i - 1 = 0 here - Assign count to element
    cout << " | " << vec.at ( 0 );
    // increment i to 2
    i++;                 //Increment the counter
    vec[ 1 ] = i;     // i - 1 = 1 here - Assign count to element
    cout << " | " << vec.at ( 1 );

    // continue to i = 9 ...

    // increment i to 10
    i++;                 //Increment the counter
    vec[ 9 ] = i;     // i - 1 = 9 here - Assign count to element
    cout << " | " << vec.at ( 9 );    
    return 0;
}

you're assigning the numbers 1 to 1o to your vector. 您正在为向量分配1到1o的数字。

vec[i-1] = i

follows directly after i++ which means,for your first index you're assigning a value a count/step more than index. i++之后紧随其后,这意味着,对于您的第一个索引,您分配的值比索引要多。 Put simply,let's follow the first 4 values of i and the elements inserted into the vector: 简而言之,让我们跟随i的前四个值和插入向量中的元素:

i = 0;
i = 1;here vec[ 1 - 1] = vec[0] = 1
i = 2;here vec [2 - 1] = vec[1] = 2
i = 3;and finally vec[ 2 ] = 3

Vectors are wrapper classes for arrays (Source: Link to C++ reference ) that also do some really cool things like use templates for allocators, provide dynamic space, and use stl iterators. 向量是数组的包装类(来源: C ++参考的链接 ),它们也做一些非常酷的事情,例如为分配器使用模板,提供动态空间以及使用stl迭代器。

So, vectors can be accessed like arrays using the [ ] operator. 因此,可以使用[]运算符像数组一样访问向量。 The two code snippets are identical: 这两个代码段是相同的:

First, the array form: 一,数组形式:

//Allocate and assign array

int* arr[5]={1,2,3,4,5};

//Print the 3rd element, note that the first index corresponds to 0.

std::cout<< arr[2] <<std::endl;

//Reassign the 2nd element:

arr[1]=54;

Now the vector version: 现在是矢量版本:

//Allocate and assign vector

std::vector<int> arr( {1,2,3,4,5} );

//Print the 3rd element, note that the first index corresponds to 0.

std::cout<< arr[2] <<std::endl;

//Reassign the 2nd element:

arr[1]=54;

A tip for the wise: Accessing vectors like this can be dangerous since the size of an array can be changed elsewhere in code. 明智的提示:像这样访问向量可能很危险,因为数组的大小可以在代码的其他地方更改。 Instead consider the following for assignment: 而是考虑以下分配:

std::vector<int> arr( {1,2,3,4,5} );
int index=0;
for(std::vector<int>::iterator it = arr.begin(); it!= arr.end(); ++it){
    if(index++ == 3){
        (*it) = 54;
    }
}

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

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