Why is this simple block of code not compiling
//using namespace std;
struct test {
std::vector<int> vec;
};
test mytest;
void foo {
mytest.vec.push_back(3);
}
int main(int argc, char** argv) {
cout << "Vector Element" << mytest.vec[0] << endl;
return 0;
}
I get the following errors:
vectorScope.cpp:6:5: error: ‘vector’ in namespace ‘std’ does not name a type
vectorScope.cpp:11:6: error: variable or field ‘foo’ declared void
vectorScope.cpp:11:6: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
vectorScope.cpp:12:12: error: ‘struct test’ has no member named ‘vec’
vectorScope.cpp:12:28: error: expected ‘}’ before ‘;’ token
vectorScope.cpp:13:1: error: expected declaration before ‘}’ token
Thank you,
Mustafa
You can actually create a vector of structs!
Vector allocates what it holds on the heap (vec. size() * sizeof(/* what you are holding*/)) - it holds sizeof(std::vector<>) on where it is allocated. Global variables may be stored anywhere, it depends on the implementation.
Can C++ struct have member functions? Yes, they can.
You need to include vector header file
#include <vector>
#include <iostream>
struct test {
std::vector<int> vec;
};
test mytest;
void foo() {
mytest.vec.push_back(3);
}
int main(int argc, char** argv)
{
foo();
if (!mytest.vec.empty()) // it's always good to test container is empty or not
{
std::cout << "Vector Element" << mytest.vec[0] << std::endl;
}
return 0;
}
You didn't include the vector header or possibly the iostream one if your code sample is complete. Also your foo function is incorrectly declared without the () for parameters:
#include <vector>
#include <iostream>
using namespace std;
struct test {
std::vector<int> vec;
};
test mytest;
void foo() {
mytest.vec.push_back(3);
}
int main(int argc, char** argv) {
cout << "Vector Element" << mytest.vec[0] << endl;
return 0;
}
Also, your subscripting an empty vector at index 0 which is undefined behaviour. You probably wanted to call foo() first before doing that?
You are missing the <vector>
header.
#include <vector>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With