vector trouble

Hey all, I'm pretty new to C++ so any help would be greatly appreciated!

I'm trying to use vectors for a small program in place of arrays (though arrays are clearly a viable approach). Here is the start to my program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>

using namespace std;


class Board{
      
      vector<char> board (3);
      
      public: Board()
      {
              
      }
      
      
      public: void modboard(int x, int y, char xo)
      {
                            
      }
      
};
      
      
      
int main()
{
   vector<int> valuesd(5);
    return 0;   
}


This code gives me the error: "expected ';' before '(' token" in line 9 (right after the class definition). However, if I do not specify the size of the vector, I do not get an error.

Also, is it possible to declare a 2d vector?

Again, thanks for the help!
You may not specify a constructor for a vector inside a class definition. So instead of

vector<char> board (3);

you should write

vector<char> board;
So then I can specify the dimensions of the vector in a constructor? For example:

1
2
3
4
5
6
7
public: Board()
      {
          board = vector<char> (3);    
      }
      

You can but using another syntax

Board() : board( 3 ) {}

The difference is that in this case only one constructor of the vector is called.
Last edited on
Shouldn't the original code work in C++11? Or is that only when using curly brackets?
Peter87,
I have looked through section 9.2 of the C++ Standard quickly and there is the following grammar for the member-declarator

declarator brace-or-equal-initializeropt
Last edited on
Ok, so vector<char> board = vector<char>(3); and vector<char> board{0, 0, 0}; will work but vector<char> board(3); will not work.
wait, sorry, vlad, why does your suggested syntax work? and what are its advantages?
In your example

1
2
3
4
public: Board()
{
   board = vector<char> (3);    
}


at first the default constroctor for the vector is called then inside the body of the constructor of the class Board a temporal vector is created and the copy assignment operator is called to assign this temporal vector to the vector board.

In my example instead of calling at first the default constructor for the vector the required constructor is called at once.
Last edited on
Topic archived. No new replies allowed.