Arrays

Write your question here.
I don't understand this code

1
2
3
4
5
6
7
  string *const p = new string[n]; 
  string s;
   string *q = p;                   
     while (cin >> s && q != p + n)
    *q++ = s;                    
const size_t size = q - p;       
delete[] p;  
It does roughly the same as this. Nothing useful because the array is deleted as soon as you have filled it.
1
2
3
4
5
6
   vector<string> p( n );
   for ( int i = 0; i < n; i++ )
   {
      cin >> p[i];
   }
   int size = n;


1
2
3
4
5
6
7
string *const p = new string[n];        // create a new array of size n
  string s;                             // declare a string variable
   string *q = p;                       // point q at the start of the array                    
     while (cin >> s && q != p + n)     // input strings (into s) until q points beyond the end of the array
    *q++ = s;                           // set the array element pointed to by q to string s, then advance q to point at the next element 
const size_t size = q - p;              // this simply sets the size of the array; size = n would do       
delete[] p;                             // delete the array you have input ... and done nothing with!   
Last edited on
Once understood, shortened code is probably the easiest to read, but sometimes we need to follow the logic step by step.

Perhaps this version is a bit clearer:
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
#include <iostream>
#include <string>


int main()
{
    constexpr std::size_t init_size { 4 };

    // Reserve space for init_size std::strings: 
    std::string* const p = new std::string[init_size];

    // Declare a new pointer to be modified - we don't want to modify 'p'!!
    std::string* q = p;

    std::cout << "Please insert " << init_size + 1
              << " words separated by space and press ENTER: ";

    for ( std::string s; std::cin >> s && q != p + init_size; ++q ) {
        *q = s;
    }

    const std::size_t guessed_size = q - p;

    delete[] p;

    std::cout << "initial size: " << init_size
              << "; guessed size: " << guessed_size
              << '\n';
}


Actually the original code isn't very good, because it will require you to input n+1 things before storing the first n in an array.

The order of the two 'AND'ed things in the while condition should be reversed.
while ( q != p + n && cin >> s )
The original code is meaningless. Look at the OPs next post. Obviously an ad.
Topic archived. No new replies allowed.