How do I declare a Global Vector?

Apr 5, 2017 at 11:41pm
Hello thank you for taking the time to help.
Does someone know the proper way to declare a vector GLOBALLY?
The following code works when I put the vector within the function and make it local.
But for my assignment it needs to be declared Globally because I will have more than one function using it.
Any help would be much appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54


#include<iostream>
#include<fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>


using namespace std;

vector<int> Practice(9);
Practice[0] = 2;
Practice[1] = 9;
Practice[2] = 5;
Practice[3] = 7;
Practice[4] = 33;
Practice[5] = 16;
Practice[6] = 63;
Practice[7] = 96;
Practice[8] = 55;




string ascend = "Vector sorted in Ascending Order";



void function1()
{

int i;
sort(Practice.begin(), Practice.end());
	cout << ascend << endl;
	for (i = 0; i < Practice.size(); i++)
	{
		cout << Practice[i] << " ";
	}

}




int main()
{
	
	function1();
	return 0;

}
}
Last edited on Apr 5, 2017 at 11:55pm
Apr 5, 2017 at 11:51pm
Pass the vector by copy as arguments to the required calling functions and do stuff on these copies, keeping the original vector unchanged.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <algorithm>

static const std::vector<int> practice {2, 9, 5, 7, 33, 16, 63, 96, 55};
void function1(std::vector<int> v)
{
    std::sort(v.begin(), v.end());
    std::cout << "Vector sorted in ascending order \n";
    for (const auto & elem : v)std::cout << elem << " ";
    std::cout << "\n";
}

int main()
{
   function1(practice);
}

note there the original vector is const qualified and so has to be passed by copy to modifying algorithms like std::sort that gets to work on a copy of the vector. If you wish to pass the vector by reference then the original vector should not be const qualified
Apr 6, 2017 at 12:16am
thank you so much for your help!
Topic archived. No new replies allowed.