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

Lol_KekCheburek

0 / 0 / 0

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

Сообщений: 16

1

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

12.02.2018, 15:30. Показов 3340. Ответов 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



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

223k30 gold badges266 silver badges323 bronze badges

asked Jun 11, 2010 at 22:04

Nick Heiner's user avatar

Nick HeinerNick Heiner

118k187 gold badges474 silver badges698 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

277k50 gold badges513 silver badges538 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,5511 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

746k102 gold badges631 silver badges655 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

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);

Сам по себе этот фрагмент кода не имеет определения bar, vector или odp. Что касается того, почему вы не получаете ошибку об определении bar, я могу только предположить, что вы выбрали ее из контекста.

Я предполагаю, что он должен определять foo как функцию, что vector называет шаблон и что он должен определять параметр с именем ftw, но в декларации ничего, что на самом деле не определено чтобы быть объявленным ранее, чтобы компилятор знал, что означают все другие идентификаторы.

Например, если вы определяете новые типы следующим образом, вы получите фрагмент, который будет компилироваться:

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

bar foo(vector<odp> ftw);

Понравилась статья? Поделить с друзьями:
  • Синтаксическая ошибка идентификатор tchar
  • Синтаксическая ошибка при установке whatsapp
  • Синтаксическая ошибка идентификатор string
  • Синтаксическая ошибка при установке rustore
  • Синтаксическая ошибка идентификатор ifstream