Infinite loop in a C++ constructor
I've got this class in c++ and I'm having trouble with the second constructor: for some unknown reason, the IDE is acusing an infinite loop. I don't have any idea what is causing it, since I've written similar loops countless times. The code in question is this:
class ArithmeticProgression : protected Progression{
//Constructors
explicit ArithmeticProgression(double reason) : Progression(){
this->reason = reason;
}
ArithmeticProgression(double reason, int maxIndex) : Progression(){
this->reason = reason;
for(int i = 0; i < maxIndex; i++){
}
}
//Destructor
~ArithmeticProgression(){
delete this;
}
protected:
double reason;
};
1 answer
-
answered 2022-05-07 01:24
Blindy
You must be reading it wrong, because the infinite loop is in your destructor:
~ArithmeticProgression(){ delete this; }
You keep invoking it from within itself for absolutely no sane reason.
do you know?
how many words do you know
See also questions close to this topic
-
C++ increment with macro
I have the following code and I want to use increment with macro:
#include <iostream> #define ABS(x) ((x) < 0 ? -(x) : (x)) int main(int argc, char** argv) { int x = 5; const int result = ABS(x++); std::cout << "R: " << result << std::endl; std::cout << "X: " << x << std::endl; return EXIT_SUCCESS; }
But output will be incorrect:
R: 6 X: 7
Is it possible to somehow use macros with an increment, or should this be abandoned altogether?
-
Can anyone pls tell me whats wrong with my code ? im stuck for the last 3 hours ,this question is bipartite graph in c++
idk why im getting error ,can someone help ? im trying to prove if a graph is bipartite or not in c++
bool isBipartite(vector<int> graph[],int V) { vector<int> vis(V,0); vector<int> color(V,-1); color[0]=1; queue <int> q; q.push(0); while (!q.empty()) { int temp = q.front(); q.pop(); for (int i=0;i<V;i++) { if (!vis[i] && color[i] == -1) "if there is an edge, and colour is not assigned" { color[i] = 1 - color[temp]; q.push(i); vis[i]=1; } else if (!vis[i] && color[i] == color[temp] "if there is an edge and both vertices have same colours" { vis[i]=1; return 0; // graph is not bipartite } } } return 1; }
it gives output "no" for whatever i enter
-
How to assign two or more values to a QMap Variable in Qt
I am getting confused of how to store the values assigned from 3 different functions and storing them in a single map variable
QMap<QString,QString> TrainMap = nullptr; if(......) ( TrainMap = PrevDayTrainMap(); TrainMap = NextDayTrainMap(); TrainMap = CurrentDayTrainMap(); }
The PrevDayTrainMap,NextDayTrainMap & CurrentDayTrainMap returns a set of values with Date and the TrainIdName.I need to store all the values from prevday,currentday and nextday in the TrainMap but it stores only the currentday values to the TrainMap as it is assigned at the last.I am not sure what to do so that it doesn't overwrite.If I should merge what is the way to do it?
-
I ned a while loop statment that makes the calculations loop and ask again
im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow; public class Calculator extends DIYWindow { public Calculator() { // getting number one double number1 = promptForDouble("Enter a number"); //getting number2 int number2 = promptForInt("Enter an integer"); //getting what to do with operation print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide"); String operation = input(); //declaring variable here so the same one can be used double answer = 0; switch(operation) { case "add": answer = number1 + number2; print(number1 + " + " + number2 + " = " + answer); break; case "subtract": answer = number1 - number2; print(number1 + " - " + number2 + " = " + answer); break; case "multiply": answer = number1 * number2; print(number1 + " * " + number2 + " = " + answer); break; case "divide": try { answer = number1 / number2; } catch(ArithmeticException e) { print("A number cannot be divided by 0."); } print(number1 + " / " + number2 + " = " + answer); break; } double double1 = promptForDouble("Enter a number"); double double2 = promptForDouble("Enter another number"); double double3 = promptForDouble("Enter one last number"); print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide"); String operation2 = input(); double answer2 = 0; switch(operation2) { case "add": answer2 = double1 + double2 + double3; print(double1 + " + " + double2 + " + " + double3 + " = " + answer2); break; case "subtract": answer2 = double1 - double2 - double3; print(double1 + " - " + double2 + " - " + double3 + " = " + answer2); break; case "multiply": answer2 = double1 * double2 * double3; print(double1 + " * " + double2 + " * " + double3 + " = " + answer2); break; case "divide": try { answer2 = double1 / double2 / double3; } catch(ArithmeticException e) { print("A number cannot be divided by 0."); } print(double1 + " / " + double2 + " / " + double3 + " = " + answer2); break; } want it to loop after the code on top } private double promptForDouble(String prompt) { double number1 = 0; print(prompt); String number = input(); try { number1 = Double.parseDouble(number); } catch(NumberFormatException e){ print("That is not a number. Please enter a number."); number1 = promptForDouble(prompt); } return number1; } private int promptForInt(String prompt) { int number2 = 0; print(prompt); String number = input(); try { number2 = Integer.parseInt(number); } catch(NumberFormatException e) { print("That is not an integer. Enter an integer."); number2 = promptForInt(prompt); } return number2; } public static void main(String[] args) { new Calculator(); } }
-
Data structure for iterating between players
I am new to programming, so I started working on a small guessing game for n players In theory they are supposed to take turns trying to guess some String, I've successfully implemented that game for 1 player, but now I am struggling with how to implement iterating over all players. My code right now looks something like this:
while (!gameIsFinished) { gameIsFinished = player1.takeTurn(); }
I guess I have to use some sort of Data structure to store all my players, but what would I choose in order to be able to iterate over them in a loop?
-
How do I shutil.move my file, post processing, in python based on filename?
My code-
import pandas as pd import datetime as dt import os import shutil path = "C:/Users/rocky/Desktop/autotranscribe/python/Matching" destination_path = ('C:/Users/rocky/Desktop/autotranscribe/python/Matching/Processed') for file in os.listdir("C:/Users/rocky/Desktop/autotranscribe/python/Matching"): if file.startswith("TVC")and "(updated headers)" not in file: dfs = pd.read_excel(file, sheet_name=None) output = dict() for ws, df in dfs.items(): if ws in ["Opt-Ins", "New Voting Members", "Temporary Members"]: continue if ws in ["Voting Members", "Removed Members"]: temp = df dt = pd.to_datetime(os.path.getctime(os.path.join(path,file)),unit="s").replace(nanosecond=0) temp['Status'] = "Active" if ws == "Voting Members" else "Cancelled" output[ws] = temp writer = pd.ExcelWriter(f'{file.replace(".xlsx","")} (updated headers).xlsx') for ws, df in output.items(): df.to_excel(writer, index=None, sheet_name=ws) writer.save() writer.close() shutil.move(path, destination_path )
I just want the file that is being processed here
if file.startswith("TVC")and "(updated headers)" not in file:
to be moved to another folder directory after all my code is processed and the output file is produced..where do i apply shutil.move? i put it outside my inner loop but the file didnt populate in my dest folder as expected. Do i need an if statement? if script runs successfully and output xls produced then move original file to destination folder? -
What is "does not name a type" error and how it can be resolved
#include <bits/stdc++.h> using namespace std; class Item{ unordered_map<string,int> mp; mp["Pizza"]=50; mp["Burger"]=100; mp["Coke"]=50; mp["Brownies"]=60; public: int getPrice(string s) { return mp[s]; } }; class Day{ std::unordered_map<string,int> hr; hr["Peak hour"]=30; hr["Night Charges"]=20; hr["Special days"]=50; hr["Normal"]=20; public: int getHrPrice(string s) { return hr[s]; } }; int main() { double totalBill=0; Item i; Day d; totalBill+=i.getPrice("Burger"); totalBill+=i.getPrice("Coke"); totalBill+=totalBill*5/100; totalBill+=d.getHrPrice("Special"); totalBill+=d.getHrPrice("Night"); cout<<totalBill<<endl; return 0; }
I'm getting this error :
error: ‘mp’ does not name a type
error: ‘hr’ does not name a type
I'm new to OOPS. Thanks in Advance...
-
Opengl GLFW3, Cant update vertices of two object at the same time
So i am trying to make a game where I want to update my player and enemy. enemy and player are squares. I have a square class with VAO, VBO, EBO and vertices where I load my square.
void Square::loadSquare() { unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // bind vertex array object glBindVertexArray(VAO); // bind vertex buffer object glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW); // bind element buffer objects // EBO is stored in the VAO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // registered VBO as the vertex attributes glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // unbind the VAO glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); }
and draw method:
void Square::drawSquare() { // Bind the VAO so OpenGL knows to use it glBindVertexArray(VAO); // Draw the triangle using the GL_TRIANGLES primitive glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); }
Player and Enemy classes are inherited from square class and they have their own update method where I call in my Carte classes update methode.
void Carte::update(){ drawMap(); enemy.update(GrapMap,0); player.update(GrapMap); }
In draw map I simply draw my enemy and player.
void Carte::drawMap(){ enemy.drawSquare(); player.drawSquare(); for(auto & wall : walls){ wall.drawSquare(); } }
Walls are squares too but in my case I draw therm where I want and I don't have a problem with them. at the end of every update of enemy and player after chancing vertices of them I call
glBindBuffer(GL_ARRAY_BUFFER, VAO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW);
When it was only player that I was updating it was working flawlessly. But with enemy I cant see the player but I can see that its vertices are changing accordingly to the key input of the user. When I comment out player and try to update enemy only enemy is not updating but again I can see its vertices changing as it should.
Before creating my Carte object at the main I did this:
// Vertex Shader source code const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; //Fragment Shader source code const char* fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(0.8f, 0.3f, 0.02f, 1.0f);\n" "}\n\0"; int main() { // Initialize GLFW glfwInit(); // Tell GLFW what version of OpenGL we are using // In this case we are using OpenGL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Tell GLFW we are using the CORE profile // So that means we only have the modern functions glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create a GLFWwindow object of 800 by 800 pixels, naming it "window" GLFWwindow* window = glfwCreateWindow(1000, 1000, "Window", NULL, NULL); // Error check if the window fails to create if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } // Introduce the window into the current context glfwMakeContextCurrent(window); //Load GLAD so it configures OpenGL gladLoadGL(); // Specify the viewport of OpenGL in the Window // In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800 //glViewport(0, 0, 1400, 1400); // Create Vertex Shader Object and get its reference GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); // Attach Vertex Shader source to the Vertex Shader Object glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // Compile the Vertex Shader into machine code glCompileShader(vertexShader); // Create Fragment Shader Object and get its reference GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // Attach Fragment Shader source to the Fragment Shader Object glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // Compile the Vertex Shader into machine code glCompileShader(fragmentShader); // Create Shader Program Object and get its reference GLuint shaderProgram = glCreateProgram(); // Attach the Vertex and Fragment Shaders to the Shader Program glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); // Wrap-up/Link all the shaders together into the Shader Program glLinkProgram(shaderProgram); // Delete the now useless Vertex and Fragment Shader objects glDeleteShader(vertexShader); glDeleteShader(fragmentShader);
In my while loop I am doing this:
// Specify the color of the background glClearColor(0.07f, 0.13f, 0.17f, 1.0f); // Clean the back buffer and assign the new color to it glClear(GL_COLOR_BUFFER_BIT); // Tell OpenGL which Shader Program we want to use glUseProgram(shaderProgram); int keyW = glfwGetKey(window, GLFW_KEY_W); int keyA = glfwGetKey(window, GLFW_KEY_A); int keyS = glfwGetKey(window, GLFW_KEY_S); int keyD = glfwGetKey(window, GLFW_KEY_D); carte.update(); if(keyW) deneme.setPlayerDirection(Directions::UP); else if(keyA) deneme.setPlayerDirection(Directions::LEFT); else if(keyS) deneme.setPlayerDirection(Directions::DOWN); else if(keyD) deneme.setPlayerDirection(Directions::RIGHT); // Swap the back buffer with the front buffer glfwSwapBuffers(window); // Take care of all GLFW events glfwPollEvents();
I don't understand why I can't update my two objects at the same time. Why I cant draw squares as the vertices changes when there is more then one objects vertices are changing.
edit to show how I change my vertices in Player:
if(getDirection() == Directions::UP){ trans = glm::translate(trans, glm::vec3(0.0f, 0.0002f, 0.0f)); setCenter(center.first,center.second + 0.0002f); } else if (getDirection() == Directions::LEFT){ trans = glm::translate(trans, glm::vec3(-0.0002f, 0.0f, 0.0f)); setCenter(center.first-0.0002f,center.second); } else if (getDirection() == Directions::DOWN){ trans = glm::translate(trans, glm::vec3(0.0f, -0.0002f, 0.0f)); setCenter(center.first,center.second-0.0002f); } else if (getDirection() == Directions::RIGHT){ trans = glm::translate(trans, glm::vec3(0.0002f, 0.0f, 0.0f)); setCenter(center.first+0.0002f,center.second); } else if (getDirection() == Directions::STOP) trans = glm::translate(trans, glm::vec3(0.0f, 0.0f, 0.0f)); for(int i=0; i < 4; i ++){ glm::vec4 tmp = trans * glm::vec4(getVertices()[i],1); setVertices(i, tmp.x, tmp.y, tmp.z); } glBindBuffer(GL_ARRAY_BUFFER, VAO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW);