Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
Другие темы раздела
C++ Добавить функцию https://www.cyberforum.ru/ cpp-beginners/ thread986247.html
Необходимо добавить функцию которая бы выводила на экран все не терминальные вершины дерева, которые больше чем заданное из клавиатуры число # include <iostream> # include <conio.h> # include <locale.h> using namespace std; struct node
C++ Столбцы в матрице
Помогите пожалуйста написать программу на C++: в матрице поменять местами столбцы, содержащие максимальный и минимальный элементы
C++ Прокомментировать код https://www.cyberforum.ru/ cpp-beginners/ thread986231.html
#include "stdafx.h" #include<iostream> #include<math.h> #include <stdlib.h> using namespace std; int main() { double eps, x, n; int count = 0, i = 0;
C++ Как правильно составить блок-схемму https://www.cyberforum.ru/ cpp-beginners/ thread986229.html
#include <stdio.h> #include <conio.h> #include <math.h> #include <locale> #define N 50 void main() { setlocale(2,""); int n, m, i, j, error;
Не правильно считает программа C++
Чем больше ввожу столетие, тем меньше пятниц 13 получается. #include <stdio.h> #include <conio.h> #include <math.h> int m,y,c,s,n=0; int main() { printf("'\nVvedite ctoletie\n"); scanf("%d",&c);
C++ Матрица https://www.cyberforum.ru/ cpp-beginners/ thread986211.html
Привет. Ребята помогите переделать код под borland c++ 3.1 #include <iostream> #include <conio.h> const int M = 3; const int N = 4; int main( void ) { using std::cout;
C++ Найти значение функции Помогите сделать лабораторную работу по циклам. Самым простым способ. Заранее благодарен! https://www.cyberforum.ru/ cpp-beginners/ thread986208.html C++ вычислить сумму всех составных чисел от 1 до М
вычислить сумму всех составных чисел от 1 до М.Составные числа можно представить в виде произвидения нескольких простых чисел
C++ Численное дифференцирование (Лагранж) Доброго времени суток, нужно написать программу которая будет диференцировать интерполяционный многочлен Лагранжа (n=4). Как бы все казалось не сложно, но увы. Интерполяцию ейткена вроде как помогли написать, но не уверен что правильно #include <iostream> #include <conio.h> #include <stdio.h> using namespace std; int main () { system("COLOR 0A"); double ob, x1 , x2 , y1 , y2, p1 , p2... https://www.cyberforum.ru/ cpp-beginners/ thread986198.html C++ Реализация классов. Конструкторы и деструкторы https://www.cyberforum.ru/ cpp-beginners/ thread986195.html
Создать класс, характеризующий абитуриента: фамилия, имя, отчество, оценки из трех вступительных экзаменов (математика, физика, язык). Вроде правильно, а код не работает: #include<string.h> #include <iostream> #include <conio.h> using namespace std; class Applicant { private: string applicant_name;
C++ STL и полиморфизм
Доброго времени суток! Исходная информация: класс а-базовый,b-производный у этих ребят определён виртуальный метод(для класса "a" возрачает-1,для "b"-2); class a { public: virtual int To() { return 1; } };
C++ Написать функцию, что определяет , может ли квадрат данного числа быть равен сумме квадратов других чисел, и возвращает эти числа Написать функцию, что определяет , может ли квадрат данного числа быть равен сумме квадратов других чисел, и возвращает эти числа https://www.cyberforum.ru/ cpp-beginners/ thread986186.html
2 / 2 / 1
Регистрация: 23.10.2013
Сообщений: 38
0

Vector subscript out of range (push_back, a не []) - C++ - Ответ 5226975

23.10.2013, 23:26. Показов 2635. Ответов 15
Метки (Все метки)

Author24 — интернет-сервис помощи студентам
При попытке сделать push_back() вектору вылетает ошибка vector subscript out of range. Именно при пуше, не при операторе []. Ошибка в конструкторе Population (где именно обозначил). Ее там быть не должно, как я знаю. 2 заголовочных, 3 .сpp
ЗЫ. Программа моделирует работу Генетического Алгоритма.
Код под спойлером
Кликните здесь для просмотра всего текста
MAIN__CPP
Кликните здесь для просмотра всего текста
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
#include <iostream>
#include <time.h>
#include "Individual.h"
#include "Population.h"
 
using namespace std;
 
int main(){
    int numberOfCPU=3;
    int numberOfTasks=13;
    int leftb=4,rightb=20;
    int s=10;
    int stop=60;
    int prPair=60;
    int prMut=20;
    int *cpuload=new int[numberOfCPU];
    int *task=new int[numberOfTasks];
    for(int i=0;i<numberOfTasks;i++){
            task[i]=rand()%(rightb-leftb+1)+leftb;
    }
 
 
 
    Population population(s,task,numberOfCPU,numberOfTasks, prPair, prMut, stop);
    population.showPopulation();
 
    system("pause");
    return 0;
}

INDIVIDUAL__H
Кликните здесь для просмотра всего текста
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
#include <vector>
#ifndef INDIVDUAL_H
#define INDIVDUAL_H
using namespace std;
 
class Population;
 
class Individual{
    friend class Population;
 
    static int numberOfcpu;
    static short int DNAL;//number of Tasks in that Ind.
    static vector<int> task;//vector with weights of tasks                          ALL
    
    vector<unsigned char> gene;//                                                   VECTORS     
    vector<int> cpuNumber;//contains CPU number. CPU numeration begin from Zero     SAME SIZE
    
    int res;//max. time; objective function result
    vector<int> cpuResult;
    int indNumber; //number in population
public:
    Individual(int* _tasks, int numberOfTasks, int numberOfProc, int number);
    Individual(int number);
    Individual(const Individual&);
    int ObjectFunction();
    void showFullInfo();
    void showInfo();
    void reFindResult();//recalculate result of ObjFunc
    void calcCpuResults();//recalculate cpu result's
 
    static void swap(Individual a,Individual b);//swap data. (for pairing)
};
 
#endif

INDIVIDUAL__CPP
Кликните здесь для просмотра всего текста
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
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
#include <vector>
#include <iostream>
#include <time.h>
#include <iomanip>
#include "Individual.h"
using namespace std;
 
int Individual::numberOfcpu;
short int Individual::DNAL;
vector<int> Individual::task;
 
Individual::Individual(int* _tasks, int numberOfTasks, int numberOfProc, int number){
    indNumber=number;
    numberOfcpu=numberOfProc;
    DNAL=numberOfTasks;
    for(int i=0;i<DNAL;i++){
        task.push_back(_tasks[i]);
        gene.push_back(static_cast<unsigned char>(rand()%256));
    }
 
    int step=256/numberOfProc;
    
    for(int i=0;i<DNAL;i++){
        if(gene[i]%step==0){
            cpuNumber.push_back((gene[i]/step)-1);
        }
        else cpuNumber.push_back(gene[i]/step);
    }
    for(int i=0;i<numberOfcpu;i++){
        cpuResult.push_back(0);
    }
    for(int i=0;i<DNAL;i++){
        cpuResult[cpuNumber[i]]+=task[i];
    }
 
    res=cpuResult[0];
    for(int i=1;i<numberOfProc;i++){
        if(res<cpuResult[i])res=cpuResult[i];
    }
}
Individual::Individual(int number){
    indNumber=number;
    int step=256/numberOfcpu;
 
    for(int i=0;i<DNAL;i++){
        gene.push_back(static_cast<unsigned char>(rand()%256));
        if(gene[i]%step==0){
            cpuNumber.push_back((gene[i]/step)-1);
        }
        else cpuNumber.push_back(gene[i]/step);
    }
    for(int i=0;i<numberOfcpu;i++){
        cpuResult.push_back(0);
    }
    for(int i=0;i<DNAL;i++){
        cpuResult[cpuNumber[i]]+=task[i];
    }
 
    res=cpuResult[0];
    for(int i=1;i<numberOfcpu;i++){
        if(res<cpuResult[i])res=cpuResult[i];
    }
}
Individual::Individual(const Individual& p){
    for(int i=0;i<DNAL;i++){
        gene[i]=p.gene[i];
        cpuNumber[i]=p.gene[i];
    }
    res=p.res;
    for(int i=0;i<numberOfcpu;i++){
        cpuResult[i]=p.cpuNumber[i];
    }
}
void Individual::swap(Individual a,Individual b){
    for(int i=0;i<DNAL;i++){
        swap(a.gene[i],b.gene[i]);
        swap(a.cpuNumber[i],b.cpuNumber[i]);
    }
    a.calcCpuResults();
    a.reFindResult();
    b.calcCpuResults();
    b.reFindResult();
}
 
void Individual::showFullInfo(){
    cout<<"Individual's number: "<<indNumber<<endl;
    cout<<"Number of Processors & Tasks: "<<numberOfcpu<<" & "<<DNAL<<endl;
    cout<<"Length of DNA: "<<DNAL<<endl;
    for(int j=0;j<4;j++){
        switch(j){
        case 0:
            cout<<setw(7)<<"Number:";
            for(int i=0;i<DNAL;i++){
                cout<<setw(4)<<i;
            }
            cout<<endl;
            break;
        case 1:
            cout<<setw(7)<<"Weight:";
            for(int i=0;i<DNAL;i++){
                cout<<setw(4)<<task.at(i);
            }
            cout<<endl;
            break;
        case 2:
            cout<<setw(7)<<"Gene:";
            for(int i=0;i<DNAL;i++){
                cout<<setw(4)<<static_cast<int>(gene[i]);
            }
            cout<<endl;
            break;
        case 3:
            cout<<setw(7)<<"CPU:";
            for(int i=0;i<DNAL;i++){
                cout<<setw(4)<<cpuNumber.at(i);
            }
            cout<<endl;
            break;
        }
    }
    for(int i=0;i<numberOfcpu;i++){
        cout<<"CPU"<<i<<" ("<<cpuResult[i]<<")\n";
    }
    cout<<"Objective function: "<<res<<endl;
}
void Individual::showInfo(){
    cout<<indNumber<<"(S:"<<res<<")";
}
void Individual::reFindResult(){
    res=cpuResult[0];
    for(int i=1;i<numberOfcpu;i++){
        if(res<cpuResult[i])res=cpuResult[i];
    }
}
void Individual::calcCpuResults(){
    for(int i=0;i<numberOfcpu;i++){
        Individual::cpuResult[i]=0;
    }
    for(int i=0;i<DNAL;i++){
        Individual::cpuResult[cpuNumber[i]]+=task[i];
    }
}

POPULATION__H
Кликните здесь для просмотра всего текста
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
#include "Individual.h"
#include <vector>
 
#ifndef POPULATION_H
#define POPULATION_H
class Population{
    int sizeOfPop;
    int popNumber;
    int globalIndNumber;
    int probabilityPair;//percents
    int probabilityMut;//percents
    int bestIndiNumber;
    int stoppingCrit;//
 
    vector<Individual> individual;
    vector<Individual> nextGeneration;
 
public:
    Population(int _size, int* task, int numberOfProc, int numberOfTasks,int prPair, int Mut, int stop);
    void showPopulation();
    void calcBestIndiNumber();//calc and return number of Best Individual;
    void pairing(Individual &a, Individual &b);//a and b - individuals in population
    void mutation(Individual &a);
    void newGeneration();// create new generation (0->sizeOfPop) 
    void GA();
};
#endif

POPULATION__CPP
Кликните здесь для просмотра всего текста
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
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
#include "Population.h"
#include "Individual.h"
#include <iostream>
#include <vector>
using namespace std;
 
Population::Population(int _size, int* tasks, int numberOfProc, int numberOfTasks, int prPair, int prMut, int stop){
    sizeOfPop=_size;
    popNumber=0;
    probabilityPair=prPair;
    probabilityMut=prMut;
    globalIndNumber=0;
    stoppingCrit=stop;
    for(int i=0;i<sizeOfPop;i++){
        if(i==0) {
            Individual ind(tasks, numberOfTasks, numberOfProc, i);
            individual.push_back(ind);//ERROR IS HERE
            globalIndNumber++;
        }
        else {
            Individual ind(i);
            individual.push_back(ind);
            globalIndNumber++;
        }
    }
    int tmpNumber=0;
    for(int i=1;i<sizeOfPop;i++){
        if(individual[i].res<individual[tmpNumber].res) tmpNumber=i;
    }
    Population::bestIndiNumber=tmpNumber;
}
void Population::showPopulation(){
    cout<<"\nPopulation #"<<popNumber<<": ";
    for(int i=0; i<sizeOfPop; i++){
        if(i%4==0) cout<<endl;
        cout<<" ";
        individual[i].showInfo();
    }
    cout<<"\nBest individual :";
    individual[bestIndiNumber].showInfo();
    cout<<endl;
 
}
void Population::pairing(Individual &a, Individual &b){
    int chance=rand()%100;
    if(chance<this->probabilityPair){
        int pointOfCross=rand()%(Individual::DNAL-1)+1;
        Individual child1(a);
        child1.indNumber=++(this->globalIndNumber);
        Individual child2(b);
        child2.indNumber=++(this->globalIndNumber);
        for(int i=pointOfCross;i<Individual::DNAL;i++){
            swap(child1.gene[i],child2.gene[i]);
            swap(child2.cpuNumber[i],child1.cpuNumber[i]);
        }
        child1.calcCpuResults();
        child1.reFindResult();
        child2.calcCpuResults();
        child2.reFindResult();
        if(child1.res>child2.res){
            //delete child1
            chance=rand()%sizeOfPop;
            mutation(child2);
                if(child2.res<(this->individual[chance].res)) {
                    nextGeneration.push_back(child2);
                }
                else{ 
                    nextGeneration.push_back(individual[chance]);
                }
            }
        else {
            //delete child2
            mutation(child1);
            chance=rand()%sizeOfPop;
                if(child1.res<(this->individual[chance].res)) {
                    nextGeneration.push_back(child1);
                }
                else{ 
                    nextGeneration.push_back(individual[chance]);
                }
            }
    }
}
void Population::mutation(Individual &a){
    int chance=rand()%100;
    if(chance<(this->probabilityMut)){
        chance=rand()%Individual::DNAL;
        if((a.gene[chance]%2)==0) a.gene[chance]++;
        else a.gene[chance]--;
        int step=256/Individual::numberOfcpu;
        if(a.gene[chance]%step==0){
            a.cpuNumber[chance]=a.gene[chance]/step-1;
        }
        else a.cpuNumber[chance]=a.gene[chance]/step-1;
        a.calcCpuResults();
        a.reFindResult();
    }
}
void Population::calcBestIndiNumber(){
    int tmpNumber=0;
    for(int i=1;i<sizeOfPop;i++){
        if(individual[i].res<individual[tmpNumber].res) tmpNumber=i;
    }
    Population::bestIndiNumber=tmpNumber;
}
void Population::newGeneration(){
    for(int i=0;i<sizeOfPop;i++){
        int pairNum=rand()%sizeOfPop;
        while(pairNum==i) pairNum=rand()%sizeOfPop;
 
        pairing(individual[i],individual[pairNum]);
        this->calcBestIndiNumber();
    }
    popNumber++;
    this->calcBestIndiNumber();
    nextGeneration.swap(individual);
}
void Population::GA(){
    int sC=0;
    int lastBest=individual[bestIndiNumber].res;
    while(sC!=stoppingCrit){
        this->newGeneration();
        this->showPopulation();
        if(lastBest==individual[bestIndiNumber].res){
            sC++;
        }
        else{   
            lastBest=individual[bestIndiNumber].res;
        }
        nextGeneration.clear();
    }
}


Вернуться к обсуждению:
Vector subscript out of range (push_back, a не []) C++
0
Заказать работу у эксперта
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
23.10.2013, 23:26
Готовые ответы и решения:

Struct / Vector / Expression: vector subscript out of range
Добрый вечер. Имеется структура: struct Contact { public: string name; vector&lt;string&gt;...

Vector subscript out of range
Не понимаю что происходит, объясните пожалуста #include &quot;pch.h&quot; #include &lt;iostream&gt; #include...

Vector subscript out of range
Помогите пожалуйста, выводит такую ошибку , не пойму почему #include&lt;iostream&gt;...

Vector subscript out of range
Привет, друзья, у меня следующая проблема: if (!MeteorVec.empty()) { for (int i = 0; i &lt;...

15
23.10.2013, 23:26
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
23.10.2013, 23:26
Помогаю со студенческими работами здесь

Vector subscript out of range
int main() { srand( time(0) ); vector &lt;int&gt; m(10000); int i,n,c,max; while(i&lt;=10000) {...

vector subscript out of range
Доброго времени суток! Подскажите пожалуйста, где именно я ошибся, вроде не должен он за пределы...

Vector subscript out of range
Доброе утро, прочитал статью про векторы и решил создать один из них, однако при выводе он выдаёт...

expression vector subscript out of range
Появляется ошибка при компиляции expression vector subscript out of range.Нужна помощь. Сортировка...

0
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru