views:

295

answers:

4

Why can't I do this:

struct sName {
  vector<int> x;
};

It takes only three pointers to store a vector, so I should be able to do this?

+2  A: 
#include <vector>

using namespace std;

struct sName {
  vector<int> x;
};

int main()
{
return 0;
}

Compiled with:

g++ -Wall 1.cpp

Compiled fine.

What seems to be the problem with your code?

Douglas Leeder
When I declare a variable of this type "struct sName z" inside a switch statement, I get errors: cross initialization of 'sName z' and 'jump to case label'. Otherwise, the program works fine.
@parasoon99: That's a totally different problem. Create a new post with the new problem, but this time *include the compiler errors*
John Dibling
Thank you - will do.
@John: Couldn't the OP (or anyone) just edit the question to reflect the actual problem?
Bill
See Bills post below.
A: 

You can do this. In fact, what you have above is correct and works fine (aside from the missing semicolon and potentially missing std:: in std::vector). Please, rephrase your question so that it doesn't contradict itself.

AndreyT
+3  A: 

You mentioned this failed in a switch statement. You'll need to wrap it up in an extra pair of braces:

int type = UNKNOWN;
switch(type)
{
  case UNKNOWN:
    cout << "try again" << endl;
    break;
  case KNOWN:
  { // Note the extra braces here...
    struct sName
    { 
      vector<int> x;
    } myVector; 
  } // and here
}

Alternatively, you could have already declared the structure, and are just trying to declare and initialize a local variable. This isn't a problem unique to struct, it'll happen anytime you try to initialize a variable inside a case:

struct sName
{ 
  vector<int> x;
};

int type = UNKNOWN;
switch(type)
{
  case UNKNOWN:
    cout << "try again" << endl;
    break;
  case KNOWN:
  { // Note the extra braces here...
    sName myVector;
  } // and here
  case OTHER:
    int invalid = 0; // this will also fail without the extra pair of braces
    break;
}
Bill
I have seen this reason before, but why? And this works but I don't like this "work around".
@prasoon: all `case`s within a switch are in the same scope. A variable declared in any of them is in the scope of all of them, but the initialization could be skipped. See http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement
Bill
@parasoon99: It's not a workaround -- it is leveraging the features of the language in a way that was intended and is valid. It's just something you're not used to. I do this all the time.
John Dibling
@Bill, +1 for good psychic abilities.
Thomas Matthews
A: 

did you forget using namespace std?

Foxcat