简体   繁体   中英

is there any way to define dynamic array without Determine the size of it

I need a dynamic array that I don't have to scale(Determine) to a fixed number like the following

string* s;

I have this code so far, but obviously it doesn't work.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    fstream f;
    f.open("resa.txt");
    string* s;
    int i = 0;
    while (f.good())
    {
        f >> *(s + i);
        i++;
    }
    return 0;
}

This is my task:

Now we change the class definitions a bit. No static arrays can occur anymore. The fact that the arrays instead become dynamic means that some class methods need to be modified, and that some / some of the classes need copy constructors and assignment methods (or superimposed assignment operator). [...]"

This means, that I just can't use data structures.

It's not automatic, you have to allocate more memory every time you want to resize, copy elements into new array and delete the old one. Fortunately, standard library got you covered with std::vector - an automatically resizable array.

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    fstream f;
    f.open("resa.txt");
    string temp;
    std::vector<std::string> s;
    while (f >> temp)
    {
        s.push_back(temp);
    }
    return 0;
}

I also fixed your input reading - see Why is iostream::eof inside a loop condition (ie while (.stream.eof()) ) considered wrong? (applies to good() as well).


Alternatively, you can use std::istream_iterator to initialize vector in one line instead of using loop (credit to Ayxan ):

vector<string> s{ istream_iterator<string>{f}, {} }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM