Passiing vector as a parameter

This is why programming is so frustrating to me. In my class, I didnt even know what a C++ vector was until this assignment was due. ??? Anyway, I need to pass the vector declared in int main into the plusPlusN function so I can modify it. (If anyone cares, Im just suppose to take the vector's numerical equivalent and add one to it) But my issue is I can't pass this vector into my function without it crashing my computer or telling me my vector isnt just
9 9 but instead it says its like 9 9 921235654.
I know to some of you I look like an idiot but any help is appreciated.

#include <iostream>
#include <vector>

using namespace std;

1
2
3
4
5
6
7
8
9
10
11
12
vector<int> plusPlusN(vector<int> v)
{

    return v;
}

int main()
{
    vector<int> v {9, 9};
    vector<int> retVal = plusPlusN(v); // retVal = {1, 0, 0}
    return 0;
}
Last edited on
The code you've posted doesn't really do anything. There's no way for it to crash or display anything, so I can't really help you with the problems you mentioned.

You can pass a vector by reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <vector>
#include <iostream>

//Note the ampersand, which declares the function parameter as a reference.
void f(std::vector<int> &v){
    v.push_back(42);
}

int main(){
    std::vector<int> a = {2, 4};
    for (auto i : a)
        std::cout << i << std::endl;
    std::cout << "-----\n";
    f(a);
    for (auto i : a)
        std::cout << i << std::endl;
}
Last edited on
I don't see a problem with the code posted. Perhaps the problem is in some other part of the code.
Sorry I should've elaborated more.
1) I have the use the function stated above exactly as its written (means i cant pass by reference)
2)My code doesnt have anything because I cant find a way to pass it into the function
Could you post your actual code which allows us to reproduce the same error which you are getting?
The code you've shown is correctly passing a vector into the function and the function is correctly returning another vector to the caller. If you're having problems with some code then you should post that code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>

using namespace std;

vector<int> plusPlusN(vector<int> v)
{

    cout << "Vector: ";
    for (unsigned int i = 0; i<= v.size(); i++)
    {
       cout << v[i] << " ";
    }

    cout << endl;
    return v;
}

int main()
{
    vector<int> v {9, 9};
    vector<int> retVal = plusPlusN(v); // retVal = {1, 0, 0}
    return 0;
}


Here im just trying to show whats inside the vector v.
1
2
// for (unsigned int i = 0; i<= v.size(); i++)
for (unsigned int i = 0; i < v.size(); i++) // note: i less than v.size()  
Thank you so much!
Topic archived. No new replies allowed.