0

I create a partition and union structure. It can make a set and return the position of that set. In my code, my partition class has a listSet class. The problem is I cannot output element in the main() after I return the position of a set, but in the function makeSet(), I can output the element. I do not know if my data type of makeSet() correct or not. How could I fix the bug? Should I return a pointer in makeSet()?

#ifndef LISTSET_H
#define LISTSET_H

#include <iostream>
#include <vector>
using namespace std;

template<typename E>
class Partition
{
    public:
typedef typename vector<E>::iterator Itr; //create an iterator

public:
    template <typename E>
    class listSet //create an class listSet
    {   
        private:
            vector<E> L;
            int size;

        public:
            listSet() { size = 1; }
            int getSize() { return size; }

            Itr insert(E e) /*return a position*/
            { 
                L.push_back(e);
                Itr p = L.begin();
                //cout << *p << endl; //OK
                return p;
            }
    };

    public:
      Itr makeSet(E e);
};

template<typename E>
 typename Partition<E>::Itr Partition<E>::makeSet(E e)
{
 listSet<E> set; 
 Itr p = set.insert(e);
 cout << *p << endl; //OK

 return p;
}
#endif 

int main()
{
Partition<int> set1;
Partition<int>::Itr  p1, p2, p3;
p1 = set1.makeSet(1);
p2 = set1.makeSet(2);

cout << *p1 << endl; //error is here
}

enter image description here

Jun
  • 1
  • 2
  • If I comment out cout << *p1 << endl; in main(), I can output 1 and 2 in my makeSet(). – Jun Jun 24 '22 at 05:30
  • 1
    When in ***your*** code does the exception happen? And please **[edit]** your question to add important details. – Some programmer dude Jun 24 '22 at 05:32
  • 2
    `makeSet` returns a dangling iterator to a local variable that was destroyed when the function ended. – Retired Ninja Jun 24 '22 at 05:33
  • @ Retired Do you mean I should change it to return a pointer in makeSet()? – Jun Jun 24 '22 at 06:35
  • Two problems: #1) listSet set; should be a class member so it hangs around between function calls, #2) when a vector reallocates it's size the iterators become invalid so either reserve the full size first or don't do this. Much better to create functions on the template class to ask for these details directly from the vector when you need it – Natio2 Jun 24 '22 at 06:55

0 Answers0