List three ways to initialize a vector with the value 42

closed account (EwCjE3v7)
I have this ecer
List three ways to define a vector and give it ten elements,
each with the value 42. Indicate whether there is a preferred way to do so
and why.

But it does not say if it has to be a int or string ...
so i went for int and i got this

1
2
3
4
5
6
7
8
9
10
11
12
13
  #include <iostream>
#include <vector>
using std::cout; using std::cin; using std::endl;
using std::vector; using std::string;

int main()
{
    vector<int> (10, 42); // first
    vector<int> {42, 42, 42, 42, 42, 42, 42, 42, 42, 42}; // second
    
    return 0;
}


And i donno a third way to do it with an int

but i can do it with a string:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
using std::cout; using std::cin; using std::endl;
using std::vector; using std::string;

int main()
{
    vector<string> (10, "42"); // first
    vector<string> {10, "42"}; // second
    vector<string> {"42", "42", "42", "42", "42", "42", "42", "42", "42", "42"}; // third

    return 0;
}


So is there a third way with the int vector or no?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>

int main()
{
	std::vector<int> first(10, 42);                           //uses fill constructor
	std::vector<int> second(first.begin(), first.end());      //uses range constructor
	std::vector<int> third(second);                           //uses copy constructor       
	std::vector<int> fourth{42, 42, 42, 42, 42, 42, 42, 42, 42, 42};
	int *pFirst, *pSecond;
	pFirst = &first[0];
	pSecond = &first[9];
	std::vector<int> fifth(pFirst, pSecond);               //another use of the range constructor

	std::cin.ignore();
	return 0;
}


http://www.cplusplus.com/reference/vector/vector/vector/
Last edited on
Create an empty vector and add elements using a loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <vector>

int main()
{
    vector<int> first(10, 42);
    vector<int> second{42, 42, 42, 42, 42, 42, 42, 42, 42, 42};
    vector<int> third;
    
    for(int k=0; k<10; k++)
        third.push_back(42);
    
    return 0;
}
closed account (EwCjE3v7)
Thanks guys
Topic archived. No new replies allowed.