Determining the size of a vector

  • Context: MHB 
  • Thread starter Thread starter needOfHelpCMath
  • Start date Start date
  • Tags Tags
    Vector
Click For Summary
SUMMARY

The discussion focuses on determining the size of a vector in C++ using the Standard Template Library (STL). The initial code incorrectly assigns a constant value of 10 to the variable currentSize after resizing the vector sensorReadings. The correct approach is to use the method sensorReadings.size() to retrieve the actual size of the vector, which reflects the number of elements it contains.

PREREQUISITES
  • Understanding of C++ programming language
  • Familiarity with the Standard Template Library (STL)
  • Knowledge of vector data structure in C++
  • Basic concepts of dynamic memory management
NEXT STEPS
  • Learn about C++ vector methods, specifically vector::size()
  • Explore memory management in C++ with dynamic arrays
  • Study the differences between static and dynamic arrays in C++
  • Investigate error handling in C++ when working with STL containers
USEFUL FOR

Students, C++ developers, and software engineers looking to enhance their understanding of vector operations and memory management in C++ programming.

needOfHelpCMath
Messages
70
Reaction score
0
May anyone help guide and explain this program for meAssign the size of vector sensorReadings to currentSize.
Code:
#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<int> sensorReadings(4);
   int currentSize = 0;

   sensorReadings.resize(10);

     
       currentSize = 10;

   cout << "Number of elements: " << currentSize << endl;

   return 0;
}
Testing sensorReadings.resize(10)
Your value: 10
✖ Testing sensorReadings.resize(2)
Expected value: 2
Your value: 10
 
Technology news on Phys.org
needOfHelpCMath said:
May anyone help guide and explain this program for me

Assign the size of vector sensorReadings to currentSize.

Hi needOfHelpCMath! (Smile)

We can retrieve the size of vector sensorReadings with [m]sensorReadings.size()[/m].
That's what we need instead of assigning a constant value of $10$.
 

Similar threads

  • · Replies 6 ·
Replies
6
Views
7K
Replies
12
Views
3K
  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 3 ·
Replies
3
Views
5K
Replies
3
Views
1K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 3 ·
Replies
3
Views
5K