0

I am new to c++ and am trying to assign two variables within a vector, one being at the first index and the other at the (first index + 1).

Here is what I have so far:

#include <iostream>
#include <iterator>
#include <vector>

using std::cout, std::endl, std::vector;

int main() {
    vector<int> numList{25, 10, 4, 3, 1, 6};
    int var1;
    int var2;

    // Looping through vector
    for(auto it = numList.begin(); it != numList.end(); ++it) {
        int index = std::distance(numList.begin(), it);
        var1 = numList[index];
        var2 = numList[index + 1];
    }

    cout << "var1: " << var1 << " var2: " << var2 << endl;
}

I am expecting this to print out: var1: 25 var2: 10

The actual output is: var1: 6 var2: 0

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
TeemoMain
  • 105
  • 1
  • 1
  • 8
  • 8
    Why do you expect `var1: 25 var2: 10`? You loop until the end of the vector. – NathanOliver Sep 23 '19 at 15:19
  • 5
    `numList[index + 1];` is undefined behavior, when `index == numList.size () - 1`. – Algirdas Preidžius Sep 23 '19 at 15:19
  • 2
    `for (std::size_t index = 0; 1 + index < numList.size(); ++index)` is more tractable, and also fixes your bounds bug. – Bathsheba Sep 23 '19 at 15:19
  • 3
    Why convert iterators back to indices? `var1 = *it;` and `var2 = `*(it + 1);` would work. But still, you have an off-by-one problem mentioned above. – Yksisarvinen Sep 23 '19 at 15:21
  • There's also no `neighbor` declared anywhere in this code, yet according to you it's value is expected to be `10`. – WhozCraig Sep 23 '19 at 15:21
  • 3
    I think you have misunderstood the concept of how a loop works. Back to basics! :-) – super Sep 23 '19 at 15:22
  • 1
    If you just need first two indices, you don't need a loop at all, you can just have `val1 = numList[0]; val2 = numList[1];` – just that you should add a range check if you cannot guarantee the vector containing at least two elements. – Aconcagua Sep 23 '19 at 15:28
  • You might want to step through with a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems), that would shed some light on the matter for you... – Aconcagua Sep 23 '19 at 15:31
  • 2
    Put the iine `cout << "var1: " << var1 << " var2: " << var2 << endl;` inside the `for` loop to get a hint of what's happening. – Ted Lyngmo Sep 23 '19 at 15:39

2 Answers2

4

Your codes mostly are fine, your expectation is wrong.

Why do you expect var1: 6 var2: 0 ?

Also, I have changed two things on your codes.

  1. int var1 = 0, var2 = 0;

Get used to initialize values

  1. for (auto it = numList.begin(); it < numList.end() -1; ++it)

The original condition ( for(auto it = numList.begin(); it != numList.end(); ++it)) will throw Out-of-Bound error since it will try to access the index that is bigger than the vector size in the end.

It will not throw Out-Of-Bound error because operator[] is unchecked, but still it returns as undefined behavior. Thanks to @Ted Lyngmo.

Modify your condition to the code above I suggested to avoid the undefined behavior. If you are planning to use .at(), try-catch is suggested to prevent Out-Of-Range.

try{
        //... codes
}
catch(const std::out_of_range& e){
    cout << "Out of Range Thrown" << endl;
}

The revised codes

int main() {
    vector<int> numList{ 25, 10, 4, 3, 1, 6 };
    int var1 = 0, var2 = 0;

    // Looping through vector

    for (auto it = numList.begin(); it < numList.end() -1; ++it) {
        int index = std::distance(numList.begin(), it);
        var1 = numList.at(index);
        var2 = numList.at(index+1);

        cout << "var1: " << var1 << " var2: " << var2 << endl;
    }

    cout << "Final: var1: " << var1 << " var2: " << var2 << endl;
}

I've added your cout code inside of the loop, so you can see what happens during loops.

And the output is

The Result

JM C
  • 68
  • 4
0

Firstly, you print now values after the end of the loop, so it should print the last two variables in vector. Secondly, end() from vector return iterator to n+1 position in vector. If the vector size is n, the iterator goes beyond vector - it results in this case var2 == 0. You should iterate through vector with it != (numList.end()-1) condition in for loop.

Piotr
  • 55
  • 8
  • 2
    It results in undefined behaviour, receiving `var2 == 0` is just pure accident. The programme might as well have printed some arbitrary garbage value instead or even crashed. – Aconcagua Sep 23 '19 at 15:38
  • 1
    @Aconcagua Exactly. For me this is optimized into a direct crash without output :-) – Ted Lyngmo Sep 23 '19 at 15:40