-3

Hey guys I'm trying to write a method to create vectors named y_i where i starts at 1 and ends at a variable names rows for entering a matrix. I'm trying to write it so that it dynamically adds enough vectors to this code. Vectors of the form vector y_1, vector y_2 etc etc.

Code is below. My questions are am I doing this right? do I need a struct? A class? Help!

#include <iostream>
#include <vector>
using namespace std;
int i, rows;
vector<vector< double > >matrix;
void VectorCreation(int rows)
{
    for (i = 1; i <= rows; i++)
    {
        new vector<double>;
    }
}
int main()
{
    cin >> rows;
    VectorCreation(rows);
    return 0;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Don't start with global variables, and most of the time you don't need to use `new` in modern C++ (plus, you don't *do anything* with that!). – crashmstr Oct 20 '15 at 15:11
  • 1
    _`new vector;`_ this line makes absolutely no sense. You allocate a `vector` (which you shouldn't anyway), and discard the result. – πάντα ῥεῖ Oct 20 '15 at 15:11
  • 2
    Oy.... where to start? Don't use `new` *unless you know what you are doing*. Don't use global variables *unless you know what you are doing*. Don't try to trial&error C++. [Get a good book](http://stackoverflow.com/questions/388242). ;-) That being said, what you're looking for is [documentation](http://www.cppreference.com)... – DevSolar Oct 20 '15 at 15:11

2 Answers2

1

You currently allocate a std::vector on the heap with new but don't assign it to anything so the data allocated is forever lost.

I wouldn't advice using new for this but just using stack allocation:

#include <iostream>
#include <vector>
using namespace std;
int rows;
vector<vector< double > >matrix;
void VectorCreation(int rows)
{
  matrix.resize(rows);
}
int main()
{
    cin >> rows;
    VectorCreation(rows);
    return 0;
}
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

First off

void VectorCreation(int rows)
{
    for (i = 1; i <= rows; i++)
    {
        new vector<double>;
    }
}

Is doing nothing but creating a memory leak as you are creating new vectors and then letting the pointers to them go out of scope so the memory is no longer accessible but being used.

Secondly if you want to create a 2d vector you would use:

std::vector<std::vector<type>> vector_name(num_rows, std::vector<type>(num_cols, default_value));
NathanOliver
  • 171,901
  • 28
  • 288
  • 402