-4

I have tried to realize set by basic metods via struct. This is my variant:

#include <iostream>

using namespace std; 

struct Set<T> {
    int n;
    T[n] elements;
}

int main(){
    struct Set microSet;
    int oneElm, length;
    cin>>length;
    microSet.n=length;
    for(int i=0;i<length;i++) {
        cin>>oneElm;
        microSet.elements[i]=oneElm;
    }

    for(int i=0;i<length;i++) 
        cout << microSet.elements[i];

    return 0;
}

Compilator shows me an error related with sruct. What've I done wrong?

litelite
  • 2,857
  • 4
  • 23
  • 33
DumbSimon
  • 65
  • 1
  • 7
  • 2
    What does the actual error text say? Do note that a struct/class body must end with a `;`. – NathanOliver Jul 19 '17 at 17:42
  • 6
    You should read a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Passer By Jul 19 '17 at 17:44
  • 3
    If this is not a learning exercise, just use `std::set`. – cdhowie Jul 19 '17 at 17:45
  • 1
    Something to read: [Why is “using namespace std” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Deduplicator Jul 19 '17 at 17:45
  • 2
    It looks like you're attempting a fusion of C++, Java, and C based on guesswork. Get yourself a good book. – molbdnilo Jul 19 '17 at 18:14

1 Answers1

6

Your code is illegal (and wrong in many places, so take a few days to read a good C++ book then look at some C++ reference website). You can't declare a variable length array as a member of a struct or class (and even if you could, you have the wrong syntax; some compilers support them as an extension, and C99 -but no C++ dialect- has flexible array members).

You'll better use existing standard C++ containers. If you can't use them, you need pointers (and you should prefer smart pointers).

Even if you have some compiler accepting VLAs as an extension, you probably need to dynamically allocate a memory zone for them.

I strongly recommend learning to use containers.

Don't forget to enable all warnings & debug info when compiling. With GCC, compile with g++ -Wall -Wextra -g. Use the debugger (gdb) and perhaps valgrind.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547