2

I write a program using cpp to read strings with cin and save them in an allocated memory. An extra work I need to do is dealing with the circumstance when the size of the input is more than expected. When I testing the code, it doesn't display the content of the final memory saves, cannot terminate automatically. Here is the code.

#include <iostream>
#include <memory>
using namespace std;
int main(){
    allocator<string> sa;
    cout << "Please input the amount of words" << endl;
    int count;
    cin >> count;
    auto p = sa.allocate(count);
    cout << "Please input the text" << endl;
    string s;
    auto q = p;
    while(cin >> s){
        if (q == p + count) {
            auto p2 = sa.allocate(count * 2);
            auto q2 = uninitialized_copy_n(p, count, p2);
            while (q != p) {
                sa.destroy(--q);
            }
            sa.deallocate(p, count);
            p = p2;
            q = q2;
            count *= 2;
        }
        sa.construct(q++, s);
    }
    for (auto pr = p; pr != q; ++pr) {
        cout << *pr << " ";
    }
    cout << endl;
    while (q != p) {
        sa.destroy(--q);
    }
    sa.deallocate(p, count);
    return 0;
}
  • why using a allocator for this? I'm surprised that you use this instead of new or even better(!), a container like std::vector and std::string. – The Techel May 06 '17 at 09:49

1 Answers1

5

Why do you use allocator? This template shouldn't be used directly in code. It suppose to be used to tweak behavior of STL containers. You are a newbie so do not touch it. This feature is for advanced developers to be used in extreme cases.

Simply just use std::vector<string> it has all features you need.

cout << "Please input the amount of words" << endl;
int count;
cin >> count;
auto v = vector<string> {};
v.reserve(count);

string s;
while (cin >> s)
{
    v.push_back(s);
}
Marek R
  • 32,568
  • 6
  • 55
  • 140