-3

The goal here == i'm trying to push_back a string value into a vector.... issues arises such as (vector subscript out of range)

i've made a function that accepts a string vector as a parameter

i've made a for loop inside that function utilizing a variable combined with a 'cin' function

all i got back is 'vector subscript out of range'... how? am i missing something?

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


    void sentDef(std::vector <std::string> sentienceVar) {

        std::string terms;

        std::cout << "input how many terms/variables made" << std::endl;
        int howManyVar;
        std::cin >> howManyVar;

        for (int i = 0; i < howManyVar; i++) {
            std::cin >> terms;
            sentienceVar.push_back(terms);
        }
    }

    int main() {

        std::vector <std::string> sentienceVar;
        sentDef(sentienceVar);

        std::cout << sentienceVar[0] << std::endl;

        system("pause");

    }
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    [Read a good beginners book or two](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and learn the difference between passing argument by value or by reference. – Some programmer dude Oct 08 '17 at 16:23
  • If you're going to change anything passed as parameter to your function pass it by reference. – user0042 Oct 08 '17 at 16:26

2 Answers2

4

Change this:

void sentDef(std::vector <std::string> sentienceVar)

to this:

void sentDef(std::vector <std::string>& sentienceVar)

Now your vector is passed by reference, and thus preserves the changes made to it.

In your code, it was passed by value (thus a copy of it was passed to the function. The function operated on that copy, and at the end of that function, that copy went out of scope).

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • lol of course xD its always those little small mistakes... now this makes me take my teachers more seriously when they say some of the biggest errors are probably the smallest things we overlook lol – thundergawd Oct 08 '17 at 16:29
  • @thundergawd your should hear your teachers! – gsamaras Oct 08 '17 at 16:34
  • 2
    @gsamaras Please stop answering these _off-topic_ questions. There's a close reason for them. Also better know the dupes! – user0042 Oct 08 '17 at 16:37
1

To expand on @gsamars, please google passing arguments by copy and by reference.

What you are doing in your function is accepting a copy of the vector, so the original sentiencevar is empty when the function returns!

The addition of & after the type tells the compiler you want to pass by reference, so what you coin the function affects the original vector. Note this is also faster than creating a copy.

kabanus
  • 24,623
  • 6
  • 41
  • 74
  • i know, its just overlooked too hard and didn't realize this, kind of like we sometimes forget ';' at the end of some line. thx – thundergawd Oct 08 '17 at 16:29