mercredi 11 août 2021

error while pushing back pointer vector elements to non pointer vector c++

I am trying to push back elements of pointer vector ptrVctor to nonpointer vector myvector2 through below for loop in function full when the input words size is greater than or equal to 5 but its not happening. When I enter less than 5 words program runs fine. But when I enter more than 5 words program didnt worked as expected but it just terminates.

Main.hpp:

#ifndef WORDS_WORDS1_H
#define WORDS_WORDS1_H

#endif //WORDS_WORDS1_H

#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>
#include <algorithm>

using namespace std;
template <class T>
class MyVector {
public:
    void full(int i){
        if (i >= 5) {//

            for (int j=0; j<ptrVctor->size(); j++){
                myvector2.push_back((*ptrVctor)[j]);//has problem
            }
            delete ptrVctor;
            ptr_cout++;
        }
    }
    void setItems2( T &a){
        if (ptr_cout==0){
            ptrVctor->push_back(a);
        }
        else{
            myvector2.push_back(a);
        }
    }

    int getUsed2 (){
        if (ptr_cout==0)
            return ptrVctor->size();
        else
            return myvector2.size();
    }
    void setUsed2 (int a){
        used2 = a;
    }
private:
    int used2 =0;
    int ptr_cout =0;
    vector<T>* ptrVctor = new vector<T>();
    vector<T> myvector2;
};

Main.cpp:

#include "main.hpp"
int main()
{
    MyVector<string> v;
    int count = 0;
    string word;
    while (cin >> word) {

        count += 1;
        v.setUsed2(count);
        v.setItems2(word);
        v.full(count);
    }
    cout << "Total: " << v.getUsed2() << '\n';
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire