How to Properly Resize and Populate a Vector in C++ Without Using push_back?

  • Context: C/C++ 
  • Thread starter Thread starter EvanET
  • Start date Start date
  • Tags Tags
    C++ Vector
Click For Summary
SUMMARY

To resize and populate a vector in C++ without using the push_back method, developers can utilize the resize function or reassign the vector with a new instance. Specifically, the vector countDown should be resized to newSize elements, and then populated with integers in descending order from newSize to 1. For example, if newSize is set to 3, the output will be 3 2 1 Go!.

PREREQUISITES
  • C++ programming language knowledge
  • Understanding of STL (Standard Template Library) vectors
  • Familiarity with vector member functions like resize and at
  • Basic knowledge of loops and output in C++
NEXT STEPS
  • Learn how to use vector::resize effectively in C++
  • Explore vector initialization techniques in C++
  • Investigate performance implications of vector resizing
  • Study alternative data structures in C++ for dynamic arrays
USEFUL FOR

C++ developers, software engineers, and students learning about vector manipulation and memory management in C++.

EvanET
Messages
10
Reaction score
0
Resize vector countDown to have newSize elements. Populate the vector with integers {newSize, newSize - 1, ..., 1}. Ex: If newSize = 3, then countDown = {3, 2, 1}, and the sample program outputs:

3 2 1 Go!

**I want to do this WITHOUT push_back**
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> countDown(0);
int newSize = 0;
int i = 0;

newSize = 3;

//enter code here

for (i = 0; i < newSize; ++i) {
count << countDown.at(i) << " ";
}
count << "Go!" << endl;

return 0;
}
 
Technology news on Phys.org
EvanET said:
Resize vector countDown to have newSize elements. Populate the vector with integers {newSize, newSize - 1, ..., 1}. Ex: If newSize = 3, then countDown = {3, 2, 1}, and the sample program outputs:

3 2 1 Go!

**I want to do this WITHOUT push_back**
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> countDown(0);
int newSize = 0;
int i = 0;

newSize = 3;

//enter code here

for (i = 0; i < newSize; ++i) {
count << countDown.at(i) << " ";
}
count << "Go!" << endl;

return 0;
}

Hi EvanET! Welcome to MHB! ;)

To pre-allocate the required memory, we can use 2 methods:
1. Call [M]countDown.resize(newSize)[/M].
2. Re-create the vector by executing [M]countDown = vector<int>(newSize)[/M].

After that we still have to fill in the newly available memory locations.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 36 ·
2
Replies
36
Views
6K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 66 ·
3
Replies
66
Views
6K