Ошибка vector does not name a type

I’m having lots of errors in my final project (a poker and black jack sim). I’m using a vector to implement the «hands» in the blackJack class, and I’m using a structured data type declared in another class, which is publicly inherited. The error I’m worried about is the compiler I’m using telling me that I’m not declaring a type in the vector.

blackJack header file:

 #ifndef BLACKJACK_H
 #define BLACKJACK_H
 #include <vector>
 #include "card.h"

 class blackJack: public cards
 {
 private:
    vector <Acard> playerHand;
    vector <Acard> dealerHand;

 public:
    blackJack();
    void dealHands();
    void hitOrStay();
    void dealerHit();
    int handleReward(int);
    void printHands();
 };
 #endif 

card header file (this is the class black jack inherits from):

 #ifndef CARD_H
 #define CARD_H

 const char club[] = "xe2x99xa3";
 const char heart[] = "xe2x99xa5";
 const char spade[] = "xe2x99xa0";
 const char diamond[] = "xe2x99xa6";
 //structured data to hold card information
 //including:
 // a number, representing Ace-King (aces low)
 //a character, representing the card's suit
 struct Acard
 {
   int number;
   char pic[4];
 };



 // a class to hold information regarding a deck of cards
 //including:
 //An array of 52 Acard datatypes, representing our Deck
 //an index to the next card in the array
 //a constructor initializing the array indices to Ace-king in each suit
 //a function using random numbers to shuffle our deck of cards
 //13 void functions to print each card
 class cards
 {
  private:
    Acard Deck[52];
    int NextCard;
  public:
    cards();
    Acard getCard();
    void shuffleDeck();
    void cardAce(char[]);
    void cardTwo(char[]);
    void cardThree(char[]);
    void cardFour(char[]);
    void cardFive(char[]);
    void cardSix(char[]);
    void cardSeven(char[]);
    void cardEight(char[]);
    void cardNine(char[]);
    void cardTen(char[]);
    void cardJack(char[]);
    void cardQueen(char[]);
    void cardKing(char[]);

 };

 #endif

I’m having lots of errors in my final project (a poker and black jack sim). I’m using a vector to implement the «hands» in the blackJack class, and I’m using a structured data type declared in another class, which is publicly inherited. The error I’m worried about is the compiler I’m using telling me that I’m not declaring a type in the vector.

blackJack header file:

 #ifndef BLACKJACK_H
 #define BLACKJACK_H
 #include <vector>
 #include "card.h"

 class blackJack: public cards
 {
 private:
    vector <Acard> playerHand;
    vector <Acard> dealerHand;

 public:
    blackJack();
    void dealHands();
    void hitOrStay();
    void dealerHit();
    int handleReward(int);
    void printHands();
 };
 #endif 

card header file (this is the class black jack inherits from):

 #ifndef CARD_H
 #define CARD_H

 const char club[] = "xe2x99xa3";
 const char heart[] = "xe2x99xa5";
 const char spade[] = "xe2x99xa0";
 const char diamond[] = "xe2x99xa6";
 //structured data to hold card information
 //including:
 // a number, representing Ace-King (aces low)
 //a character, representing the card's suit
 struct Acard
 {
   int number;
   char pic[4];
 };



 // a class to hold information regarding a deck of cards
 //including:
 //An array of 52 Acard datatypes, representing our Deck
 //an index to the next card in the array
 //a constructor initializing the array indices to Ace-king in each suit
 //a function using random numbers to shuffle our deck of cards
 //13 void functions to print each card
 class cards
 {
  private:
    Acard Deck[52];
    int NextCard;
  public:
    cards();
    Acard getCard();
    void shuffleDeck();
    void cardAce(char[]);
    void cardTwo(char[]);
    void cardThree(char[]);
    void cardFour(char[]);
    void cardFive(char[]);
    void cardSix(char[]);
    void cardSeven(char[]);
    void cardEight(char[]);
    void cardNine(char[]);
    void cardTen(char[]);
    void cardJack(char[]);
    void cardQueen(char[]);
    void cardKing(char[]);

 };

 #endif

i have this error in the title:
here class declaration of variables and prototypes of function

#ifndef ROZKLADLICZBY_H
#define ROZKLADLICZBY_H


class RozkladLiczby{
public:
    RozkladLiczby(int);                  //konstruktor
    vector<int> CzynnikiPierwsze(int); //metoda
    ~RozkladLiczby();
};  


#endif

And class body:

#include "RozkladLiczby.h"
using namespace std;
#include <iostream>
#include <vector>




RozkladLiczby::~RozkladLiczby()         //destruktor
{}

RozkladLiczby::RozkladLiczby(int n){
int* tab = new int[n+1];
int i,j;

for( i=0;i<=n;i++)
    tab[i]=0;                  //zerujemy tablice

for( i=2;i<=n;i+=2)
    tab[i]=2;                  //zajmujemy sie liczbami parzystymi

for(i=3; i<=n;i+=2)
    for(j=i;j<=n;j+=i)         //sito erastotesa
        if(tab[j]==0)
            tab[j]=i;

}

   vector<int> RozkladLiczby::CzynnikiPierwsze(int m){
vector<int> tablica;
while(m!=1){
        tablica.push_back(tab[m]);
        m=m/tab[m];
}

return tablica;

}

Whats wrong with the prototype of function in first block? Why vector is told to be not a type? I would be grateful if u could help me to find out this.

asked Mar 22, 2014 at 12:25

user3402584's user avatar

Your header file does not include the vector header. Add a #include <vector> to the beggining.

Besides, you should refer to it as std::vector<int> instead of vector<int>, since it belongs to the std namespace. Declaring using namespace x; in header files is not a good practice, as it will propagate to other files as well.

Shoe's user avatar

Shoe

74.7k35 gold badges165 silver badges269 bronze badges

answered Mar 22, 2014 at 12:31

mateusazis's user avatar

0

Change your header file to:

#ifndef ROZKLADLICZBY_H
#define ROZKLADLICZBY_H
#include <vector>

class RozkladLiczby{
public:
    RozkladLiczby(int);                  //konstruktor
    std::vector<int> CzynnikiPierwsze(int); //metoda
    ~RozkladLiczby();
private:
    int* tab;
};  


#endif

answered Mar 22, 2014 at 12:29

πάντα ῥεῖ's user avatar

πάντα ῥεῖπάντα ῥεῖ

87k13 gold badges114 silver badges189 bronze badges

8

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

1

01.11.2017, 21:59. Показов 5010. Ответов 67


Студворк — интернет-сервис помощи студентам

Доброго времени суток форумчане!
Возникла проблема с векторами. но понимаю как работают эти самые векторы.
Задача такова, есть абстрактный класс Object с какими-то функциями(это не столь важно). Так же есть дочерние классы такие как Circle и Circle2. В главной функции создаются новые объекты дочерних классов и заносятся в массив.
НО когда хочу сделать через вектор то выдаёт ошибку: «error: ‘vector’ does not name a type».
так же по мере решения это проблемы будет ещё несколько вопросов таких как: «Как реализовать уничтожение объектов Массива/Вектора», «Как сделать универсальную функцию определения координат курсора в окне»



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 22:05

2

Ты заголовок подключил?



0



0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 22:10

 [ТС]

3

Какой заголовок? Заголовочный файл? Как эти файлы работают я не особо понимаю…



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 22:44

4

<vector> подключил?



0



0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 22:45

 [ТС]

5

да но не работает…



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 22:46

6

Показывай.



0



SkeiTax

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 22:49

 [ТС]

7

Вот как я создаю вектор

C++
1
vector<int> k(1);

вот что выводит компилятор «…|error: ‘vector’ does not name a type|»

Добавлено через 1 минуту
||=== Build file: «no target» in «no project» (compiler: unknown) ===|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
|13|error: ‘vector’ does not name a type|
||=== Build failed: 1 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

Это всё сообщение после сборки…



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 22:49

8

std::vector сделай. Если не заработает, значит ты не подключил заголовок.



0



SkeiTax

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 22:54

 [ТС]

9

Оп… Точно, чего-то не думал что в этом может быть проблема

Добавлено через 55 секунд
тогда следующий вопрос

Добавлено через 1 минуту
Вот часть кода в отдельном файле

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Function.cpp
using namespace sf;
 
int mouse_xy(bool i, RenderWindow *win){
    int xy[2];
    Vector2i mouse_v;
 
    mouse_v = Mouse::getPosition(*win);
 
    xy[0] = mouse_v.x;
    xy[1] = mouse_v.y;
 
    return xy[i];
}
 
float distance_to_point(float x1, float y1, float x2, float y2){
    float x, y;
    x=pow(pow(x1-x2,2),0.5);
    y=pow(pow(y1-y2,2),0.5);
    return pow(x*x+y*y,0.5);
}

Когда пытаюсь обратиться из объекта класса Circle к этой функции выдаёт ошибку



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 22:56

10

Текст ошибки где?



0



SkeiTax

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 22:59

 [ТС]

11

В главном методе создаю окно

C++
1
RenderWindow window(VideoMode(600, 500), "WinGraph");

Потом создаю объект одного из класса Circle/Circle2

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (!preSpase)
        if (Keyboard::isKeyPressed(Keyboard::Space)){
            Circle *cir = new Circle();
            cir->XX = mouse_xy(0, &window);
            cir->YY = mouse_xy(1, &window);
            cir->window = &window;
            cir->ID=id;
            cir->Create();
            obj[id] = cir;
            id++;
            upd=true;
        }
        if (!preControl)
        if (Keyboard::isKeyPressed(Keyboard::LControl)){
            Circle2 *cir = new Circle2();
            cir->XX = mouse_xy(0, &window);
            cir->YY = mouse_xy(1, &window);
            cir->window = &window;
            cir->ID=id;
            cir->Create();
            obj[id] = cir;
            id++;
            upd=true;
        }

В классе Circle я в методе Step() есть такое условие

C++
1
if (distance_to_point(x, y, mouse_xy(0,&window), mouse_xy(1,&window))<R);

и в итоге выдаёт ошибку: «…|error: cannot convert ‘sf::RenderWindow**’ to ‘sf::RenderWindow*’ for argument ‘2’ to ‘int mouse_xy(bool, sf::RenderWindow*)’|»



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 23:04

12

Тип второго параметра не верный. Может, там другой window?



0



SkeiTax

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 23:07

 [ТС]

13

вот часть кода в Circle2

C++
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
31
32
33
34
35
class Circle2 : public Object{
public:
    float x, XX, y, YY, speed, R=25;
    int dir, ID;
 
    RenderWindow *window;
    CircleShape shape;
 
    void Create(){
        x=XX;
        y=YY;
        dir=0;
        speed=0;
 
        shape.setRadius(R);
        shape.setOrigin(R,R);
        shape.setFillColor(Color(100,175,200));
    }
...
 
        if (speed<0) speed=0;
        if (Keyboard::isKeyPressed(Keyboard::A)) dir=180;
        if (Keyboard::isKeyPressed(Keyboard::D)) dir=0;
        if (Keyboard::isKeyPressed(Keyboard::W)) dir=90;
        if (Keyboard::isKeyPressed(Keyboard::S)) dir=270;
        y-=sin(dir*M_PI/180)*speed;
        x+=cos(dir*M_PI/180)*speed;
 
        if (distance_to_point(x, y, mouse_xy(0,&window), mouse_xy(1,&window))<R);
    }
 
    void Draw(){
        shape.setPosition(x, y);
        window->draw(shape);
    }



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 23:08

14

Ну так зачем ты двойной указатель передаёшь? Убери амперсанды.



0



SkeiTax

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 23:11

 [ТС]

15

хорошо но тогда ошибка тоже… сейчас покажу

Добавлено через 1 минуту
||=== Build file: «no target» in «no project» (compiler: unknown) ===|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
|8|warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11|
||In function ‘int mouse_xy(bool, sf::RenderWindow*)’:|
->|5|error: redefinition of ‘int mouse_xy(bool, sf::RenderWindow*)’|
|5|note: ‘int mouse_xy(bool, sf::RenderWindow*)’ previously defined here|
||In function ‘float distance_to_point(float, float, float, float)’:|
|17|error: redefinition of ‘float distance_to_point(float, float, float, float)’|
|17|note: ‘float distance_to_point(float, float, float, float)’ previously defined here|
||=== Build failed: 2 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

Добавлено через 1 минуту
в условии теперь без амперсантов

C++
1
if (distance_to_point(x, y, mouse_xy(0, window), mouse_xy(1, window))<R);



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 23:13

16

Там же всё написано. Redefenition — ты два раза одну и туже функцию описал, что ли?



0



SkeiTax

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 23:21

 [ТС]

17

В смысле?

Добавлено через 1 минуту
вот

C++
1
if (distance_to_point(x, y, mouse_xy(0, window), mouse_xy(1, window))<R);

Добавлено через 3 минуты
функция возвращающая расстояние между точками — distance_to_point(x1, y1, x2, y2)
Возвращает координату по x и y если первый аргумент равен 0 или 1 соответственно — mouse_xy(0, window)



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 23:22

18



0



SkeiTax

0 / 0 / 0

Регистрация: 06.09.2017

Сообщений: 114

01.11.2017, 23:35

 [ТС]

19

координату курсора мышки относительно окна window *

Добавлено через 2 минуты
В файле Cickle2.cpp подключается <Function.cpp> и в Main.cpp

Добавлено через 1 минуту
Все подключения в Main.cpp

C++
1
2
3
4
5
6
#include "Include.h"
#include "Object.cpp"
#include "Circle1.cpp"
#include "Circle2.cpp"
#include "Function.cpp"
#include <vector>

Все подключения в Circle2.cpp

C++
1
2
#include "Include.h"
#include "Function.cpp"

И Include.h

C++
1
2
3
4
5
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/System/Vector2.hpp>
#include <math.h>

Добавлено через 3 минуты
Благодарю за помощь я понял в чём была беда)

Добавлено через 41 секунду
Теперь меня интересует ещё кое что

Добавлено через 3 минуты
Вот у меня есть объект Circle & Circle2. В данный момент они сохраняются в массив Object *obj[1];
я хочу передать под вектор всё это дело и как я понимаю это выглядит так: vector<Object*> obj;
И вот как например удалять созданные объекты которые «сохраняются» в этот вектор и как и него добавлять новые объекты Circle и Circle2?



0



7535 / 6397 / 2917

Регистрация: 14.04.2014

Сообщений: 27,863

01.11.2017, 23:40

20

Если там указатели, просто delete и присваиваешь другой. От массива не отличается.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

01.11.2017, 23:40

Помогаю со студенческими работами здесь

Классы, объекты
Привет. Необходимо обратиться к объекту не используя (например, TextBox a = (TextBox)sender) т.к….

Классы и объекты
Создать объявление класса и разработать программу-драйвер, который продемонстрирует работу класса….

КЛАССЫ И ОБЪЕКТЫ
Помогите с кодом:

Рациональная (несократимая) дробь представляется парой целых чисел (а, b), где…

Классы и объекты
Здравствуйте объясните пожалуйста следующую задачу
Нужно создать класс данных А и класс…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20

I have a mysterious problem. I keep getting a ‘vector’ does not name a type error when trying to define a variable in the tour class. The library seems installed correctly, since I can define vectors in main. According to many posts here I have checked for the right vector includes and std namespace. Still I get the error.

main.cpp

#include <vector>
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <cmath>
#include <cstdlib>
#include "tour.h"
using namespace std;

int main () {

        //vector declaration works here
return 0;
}

tour.h

#ifndef TOUR_H_
#define TOUR_H_

#include<vector>
using namespace std;

class tour
{
    public:
      //variables
      int teamID;
      vector<int> tourseq; //this is where the error occurs

      //functions
      tour(int);

};

#endif /* TOUR_H_ */

tour.cpp

#include<vector>
#include "tour.h"
using namespace std;

tour::tour(int id){
teamID = id;
}

What could be wrong here?

  • Ошибка vds10 gta 4
  • Ошибка vds bmw s1000rr
  • Ошибка vdc off инфинити g25
  • Ошибка vdc off инфинити fx35
  • Ошибка vdc off nissan teana j32