0

I understand how to manipulate a vector within a function, but I am confused on how to return that vector. I am quite new to C++ and would appreciate any guidance. I am currently using these libraries within this function :

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

using std::cin; using std::cout; using std::endl;
using std::string; using std::vector;

I am unsure if I am already missing something which is causing many errors during compiling, but this is what I have initialized my program with. I seem to have an absolutely massive amount of errors when compiling. I have noticed a lot of errors with a focus on ostream which could be the source of my problems. Here is the code I'd like to run. This is a dumbed down version of what I'd like to do within the function, but I was baffled at the massive amount of errors with such little code which I am assuming is derived from trying to return a vector. Thank you for any help you can provide me with.

vector<long> function(long small,long big){

    vector<long> vec;

    vec.push_back(big);

    vec.push_back(small);

    return vec;
}

int main(){

    cout << function(1, 2);
}
Teddy
  • 55
  • 1
  • 2
  • 4

1 Answers1

-1

Your problem isn't with returning a vector, but trying to output a vector. You can output an element from a vector, but there is no predefined function to output a vector. You can either assign a vector to the one that is returned then iterate through that (Option1), or write a function to output a vector (Option 2 and 3).

Option 1:
std::vector<long> vec;

vec = function(1, 2);

for(long i: vec)
    std::cout << vec.at(i) << " ";

Option 2:
void printVector(std::vector<long> vec)
{
    for(long i: vec)
        std::cout << vec.at(i) << " ";
}

Option 3:
std::ostream& operator<<(std::ostream& out, std::vector<long> vec)
{
    for(long i: vec)
        out << vec.at(i) << " ";
    return out;
}

int main()
{
    std::vector<long> vec;
    //Do whatever to vec
    printVector(vec);
    std::cout << vec;
    return 0;
}

All of the options will give the exact same output.
If you want to do the function "correctly" you should make it a template function, but as you are very new, I won't go into that. However if you do want to here is a walkthrough.

Hawkeye5450
  • 672
  • 6
  • 18
  • I think you mean `i < vec.size()`. Also, a range-based `for` loop would be a better option if you're just printing values. – Mike Borkland Mar 11 '18 at 00:55