-2

I want to create auto iteration loop like this:

std::vector<sometype> vector1;
for(auto it : vector1)
{
   if(&it == &vector1.at(4))
      //do something...
   else
      continue;
}

but I found out that adress of "it" when it's equal to vector1.at(4) is not the same as adress of vector1.at(4). How can I do for loop which would assign to "it" not value but adress of value currently pointing to.

Daniel Klimek
  • 77
  • 1
  • 7
  • 2
    The answer below explains *how* to do this, but may I ask *why* you want to do this? e.g. in this particular case, you could just `// ... do something` with `vector.at(4)` directly. – cigien Oct 09 '20 at 16:08

3 Answers3

2

You can use reference (add & to variable declarations) to do something like that.

std::vector<sometype> vector1;
for(auto& it : vector1) // add &
{
   if(&it == &vector1.at(4))
      //do something...
   else
      continue;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

Looking at your code as pseudo-code for an algorithm, it basically attempts to solve

  1. Check (via O(n) instead of O(1) cost) if the vector has at least 5 elements.
    • If true, go to 2.
    • Otherwise do nothing.
  2. Do something with the 5th element.

If this is indeed the case, you don't actually need a for loop for this, you could just query the size of the vector prior to conditionally accessing (O(1) random access) the 5th element to //do something...:

#include <iostream>
#include <string>
#include <vector>

int main() {
    const std::vector<std::string> v{"a", "b", "c", "d", "e", "f"};
    if (v.size() > 4) { 
        auto s = v[4];
        // do something with the 5th element, as it exists.
        std::cout << e; // d
    }
}

Or, you could make use of the bounds-checking element accessor at() clong with exception handling in case of attempted out-of-bounds access.

dfrib
  • 70,367
  • 12
  • 127
  • 192
0

In the range-based for loop

std::vector<sometype> vector1;
for(auto it : vector1)
{
   if(&it == &vector1.at(4))
      //do something...
   else
      continue;
}

it is not an iterator. It is an object of the type sometype that stores the value of the corresponding element in the vector.

Instead of creating an object you should use a reference as for example

std::vector<sometype> vector1;
for( auto &value : vector1)
{
   if( &value == &vector1.at(4))
      //do something...
   else
      continue;
}

Pay attention that the else statement with continue does not make a great sense. You could write simply

std::vector<sometype> vector1;
for( auto &value : vector1)
{
   if( &value == &vector1.at(4))
      //do something...
}

Though it is unclear why you are using the range-based for loop when only one element of the vector will satisfy the condition.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335