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?
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?
#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?
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.
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;
}