Oliver Kress
Oliver Kress

Reputation: 23

Accessing vector outside of scope of if loop in C++

First off, I'm new to C++ and very accustomed to working in MatLAB. My code will probably want to make seasoned C++ users shoot me in the face, but it looks like this:

EDIT: I have heavily edited my code snippet. The following is a cleaned up, generalized example of what I'm trying to accomplish.

int main()
{


int t = 0;
vector<int> Pad_Ref_Vec; //initialize vector. Required size unknown


     for (int n = 0; n <= 10; n++)
     {

          if (t == 0)
          { 
               vector<int> Pad_Ref_Vec(100); //at this point in the code, i know the size i need this vector to be

               for (int i = 0; i < 100; i++)
               {
                    Pad_Ref_Vec[i] = i;         
               }

           }
           else
           {

            //do some operation using the values of Pad_Ref_Vec created in the above 
            //if statement  

            }

     t++;

     }

    return 0;
}

If I do this, the vector Pad_Ref_Vec does not read [0 1 2 3 4 5 ... ... ] after the if statement, but goes back to its previous form (after the first initialization before the for loop) which is just a vector of size 0

I'm finding it hard to believe that something so simple is turning out to be such a hassle. Thanks in advance for any constructive tips.

Upvotes: 0

Views: 1962

Answers (1)

David Levy
David Levy

Reputation: 511

Several things here.

Most important thing, is lifetime of what you declare. If you declare a vector inside a {}, it won't be available outside of it. So if you want to use your vector outside of a if if (t == 0), you have to declare it outside of the if, else it won't exist anymore when you want to access it.

You can declare it outside of the if, and just initialize it when you want with a if. Or if you just want to add elements without really knowing the size, use push_back

Vector class has a lot of usefull function, to will help you in this situation : http://en.cppreference.com/w/cpp/container/vector (changed from cplusplus.com following comments)

Upvotes: 1

Related Questions