Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global struct with vector member [closed]

Tags:

c++

struct

vector

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

like image 313
Mustafa Avatar asked Jan 14 '13 00:01

Mustafa


People also ask

Can you have a vector in a struct?

You can actually create a vector of structs!

Can we declare vector globally?

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 structure contains function in C++?

Can C++ struct have member functions? Yes, they can.


3 Answers

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;
}
like image 139
billz Avatar answered Oct 12 '22 15:10

billz


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?

like image 45
goji Avatar answered Oct 12 '22 15:10

goji


You are missing the <vector> header.

#include <vector>
like image 34
juanchopanza Avatar answered Oct 12 '22 15:10

juanchopanza