0

I am hoping to get a newly generated vector and add into a global vector from calling two functions in main. I have a rough idea of how to do this but apparently this is not right..pretty new to c++ and I don't really quite want to deal with vector recycle..do I have to use pointers if I can't use C++11? what's the best way to do this?

void main(){
  vector <int> newVector = function1 ();
  addVector (newVector);
}

vector <int> function1 (){
   ....
   return returnedVector
}

void addVectors (vector <int> incomingVector){
   globalVector.insert( globalVector.end(), incomingVector.begin(), incomingVector.end());
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
acbh
  • 167
  • 1
  • 8

1 Answers1

0

First off, void main() in c++ is bad - it should be int main().

Secondly, you have the statement return vector; in function1() whilst you are likely using namespace std; - this is also very bad, as it can be interpreted as attempting to return a type which is not possible nor what you want to do.

Here is a refactoring of your code:

#include <vector>
std::vector<int> function1(); // declaration
void add_vectors(std::vector<int>& ov, const std::vector<int>& iv);
int main() {
    std::vector<int> overall_vec;
    std::vector<int> vec = function1();
    add_vector(overall_vec, vec);
}
std::vector<int> function1() { // definition
    std::vector<int> rtnvec;
    // fill rtnvec with some values
    return rtnvec;
}
// insert incoming_vec to end of overall_vec
void add_vectors(std::vector<int>& overall_vec, const std::vector<int>& incoming_vec) {
    overall_vec.insert(overall_vector.end(), incoming_vec.begin(), incoming_vec.end());
}

Note that we haven't used a global std::vector variable here as global variables are generally quite bad, it's typically better to pass the vector around by reference or const reference when and if you need to - or wrap your code in a class or namespace if the situation is suitable for either.

Community
  • 1
  • 1
sjrowlinson
  • 3,297
  • 1
  • 18
  • 35