Dynamic Array Curiousity

I'm learning about Dynamic Arrays and I'm getting to programs that apply user input with them and have been practicing this; however, I would like to learn how to, instead of using user input, read from a text file into a dynamic array.

For example-
Txt file would say:

Iron Man, 487
Captain America, 568
The Hulk, 17
Black Widow, 542
Spider Man, 309
Scarlet Witch, 184
Winter Soldier, 237
Just Thor, 491
The Falcon, 319

So like this simple dynamic array below, except instead of getting input from the user, it's reading it from this file and then showing it.

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
 #include <iostream>

using namespace std;

int main()
{
	cout << "Enter a positive integer: ";
	int length;
	cin >> length;

	int *array = new int[length]; 

	cout << "I just allocated an array of integers of length " << length << '\n';

	array[0] = 5; 

	delete[] array;
					

	cin.clear(); 
	cin.ignore(32767, '\n'); 
	cin.get(); 
	
	return 0;

}
Last edited on
In C++ you would usually use a vector for a dynamic array. Something like this:
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
30
31
32
33
34
35
36
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;

struct Movie {
    string name;
    int    votes;
    Movie(string n, int v) : name(n), votes(v) {}
};

ostream& operator<<(ostream& os, const Movie& m) {
    return os << m.name << ':' << m.votes;
}

int main() {
    ifstream fin("movies.cpp");
    vector<Movie> movies;

    string line;
    while (getline(fin, line)) {
        istringstream iss(line);
        string name;
        getline(iss, name, ',');
        int votes;
        iss >> votes;
        movies.push_back(Movie(name, votes));
    }

    for (const auto& m: movies)
        cout << m << '\n';

    return 0;
}

@tpb That's what I was thinking, but I have read conflicting information (probably over reading to the point of misunderstanding). But could you tell me what is the difference in vector and dynamic array? This confuses me a bit because I see people "int *array" and "vector" but it doesn't seem synonymous and the C++ book I have has some explanations but they're so garbled in technicality that it confuses me more tbh. I have found some awesome youtube channels that break things down better, but any information would be greatly appreciated.

Thanks, girlscout
A std::vector is a class provided by the C++ standard library that implements a dynamic array. So the only reason for you to implement a dynamic array is for learning purposes to build your own vector. As an example starting point here's a very simplified Vector I just whipped up. I used "push" instead of "push_back" and pop returns the object, but the most important difference is that the real std::vector class has around 70 methods counting all of the overloads.
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <cstring> // memcpy

template <typename T>
class Vector {
    T*     m_p;
    size_t m_capacity;
    size_t m_size;
public:
    Vector() : m_p(nullptr), m_capacity(0), m_size(0) {}
    ~Vector() { delete [] m_p; }

    void expand() {
        m_capacity = (m_capacity + 10) * 3 / 2;
        T *q = new T[m_capacity];
        if (m_p) {
            memcpy(q, m_p, m_size * sizeof(T));
            delete [] m_p;
        }
        m_p = q;
    }

    void push(T o) {
        if (m_size >= m_capacity) expand();
        m_p[m_size++] = o;
    }

    T pop() {
        if (m_size == 0) throw 0;
        return m_p[--m_size];
    }
    
    T& operator[](size_t i) { return m_p[i]; }
    
    size_t size() { return m_size; }
};

int main() {
    Vector<int> v;
    for (int i=0; i<100; i++)
        v.push(i);
    for (size_t i=0; i<v.size(); i+=2)
        std::cout << v[i] << ' ';
    std::cout << '\n';
    while (v.size() > 0)
        std::cout << v.pop() << ' ';
    std::cout << '\n';
    return 0;
}

closed account (E0p9LyTq)
what is the difference in vector and dynamic array?

1. std::vector wraps an array in a C++ class template.

2. std::vector manages its memory automatically, a programmer doesn't have to use malloc() or new to use a vector. When a vector goes out of scope the used memory is automatically released.

3. std::vector keeps track of the number of elements, the size of the vector.

4. std::vector is easily resizable at run-time, increasing or decreasing the number of elements as needed using member functions.

5. std::vector can be created empty, with a specified number of elements or specified number of elements filled with a specified value.
1
2
3
4
5
6
7
8
// create an empty vector (zero elements)
std::vector<int> aVector;

// create a sized vector, elements are all zeroes
std::vector<int> aVector2(5);

// create a size vector, with a provided value
std::vector<int> aVector3(5, 10);

6. std::vector provides iterator functions to make sequentially accessing elements less prone to get out of bounds errors.
1
2
3
4
5
for (auto itr = aVector2.begin(); itr != aVector2.end(); itr++)
{
   std::cout << *itr << ' ';
}
std::cout << '\n';

7. std::vector works well with range-based for loops
1
2
3
4
5
for (auto itr : aVector3)
{
   std::cout << itr << ' ';
}
std::cout << '\n';

8. std::vector allows elements to be inserted and erased at any position in the vector.

9. Since std::vector keeps track of its size, having a vector as a function parameter doesn't require an additional parameter of the vector's size.
1
2
foo(aVector);
foo(anArray[ ], size);
Last edited on
@tpb Oh! I haven't used "pop" yet...currently googling the heck out of it. Super useful. Thank you! So does that mean a Vector...IS a dynamic array or just implements one?
@FurryGuy You just made so much sense out of vectors 0.0 I bet you would make great tutorials!

Okay so now that this is becoming clear to me, I'm wondering why would anyone implement a dynamic array over a vector when vector seems like a better option.
closed account (E0p9LyTq)
why would anyone implement a dynamic array over a vector when vector seems like a better option.

Maybe they don't know what vectors offer, are required to use dynamic arrays, or they don't like C++.

Learning the hard way, using dynamic arrays with malloc() or new, and the possible problems that can be encountered makes learning and using C++ containers a better overall solution.

Similar to using C rand()/srand() vs. all of what the C++ <random> header offers for generating random numbers. A bit more setup work, with a change in how random numbers are created, and consistently better random sequences are obtained with <random>.

/ "random" rant off ;)
closed account (E0p9LyTq)
does that mean a vector...IS a dynamic array or just implements one?

See http://www.cplusplus.com/reference/vector/vector/

In a nutshell, a vector is a dynamic array on steroids.
I'm wondering why would anyone implement a dynamic array over a vector when vector seems like a better option.

Ignorance, mostly.

Strongly prefer not to use new or built-in arrays at all.
This is not to say there are no cases where new or built-in arrays are the best choice, just that such cases are rare, and require careful justification and careful craftsmanship.
Topic archived. No new replies allowed.