Синтаксическая ошибка идентификатор vector

What’s wrong with this line of code?

bar foo(vector ftw);

It produces

error C2061: syntax error: identifier 'vector'

bdonlan's user avatar

bdonlan

225k31 gold badges268 silver badges324 bronze badges

asked Jun 11, 2010 at 22:04

Nick Heiner's user avatar

Nick HeinerNick Heiner

119k188 gold badges476 silver badges699 bronze badges

try std::vector instead. Also, make sure you

#include <vector>

answered Jun 11, 2010 at 22:06

Adrian Grigore's user avatar

Adrian GrigoreAdrian Grigore

33k36 gold badges130 silver badges210 bronze badges

Probably you forgot to include vector and/or import std::vector into the namespace.

Make sure you have:

#include <vector>

Then add:

using std::vector;

or just use:

bar foo(std::vector<odp> ftw);

answered Jun 11, 2010 at 22:06

Matthew Flaschen's user avatar

Matthew FlaschenMatthew Flaschen

279k50 gold badges514 silver badges539 bronze badges

1

Do you have:

#include <vector>

and

using namespace std; in your code?

<vector> defines the std::vector class, so you need to include it some where in your file.

since you’re using vector, you need to instruct the compiler that you’re going to import the whole std namespace (arguably this is not something you want to do), via using namespace std;

Otherwise vector should be defined as std::vector<myclass>

answered Jun 11, 2010 at 22:06

Alan's user avatar

try std::vector<odp> or using std;

answered Jun 11, 2010 at 22:06

TreDubZedd's user avatar

TreDubZeddTreDubZedd

2,5711 gold badge15 silver badges20 bronze badges

On its own, that snippet of code has no definition of bar, vector or odp. As to why you’re not getting an error about the definition of bar, I can only assume that you’ve taken it out of context.

I assume that it is supposed to define foo as a function, that vector names a template and that it is supposed to define a parameter called ftw but in a declaration anything that is not actually being defined needs to have been declared previously so that the compiler knows what all the other identifiers mean.

For example, if you define new types as follows you get a snippet that will compile:

struct bar {};
struct odp {};
template<class T> struct vector {};

bar foo(vector<odp> ftw);

answered Jun 11, 2010 at 22:07

CB Bailey's user avatar

CB BaileyCB Bailey

757k105 gold badges633 silver badges656 bronze badges

What’s wrong with this line of code?

bar foo(vector ftw);

It produces

error C2061: syntax error: identifier 'vector'

bdonlan's user avatar

bdonlan

225k31 gold badges268 silver badges324 bronze badges

asked Jun 11, 2010 at 22:04

Nick Heiner's user avatar

Nick HeinerNick Heiner

119k188 gold badges476 silver badges699 bronze badges

try std::vector instead. Also, make sure you

#include <vector>

answered Jun 11, 2010 at 22:06

Adrian Grigore's user avatar

Adrian GrigoreAdrian Grigore

33k36 gold badges130 silver badges210 bronze badges

Probably you forgot to include vector and/or import std::vector into the namespace.

Make sure you have:

#include <vector>

Then add:

using std::vector;

or just use:

bar foo(std::vector<odp> ftw);

answered Jun 11, 2010 at 22:06

Matthew Flaschen's user avatar

Matthew FlaschenMatthew Flaschen

279k50 gold badges514 silver badges539 bronze badges

1

Do you have:

#include <vector>

and

using namespace std; in your code?

<vector> defines the std::vector class, so you need to include it some where in your file.

since you’re using vector, you need to instruct the compiler that you’re going to import the whole std namespace (arguably this is not something you want to do), via using namespace std;

Otherwise vector should be defined as std::vector<myclass>

answered Jun 11, 2010 at 22:06

Alan's user avatar

try std::vector<odp> or using std;

answered Jun 11, 2010 at 22:06

TreDubZedd's user avatar

TreDubZeddTreDubZedd

2,5711 gold badge15 silver badges20 bronze badges

On its own, that snippet of code has no definition of bar, vector or odp. As to why you’re not getting an error about the definition of bar, I can only assume that you’ve taken it out of context.

I assume that it is supposed to define foo as a function, that vector names a template and that it is supposed to define a parameter called ftw but in a declaration anything that is not actually being defined needs to have been declared previously so that the compiler knows what all the other identifiers mean.

For example, if you define new types as follows you get a snippet that will compile:

struct bar {};
struct odp {};
template<class T> struct vector {};

bar foo(vector<odp> ftw);

answered Jun 11, 2010 at 22:07

CB Bailey's user avatar

CB BaileyCB Bailey

757k105 gold badges633 silver badges656 bronze badges

Синтаксическая ошибка: идентификатор «Player». Файл mob.h ст 40
Гуглить пробовал. Ответ так и не нашел

player.h:

#pragma once
#include "Weapon.h"
#include "Mob.h"

class Player
{
public:
	int health, armor, exp, mana;
	int currentHealth, currentArmor, currentMana, toNextLvlExp, balance;
	int missChanceBody, missChanceHead, missChanceLegs;

	Weapon sword;
	Weapon magicStick;

	Player(int _health, int _armor, const Weapon& _sword, const Weapon& _magicStick);
	int takePhysicalDamage(Mob& m);
};

mob.h:

#pragma once
#include <string>
#include "Player.h"

using namespace std;

class Mob
{
public:
	enum mobType {
		PHYSIC,
		MAGIC
	};

	enum attackDir {
		HEAD,
		BODY,
		LEGS
	};

	int health, armor, magicResistance, shockResistance;
	int currentHealth, damage, spreadDamage;
	string name;
	mobType attackType;

	

	/**
	 * Конструктор класса Mob.
	 * Принимает 3 аргумента
	 * _health - здоровье моба
	 * _magicResistance - защита от магического урона
	 * _shockResistance - защита от физического урона
	 * _damage - урон
	 * _spreadDamage - Разброс урона
	 * _name - Имя моба
	 * type - тип атаки моба
	 */
	Mob(int _health, int _magicResistance, int _shockResistance, int _damage, int _spreadDamage, string _name, mobType type);
	int takePhysicalDamage(Player* player, attackDir dir);
	int takeMagicalDamage(Player* player, attackDir dir);
};

I hate to post something so subtle, but this has me completely stumped on what I am doing wrong:
When I compile, it’s not liking Class Simulator at all. I get the error

syntax error : identifier 'Simulator'

at every instance of Simulator I use inside the DOCO header file. It also does this for my Pellet struct. The code was working completely fine until I started adding functions that work with the Simulator class inside DOCO.h.
The Simulator class uses the DOCO struct and the DOCO struct is using class Simulator. Is that a problem? Maybe I used included my headers wrong?

Here is a link to the error I get if it helps: http://msdn.microsoft.com/en-us/library/yha416c7.aspx

#include <iostream>
#include <conio.h>
#include <string>
#include "Simulator.h"   //<---Has a chain of includes for other header files
int main()
{
    RandomNumberGen R;
    Simulator S;
    Pellet P;
    DOCO D;

    system("pause");
    return 0;
}

Header Files:
Simulator.h

#pragma once
#include <iostream>
#include <stdio.h>
//#include <conio.h>
#include <vector>
#include "Pellet.h"
#include "DataParser.h"
#include "DOCO.h"
#include "RandomNumberGen.h"
#include "Cell.h"
#include "Timer.h"

using namespace std;

class Simulator
{
private:
    int s_iDocoTotal;
    int s_iPelletTotal;
    int s_iGridXComponent;
    int s_iGridYComponent;
    int tempX;
    int tempY;

    //Pellet P;
    //DOCO D;


    static const unsigned int s_iNumOfDir=8;


public:
    Simulator();
    ~Simulator();

    //int GenerateDirection();
    void InitiateDOCO(RandomNumberGen *R, DOCO *D, vector<DOCO>&);  //
    void SpreadFood(RandomNumberGen *R, Pellet *P, vector<Pellet>&, const int x, const int y);      //
    void AddPellet(Pellet *P, RandomNumberGen *R);          //
    void CheckClipping(Pellet *P, RandomNumberGen *R);      //
    void CheckPellets(Pellet *P, RandomNumberGen *R);       //
    void CreateGrid(int x, int y);//
    int GetGridXComponent();    //
    int GetGridYComponent();    //
    int GetDocoTotal();
    vector<DOCO> docoList;                  //Holds the Doco coordinates
    vector<Pellet> pelletList;              //!!Dont use this!! For data import only
    vector<vector<int> > pelletGrid;    //Holds X-Y and pellet count
    char **dataGrid;        //Actual array that shows where units are

    Simulator(const int x, const int y) : 
                s_iGridXComponent(x), 
                s_iGridYComponent(y),
                pelletGrid(x, vector<int>(y)){}
};

DOCO.h

#pragma once
#include <iostream>
#include <stdio.h>
#include <vector>
#include "Simulator.h"
//#include "DataParser.h"



using namespace std;

struct DOCO
{
private:
    int d_iXLocation;
    int d_iYLocation;
    int d_iEnergy;
    int d_iMovement;
    int d_iTemp;
    //Simulator S;
    //RandomNumberGen R;
    //Pellet P;
    enum Direction { NORTH, SOUTH, EAST, WEST, NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST};


public:
    DOCO();
    ~DOCO();
    //int a is the position in docoList to reference DOCO
    int GoNorth(Simulator *S, int a);
    int GoSouth(Simulator *S, int a);
    int GoEast(Simulator *S, int a);
    int GoWest(Simulator *S, int a);
    int GoNorthWest(Simulator *S, int a);
    int GoNorthEast(Simulator *S, int a);
    int GoSouthWest(Simulator *S, int a);
    int GoSouthEast(Simulator *S, int a);

    //int a is the position in docoList to reference DOCO
    void Sniff(Simulator *S, RandomNumberGen *R, int a);        //Detects DOCOs and food
    void Reroute(Simulator *S, RandomNumberGen *R, int a);  //Changes DOCO direction
    void SetDOCO(int tempX, int tempY, int tempEnergy, int tempMovement);
    int GetEnergy();    //
    int SetEnergy();
    int SetMovement();
    int GetMovement();  //
    int GetXLocation(); //
    int GetYLocation(); //
    void SetXLocation(int d_iTemp);
    void SetYLocation(int d_iTemp);
    void EatPellet(Pellet *P, Simulator *S, int a);//ADD DOCO ARGUMENT / DONT OVERLAP DOCO AND PELLETS
    void MoveDoco(Simulator *S, int a);
    void Death();
};
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#include <iostream>
using namespace std;
 
class book
{
private:
 
    char *author;
    char *title;
    char *publishing;
    unsigned int year;
    int num_pages;
 
public:
    book():author(NULL),title(NULL),publishing(NULL),year(0),num_pages(0){}
    book(char *cur_author
        , char *cur_title
        , char *cur_publishing
        , unsigned int cur_year
        , int cur_num_pages);
 
    void set_author(char *cur_author);
    void set_title(char *cur_title);
    void set_publishing(char *cur_publishing);
    void set_year(unsigned int cur_year);
    void set_num_pages(int cur_num_pages);
    void board();
    
    char *get_author();
    char *get_title();
    char *get_publishing();
    unsigned int get_year();
    int get_num_pages();
 
    ~book();
};
class search
{
private:
    book *arr;
    int n;
public:
    search(int n);
    void book_spisok(int n, char author);
    void book_npublishing();
    void book_year(unsigned int year);
    ~search();
};
 
book :: ~book()
{
    delete[]author;
    delete[]title;
    delete[]publishing;
}
book::book(char *cur_author
    , char *cur_title
    , char *cur_publishing
    , unsigned int cur_year
    , int cur_num_pages)
    : num_pages(cur_num_pages),
    year(cur_year)
 
{
    author = new char[strlen(cur_author) + 1];
    strcpy(book::author, cur_author);
    title = new char[strlen(cur_title) + 1];
    strcpy(book::title, cur_title);
    publishing = new char[strlen(cur_publishing) + 1];
    strcpy(book::publishing, cur_publishing);
    this -> year = cur_year;
    this ->num_pages = cur_num_pages;
}
void book::set_author(char *au)
{
    delete[] author;
    author = new char[strlen(au) + 1];
    strcpy(book::author, au);
}
void book::set_title(char *tl)
{
    delete[] title;
    title = new char[strlen(tl) + 1];
    strcpy(book::title, tl);
}
void book::set_publishing(char *ph)
{
    delete[] publishing;
    publishing = new char[strlen(ph) + 1];
    strcpy(book::publishing, ph);
}
void book::set_year(unsigned int yr)
{
    this -> year = yr;
}
void book::set_num_pages(int num)
{
    this -> num_pages = num;
}
char *book :: get_author()
{
    return this -> author;
}
char *book :: get_title()
{
    return this-> title;
}
char *book :: get_publishing()
{
    return this-> publishing;
}
unsigned int book :: get_year()
{
    return this-> year;
}
int book :: get_num_pages()
{
    return this-> num_pages;
}
 
void book::board()
{
    printf("nn Author - %s; Title - %s; Publishing - %s;n Year - %i. Number os pages - %inn", author, title, publishing, year, num_pages);
}
 
search::search(int n)
{
    this -> n = n;
    char *authors[] = { "Koval", "Baden", "Kranchenko", "Finiak", "Abakumov", "Sorokin", "Savchenko", "Podgorniy" };
    char *publishings[] = { "Bogdan", "LAZ", "Mersedes", "Volvo", "TATA" };
    char *titles[] = { "Koval", "Baden", "Kranchenko", "Finiak", "Abakumov", "Sorokin", "Savchenko", "Podgorniy" };
    arr = new book [n];
 
    for (int i = 0; i<n; i++)
    {
        arr[i].set_author(authors[rand() % 8]);
        arr[i].set_publishing(publishings[rand() % 5]);
        arr[i].set_title(titles[rand() % 8]);
        arr[i].set_year(rand() % 27 + 1987);
        arr[i].set_num_pages(rand() % 10 + 100);
        arr[i].board();
        cout << endl;
    }
}
void search::book_year(unsigned int year)
{
    int k = 0;
    for (int i = 0; i < n; i++)
    {
        if (arr[i].get_year() > year)
        {
            cout << endl << "year >  " << arr[i].get_title() << endl;
            k++;
        }
    }
    if (!k)
        cout << endl << "" << endl;
}
 
search::~search()
{
    delete[]arr;
}
 
int main()
{
    setlocale(LC_ALL,"Rus");
    int n, year;
    cout << "Количество книг: ";
    cin >> n;
    if (n > 0)
    {
        search massive(n);
        cout << "Год: ";
        cin >> year;
        massive.book_year(n);
    }
    else
        cout << "Введено неверное число книгn";
    system("pause");
    return 0;
 
}

Я пытаюсь изучать C ++, однако, параметр метода, который у меня есть в моем собственном классе, ведет себя неправильно. Когда он использует dataType типа int, он отлично работает без ошибок, но когда я пытаюсь изменить его на «string» dataType, программа вылетает с этой ошибкой.

Ошибка 1 ошибка C2061: синтаксическая ошибка: идентификатор ‘строка’ в файле temp.h ln
8 цв 1

Я использую следующие классы:

РАБОЧИЙ КОД
TesterClass.cpp // Точка входа

#include "stdafx.h"#include "Temp.h"
int _tmain(int argc, _TCHAR* argv[])
{
Temp tmp;
tmp.doSomething(7);
return 0;
}

Temp.h

#pragma once
class Temp
{
public:
Temp();
void doSomething(int blah);
};

Temp.cpp

#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>
using std::string;
Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}
void Temp::doSomething(int blah)
{
std::cout << blah;
}

Сломанный код
Temp.h

#pragma once
class Temp
{
public:
Temp();
void doSomething(string blah);
};

Temp.cpp

#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>
using std::string;
Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}
void Temp::doSomething(string blah)
{
std::cout << blah;
}

Когда я настраиваю параметр «blah» на строку, как в файле .h, так и в файле .cpp, возникает проблема.

Я огляделся, но ни один из ответов, похоже, не решил мою проблему. Я очень хотел бы помочь в этом, я вне идей. Я попытался переустановить C ++, возиться с:

using namepace std;
using std::string;
std::string instead of string
etc.

Если вы знаете, как решить мою проблему, я хотел бы услышать от вас. Я более чем рад предоставить больше информации.

-3

Решение

C ++ выполняет однопроходную компиляцию, поэтому std :: string необходимо объявить перед тем, как использовать его вообще — в том числе в заголовочном файле.

// Temp.h
#pragma once
#include <string>
class Temp
{
public:
Temp();
void doSomething(std::string blah);
};

Я бы посоветовал вам быть более точным в ваших заголовочных файлах при указании таких классов, потому что вы можете легко встретить другую библиотеку, которая определяет свою собственную string и тогда вы столкнетесь с конфликтами имен. Спасти using импортировать операторы для ваших файлов cpp.

0

Другие решения

У πάντα ῥεῖ был письменный ответ, спасибо!

Они сказали использовать std :: string при необходимости, а также #include <string> в заголовочном файле.

0

Lol_KekCheburek

0 / 0 / 0

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

Сообщений: 16

1

Передача вектора в функцию

12.02.2018, 15:30. Показов 3273. Ответов 6

Метки нет (Все метки)


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

Как правильно передавать вектор в функцию?
Опускаю подробности его инициализации, проблема в передачи в функцию.
Выводит ошибки:
1) Ошибка C2061 синтаксическая ошибка: идентификатор «vector»
2) Ошибка C2660 sort: функция не принимает 2 аргументов

Bash
1
2
3
4
5
6
7
8
9
10
void sort(int num, vector<int>& answer);
int main{
vector<int> answer;
sort(index[j], answer);
//index[j] элемент, который нужно вставить в возрастающую последовательность, которая находится в векторе
}
 
void sort(int num, vector<int>& answer){
   //происходит сортировка
}

0

Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

12.02.2018, 15:30

Ответы с готовыми решениями:

Передача вектора в функцию
вот например функция

void f(vector &lt;int&gt; v)
{
cout &lt;&lt; v.size();
}

в нее нужно передать…

Передача вектора в функцию
Сабж.
В главной программе есть структура:
struct Complex
{
double Re;
double Im;
} com;
и…

Передача вектора в функцию.
Сабж.

#include &lt;iostream&gt;
#include &lt;vector.h&gt;

void show (); // ?

int main ()
{

Передача вектора в функцию
void foo(vector&lt;int&gt; x)
{
//Тело функции
}

void foo(vector&lt;int&gt; &amp;x)
{
//Тело функции
}…

6

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

12.02.2018, 15:35

2

Lol_KekCheburek, на первый взгляд всё хорошо, только где std::? Нужно больше кода! (отсылка к Warcraft III)

0

Lol_KekCheburek

0 / 0 / 0

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

Сообщений: 16

12.02.2018, 15:41

 [ТС]

3

Цитата
Сообщение от outoftime
Посмотреть сообщение

на первый взгляд всё хорошо, только где std::? Нужно больше кода! (отсылка к Warcraft III)

В коде прописано using namespace std;

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

Цитата
Сообщение от outoftime
Посмотреть сообщение

на первый взгляд всё хорошо, только где std::? Нужно больше кода! (отсылка к Warcraft III)

Весь код. Задача отсортировать книг. В файле Books номера и название книги, я сортирую номера.

Bash
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
 
 
void sort(int num, vector<int>& answer);
 
using namespace std;
 
struct Books {
    int number;
    string name;
 
    Books(const int& n, const string& s) {
        number = n;
        name = s;
    }
};
 
int main()
{
    setlocale(LC_ALL, "rus");
 
    vector<Books> obj;
 
    std::ifstream listBooks("Books.txt");
 
    //check
    if (!listBooks.is_open()) {
        std::cout << "File is not found";
        exit(0);
    }
 
    int count = 0;
    while (!listBooks.eof()) {
 
        string s; int n;
        listBooks >> n;
        getline(listBooks, s);
        obj.push_back(Books(n, s));
        count++;
    }
 
    listBooks.close();
 
    int* b = new int[count];
    int* cof = new int[count];
 
    for (int i = 0; i < count; i++) {
        b[i] = 1; 
    }
 
    
    for (int i = 1; i < count; i++) {
        for (int j = 0; j < i; j++) {
            if (obj[j].number < obj[i].number && 1+b[j] > b[i]) {
                b[i] = b[j] + 1;
                cof[i] = j;
            }
        }
    }
    
    int lastPos = 0; int lenght = b[0];
 
    for (int i = 0; i < count; i++) {
        if (b[i] > lenght) {
            lastPos = i;
            lenght = b[i];
        }
    }
 
    int* index = new int[lenght];
    int* ans = new int[lenght];
    vector<int> answer;
 
 
    for (int i = lenght - 1; i >= 0; i--) {
        index[i] = lastPos;
        answer.push_back(obj[lastPos].number);
        lastPos = cof[lastPos];
 
    }
    reverse(answer.begin(), answer.end())//reverse vector
 
    for (int i = 0; i < answer.size(); i++)
        cout << answer[i] << " ";
 
    cout << endl;
 
    int i = 0;
    for (int j = 0; j<count; j++) {
        if (i<lenght) {
            for (; i<index[j]; i++) {
                sort(index[j], answer);
                //подкрасить obj[mas[j]].nubmer и также название
                //подкрасить в измененном списке answer[change]
            }
        }
        else
            sort(index[j], answer);
    }
 
 
    for (int i = 0; i < answer.size(); i++) {
        std::cout << answer[i] << " ";
    }
    
}
 
void sort(int num, vector<int>& answer) { 
    if (answer[0]>num) {
        int k;
        for (int i = 0; i < answer.size(); i++) {
             k = answer[i];
            answer[i] = k;
        }
        answer.push_back(k);
    }
    if (answer[answer.size() - 1] < num) {
        answer.push_back(num);
    }
 
    int i = answer.size() / 2; int upBord = answer.size();
    while (true) {
        if ((num<answer[i] && num>answer[i - 1]))
            answer.insert(answer.begin()+i-1, num);
        if (num > answer[i]) {
            i += (upBord - i) / 2;
            upBord = i;
        }
        if (num < answer[i])
            i /= 2;
    }
}

0

outoftime

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

12.02.2018, 15:47

4

Лучший ответ Сообщение было отмечено Lol_KekCheburek как решение

Решение

Lol_KekCheburek, может хотябы ту строчку на которую указывает ошибка покажете?

Добавлено через 1 минуту
Lol_KekCheburek, когда вставляете код Bash сверху нету кнопки «Выделить весь код», неудобно, пользуйтесь «С++» 2й ряд слева крайняя

Добавлено через 2 минуты
Lol_KekCheburek,

reverse(answer.begin(), answer.end()); //reverse vector

Заголовочный файл <algorithm>
http://ru.cppreference.com/w/cpp/algorithm/reverse

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

C++
1
2
3
void sort(int num, vector<int> &answer);
 
using namespace std;

Порядок не тот.

0

Lol_KekCheburek

0 / 0 / 0

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

Сообщений: 16

12.02.2018, 15:47

 [ТС]

5

Цитата
Сообщение от outoftime
Посмотреть сообщение

может хотябы ту строчку на которую указывает ошибка покажете?

1 ошибка:

Bash
1
void sort(int num, vector<int>& answer);

2 ошибка:

Bash
1
sort(index[j], answer);

3 ошибка:

Bash
1
sort(index[j], answer);

0

outoftime

║XLR8║

1212 / 909 / 270

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

Сообщений: 4,361

Записей в блоге: 5

12.02.2018, 15:48

6

C++
1
    int *ans = new int[lenght];

Не используется

0

0 / 0 / 0

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

Сообщений: 16

12.02.2018, 15:51

 [ТС]

7

Цитата
Сообщение от outoftime
Посмотреть сообщение

Порядок не тот.

Благодарю, все заработало

0

Avatar of shaolinfunk

shaolinfunk

Flag for United States of America asked on 4/15/2010

In one of my old projects I use vectors and simply needed to use include like this:

#include <vector>

Now i’m trying to insert my old code into someone else’s project which likely is a different type of project (not sure which or how to find out).  While both projects are in C++ my old code that uses vectors now generates this error C2061: syntax error : identifier ‘vector’ in his project.

How do I get rid of this?  Thanks.

C++

Avatar of undefined

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

View this solution by signing up for a free trial.

Members can start a

7-Day free trial

and enjoy unlimited access to the platform.

weird..putting using namespace std generates more errors…why is that?

but prefixing vector with std:: does the trick.

thanks for fast response evil!

>> weird..putting using namespace std generates more errors…why is that?
It imports the std namespace into the current one. If you have other symbols with names that clash with those in the std namespace you’ll get errors.

>> but prefixing vector with std:: does the trick.
What would have been my preferred solutions. I never import the std namespace, I always use fully qualified names for standard library items.

What’s wrong with this line of code?

bar foo(vector ftw);

It produces

error C2061: syntax error: identifier 'vector'

bdonlan's user avatar

bdonlan

220k29 gold badges264 silver badges321 bronze badges

asked Jun 11, 2010 at 22:04

Nick Heiner's user avatar

Nick HeinerNick Heiner

117k183 gold badges472 silver badges696 bronze badges

try std::vector instead. Also, make sure you

#include <vector>

answered Jun 11, 2010 at 22:06

Adrian Grigore's user avatar

Adrian GrigoreAdrian Grigore

32.8k36 gold badges130 silver badges209 bronze badges

Probably you forgot to include vector and/or import std::vector into the namespace.

Make sure you have:

#include <vector>

Then add:

using std::vector;

or just use:

bar foo(std::vector<odp> ftw);

answered Jun 11, 2010 at 22:06

Matthew Flaschen's user avatar

Matthew FlaschenMatthew Flaschen

274k50 gold badges513 silver badges537 bronze badges

1

Do you have:

#include <vector>

and

using namespace std; in your code?

<vector> defines the std::vector class, so you need to include it some where in your file.

since you’re using vector, you need to instruct the compiler that you’re going to import the whole std namespace (arguably this is not something you want to do), via using namespace std;

Otherwise vector should be defined as std::vector<myclass>

answered Jun 11, 2010 at 22:06

Alan's user avatar

try std::vector<odp> or using std;

answered Jun 11, 2010 at 22:06

TreDubZedd's user avatar

TreDubZeddTreDubZedd

2,5311 gold badge15 silver badges19 bronze badges

On its own, that snippet of code has no definition of bar, vector or odp. As to why you’re not getting an error about the definition of bar, I can only assume that you’ve taken it out of context.

I assume that it is supposed to define foo as a function, that vector names a template and that it is supposed to define a parameter called ftw but in a declaration anything that is not actually being defined needs to have been declared previously so that the compiler knows what all the other identifiers mean.

For example, if you define new types as follows you get a snippet that will compile:

struct bar {};
struct odp {};
template<class T> struct vector {};

bar foo(vector<odp> ftw);

answered Jun 11, 2010 at 22:07

CB Bailey's user avatar

CB BaileyCB Bailey

732k101 gold badges625 silver badges651 bronze badges

  • Remove From My Forums
  • Question

  • HI, thanks for the help.

    I can’t use ‘vector’ in cli at all. I would like to make a vector of classes. I have the following code:

    #include<cliextvector>

    static vector<CEntry^>^ entry = gcnew vector<CEntry^>();

    I get missing ‘;’ before ‘<‘ and missing type specifer — int assumed. Can you please help?

    Thank you very much.

Answers

  • It’s in the cliext namespace:

    static cliext::vector<CEntry^>^ entry =
      gcnew cliext::vector<CEntry^>();

     
    — Wayne

    • Marked as answer by

      Wednesday, March 23, 2011 10:30 PM

  • Remove From My Forums
  • Question

  • HI, thanks for the help.

    I can’t use ‘vector’ in cli at all. I would like to make a vector of classes. I have the following code:

    #include<cliextvector>

    static vector<CEntry^>^ entry = gcnew vector<CEntry^>();

    I get missing ‘;’ before ‘<‘ and missing type specifer — int assumed. Can you please help?

    Thank you very much.

Answers

  • It’s in the cliext namespace:

    static cliext::vector<CEntry^>^ entry =
      gcnew cliext::vector<CEntry^>();

     
    — Wayne

    • Marked as answer by

      Wednesday, March 23, 2011 10:30 PM

I am having a C2061 error on the private methods on my classifier.h file. As you can see, I have #include vector, and i am using it for a public struct. Can someone please help me understand what I am overlooking?

#ifndef CLASSIFIER_H
#define CLASSIFIER_H

#include "patient_data.h"
#include <QObject>
#include <vector>
#include <stdlib.h>

class Classifier : public QObject
{
    Q_OBJECT
public:
    explicit Classifier(QObject *parent = 0);
    ~Classifier();
    void classify(std::vector<patient_data>data, patient_data i);


    struct CreateSDTable
    {
        std::vector<int>sum[3];   //element 0 = Tumor, element 1 = Stage, element 2 = Adjuvant
        std::vector<long>mean[3];
        std::vector<long>error[3];
        std::vector<long>SDL[3];
        std::vector<long>SD[3];
    };

    CreateSDTable CurrentvsNeutropenic;
    CreateSDTable CurrentvsNonNeutropenic;


private:

    std::vector<int> calculatesums(vector<patient_data> data, patient_data i, Neutropenic n);
    std::vector<long> calculatemean(vector<int>validpatients, CreateSDTable Neut, CreateSDTable NonNeut);
    std::vector<long>calculateerror(patient_data d, vector<int>m);
    std::vector<long>calculatSDL(int nvp, CreateSDTable CVN, CreateSDTable CVsNN);
    int NumofValidPatients(patient_data x);

I am having a C2061 error on the private methods on my classifier.h file. As you can see, I have #include vector, and i am using it for a public struct. Can someone please help me understand what I am overlooking?

#ifndef CLASSIFIER_H
#define CLASSIFIER_H

#include "patient_data.h"
#include <QObject>
#include <vector>
#include <stdlib.h>

class Classifier : public QObject
{
    Q_OBJECT
public:
    explicit Classifier(QObject *parent = 0);
    ~Classifier();
    void classify(std::vector<patient_data>data, patient_data i);


    struct CreateSDTable
    {
        std::vector<int>sum[3];   //element 0 = Tumor, element 1 = Stage, element 2 = Adjuvant
        std::vector<long>mean[3];
        std::vector<long>error[3];
        std::vector<long>SDL[3];
        std::vector<long>SD[3];
    };

    CreateSDTable CurrentvsNeutropenic;
    CreateSDTable CurrentvsNonNeutropenic;


private:

    std::vector<int> calculatesums(vector<patient_data> data, patient_data i, Neutropenic n);
    std::vector<long> calculatemean(vector<int>validpatients, CreateSDTable Neut, CreateSDTable NonNeut);
    std::vector<long>calculateerror(patient_data d, vector<int>m);
    std::vector<long>calculatSDL(int nvp, CreateSDTable CVN, CreateSDTable CVsNN);
    int NumofValidPatients(patient_data x);

I am having a C2061 error on the private methods on my classifier.h file. As you can see, I have #include vector, and i am using it for a public struct. Can someone please help me understand what I am overlooking?

#ifndef CLASSIFIER_H
#define CLASSIFIER_H

#include "patient_data.h"
#include <QObject>
#include <vector>
#include <stdlib.h>

class Classifier : public QObject
{
    Q_OBJECT
public:
    explicit Classifier(QObject *parent = 0);
    ~Classifier();
    void classify(std::vector<patient_data>data, patient_data i);


    struct CreateSDTable
    {
        std::vector<int>sum[3];   //element 0 = Tumor, element 1 = Stage, element 2 = Adjuvant
        std::vector<long>mean[3];
        std::vector<long>error[3];
        std::vector<long>SDL[3];
        std::vector<long>SD[3];
    };

    CreateSDTable CurrentvsNeutropenic;
    CreateSDTable CurrentvsNonNeutropenic;


private:

    std::vector<int> calculatesums(vector<patient_data> data, patient_data i, Neutropenic n);
    std::vector<long> calculatemean(vector<int>validpatients, CreateSDTable Neut, CreateSDTable NonNeut);
    std::vector<long>calculateerror(patient_data d, vector<int>m);
    std::vector<long>calculatSDL(int nvp, CreateSDTable CVN, CreateSDTable CVsNN);
    int NumofValidPatients(patient_data x);

asked Dec 5, 2014 at 19:43

user3255175's user avatar

6

Load 7 more related questions

Show fewer related questions

Понравилась статья? Поделить с друзьями:
  • Синтаксическая ошибка ожидается операнд неверный маркер bash
  • Синтаксическая ошибка идентификатор tchar
  • Синтаксическая ошибка непредвиденный токен требуется объявление
  • Синтаксическая ошибка идентификатор form1
  • Синтаксическая ошибка идентификатор file