MHB Determining the size of a vector

  • Thread starter Thread starter needOfHelpCMath
  • Start date Start date
  • Tags Tags
    Vector
Click For Summary
The discussion centers around a C++ program that involves a vector named `sensorReadings`. Initially, the vector is created with a size of 4 but is then resized to 10. The main issue raised is the assignment of the vector's size to the variable `currentSize`. Instead of manually setting `currentSize` to 10, it is suggested to use the `sensorReadings.size()` method to dynamically retrieve the current size of the vector. This approach ensures that `currentSize` accurately reflects the vector's size after any modifications.
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$.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

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