question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
62,366,202
62,366,228
How do I detect if anything but an integer is passed to my class constructor?
Fair and simple: How do I check if anything else but an integer is passed to my class in c++? If I pass f.e. a char 'a' my class gets number 97 in ascii. I tried std::numeric_limits but I don't get why it is not detecting integers: #include <iostream> #include <limits> class integerCheck { public: integerCheck(int...
Delete the constructor taking chars and make the ctor explicit to prevent accepting floats as follows class integerCheck { public: explicit integerCheck(int value) { std::cout << value << std::endl; } integerCheck(char ) = delete; }; This doesn't allow the two following ctors to compile intege...
62,366,504
62,366,750
Trying to understand C++ pointers and data type initializations
I am trying to learn C++, I have a fair bit of experience in C# and the 2 languages are so dissimilar and I am having trouble understanding data types and pointer variants of data types and the initialization of them, please consider the code below: wchar_t *array = new wchar_t[10]; //Declaring a pointer of wchart_...
If you know the size of the number of elements you need to put in the array, then just use the array i.e., wchar_t arr[10];. If you don't know the size, you can create the array at runtime using dynamic memory allocation with the required size i.e., wchar_t *arr = new wchar_t[required_size]. Once the memory is allocate...
62,366,612
62,375,700
C++: question about move constructor/assignment using Stroustrup example
I understand how an rvalue would invoke the move constructor and move assignment operator, however I'm confused why the same code in Stroustrup's example below for move assignment isn't used for the move constructor. This is from C++ 4th Ed. Page 379 revised errata. As all the objects in the class are copied in the m...
The move constructor cannot do a swap because it's members are uninitialized and the destructor will not work correctly on the passed rvalue. Therefore the move constructor must copy each element one by one and set the rvalue's members to null, so the rvalue destructor will work. The move assignment can do the swap wit...
62,366,669
62,366,861
Combining two cpp files into one cpp file
I am working on an assignment where I have main.cpp,lego.cpp, and lego.h. My program currently runs fine and gives out the desired output. My issue is that to submit, I must have everything in a single cpp file. Would appreciate if someone could give a simple example. (I want everything in main.cpp) Merge C++ files int...
if anyone has this problem I just fixed it by doing this class lego {things in class}; lego::functionA(){} lego::functionB(){} int main(){}; make sure that you delete any other cpp files that are in your source folder and remove any header files from main. Was what was causing my issue.
62,366,769
62,366,844
Calling a method on an object after it was created in Switch Case in C++
I have created an object using new in a switch case. The object is assigned to an element of an array of pointers. While in the case I am able to call a method on that object, but outside the case it seems I cannot. It just doesn't do it. I have a function to set the elements of the object which I can call while wit...
Here is an explanation of what the code actually doing: First, you declared a pointer to the object then you take a copy of that pointer (an address), and then you deleted that pointer. So you have an address to memory but you are not allowed to access it as you deleted the pointer (dangling pointer). This is a common ...
62,366,875
62,366,893
How to build a vector of strings of filenames in a directory and its subfolders?
I'm currently using the following code: std::vector<std::string> paths; std::string path = "Assets/"; for (const auto& entry : std::filesystem::directory_iterator(path)) { paths.push_back(entry.path().string()); } But, it ignores the subfolders in the Assets/ folder. How can I make it keep track of all the fi...
You need to use a std::recursive_directory_iterator to get the paths of the nested directories: for (const auto& entry : std::filesystem::recursive_directory_iterator(path)) { paths.push_back(entry.path().string()); } Also, instead of storing the paths as strings, you could store them directly, like this: std::vec...
62,367,099
62,367,248
C++: Object Stores Lambda into a Struct and Later Calls that Function
What's the proper syntax to accomplish this? The idea is that some object of any class could store a lambda expression in class GuiButton, and then later that call that lambda expression with access to its own local variables. It should be noted that my platform (Arduino) does NOT support the functional header. The cod...
Something along these lines: class GuiButton { GuiButton(void (*_callback)(void*), void* _context) : callback(_callback), context(_context) {} // Invoke the callback as callback(context) void (*callback)(void*); void* context; }; // In ExampleScreen new GuiButton([](void* context) { auto self = stat...
62,367,175
62,367,298
why does it give me bigger than 4 always?
I am trying to get the numbers bigger than 4 after I loop in every other number, but the problem is that it keeps giving me bigger than 4 even tho the number isn't bigger than 4. thank you! #include <iostream> #include <vector> #include <string> using namespace std; bool isvalidcc(const string& s) { vector<char...
I figured it out Because v.at(i) is a char instead of an int it converts it into ascii code. this means u have to convert the char in to an int the right way. if (v.at(i) - '0' >4) the - '0' will convert it to an int the right way otherwise it will return the wrong values, u can check this by making a new int variable...
62,367,230
62,367,413
Linker Error when calling operator<<, how to fix this?
Important Update: Removing the delegation of friend solved the problem Partially but why? and how may I keep it as friend... Why the following code gets me linker error? Dimensions dims2(3 ,14);//Fixed class 100% the bug isn't cause by it Matrix<int> mat_2(dims2, 5); std::cout << mat_2; My class: template<class T> cla...
friend std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix); This declares a non-template function named operator<< (in the namespace enclosing Matrix definition). That function is never defined. In addition, a function template also named operator<< is defined. When doing overload resolution, the compi...
62,367,255
62,367,329
How do you comprehend "std: :forward is just syntactic sugar"? Is that true?
How do you comprehend "std::forward is just syntactic sugar"? Is that true? I would appreciate that if you could explain the related code below in detail. As per the documentation(https://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/a00416_source.html), here is the implementation of std::forward: /** * @b...
“std: :forward is just syntactic sugar”? Is that true? Depends on what one means by "is just syntactic sugar". How do you comprehend “std: :forward is just syntactic sugar”? I think that a correct and similar way to describe std::forward is that it is a very simple function template that can be implemented in stand...
62,367,513
62,368,194
C++ iteratively search through mixed type Maps
I have a large set of if statements I would like to turn into a loop: if (intParams.find(paramName) != intParams.end()) { return (float)intParams.at(paramName); } else if (floatParams.find(paramName) != floatParams.end()) { return (float)floatParams.at(paramName); } else if (boolParams.find(paramName) != boolParams...
float retval=defaultVal; auto all_maps = [&](auto&...maps){ auto one_map = [&](auto&map){ auto it = map.find(paramName); if (it==map.end()) return false; retval=static_cast<float>(it->second); return true; }; return ( one_map(maps) || ... ); }; all_maps(intParams, floatParams, boolParams); return ...
62,367,656
62,834,669
Print Opposite Triangles function in C++
Our assignment is to write a recursion that can print something like this: * * * * * * * * * * * * * * * * * * * * I wrote my code and was hoping to get the right graph. But instead, I got this: * * * * * * * * * * * * * * I cannot figure out why. I thought every time my code calls printOppositeTriangles(n-1), it wil...
There is a big problem in your code: you need to have a recursive call in printOppositeTriangles. You are calling print triangle which is not the same function name as printOppositeTriangles. This is the main idea of recursion and it doesn't present in your example. Try this void printLine(unsigned int n) { if (n =...
62,367,948
62,368,981
Confused with the basics of Hash Table in C++
here is a small code I have written about hash tables. #include <iostream> using namespace std; int hashval(int n){ return n%5; } int main(){ int hashtable[4],num, value; for (int i=0 ; i<=4; i++){ hashtable[i]=0; } for (int i=0; i <=4; i++){ cout << "Enter the number you wanna e...
Your problem is that int hashtable[4] allocates an array that can store four values, with indices from 0...3. However, then you try to store five values in the array. Usually C++ is poorly suited to the compile and see method of learning. It is very common to compile and test code in C++, find that the code "works", wh...
62,368,057
62,368,185
opengl- does VAO store texrture unit calls as well
The very basic foundation for creating a VAO, VBO and applying a texture goes like this: unsigned int VBO, VAO, EBO; //#1 glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,...
The reason lines 1 and 2 are "stored inside the VAO" is because that's what those functions do. Those functions set state within the currently bound vertex array object. A vertex array object, as the name suggests, is an object that deals with vertex arrays. Texture management, texture storage, and using textures for r...
62,368,157
62,371,653
Infinity norm function in C++
Is there a built in function for the infinity norm in C++? If not, I would like to know which package exactly has it and if it is available for installation using Cygwin. Thanks!
You’re probably looking for std::max_element.
62,368,356
62,377,989
Is there an analog to Compiler Flags from Code Blocks in Visual Studio?
I have just started a course on the creation of keylogger and the first function I encountered was something to make the console disappear: #include <iostream> #include <windows.h> using namespace std; int main() { MSG Msg; while (GetMessage(&Msg, NULL, 0, 0)) { TranslateMessage(&Msg); Dispat...
I have been digging around a little more, and found an answer here. Since the purpose of the addition of the flag was to enable the option to stop the console from appearing, this solution is sufficient.
62,368,984
62,370,405
How best can I fix my memory leak using smart pointers?
I stumbled upon this, which looks like a memory leak: void method(const string param) { if (auto* object = createObject(param)) use(object); } How best do I fix this memory leak? Should I wrap the returned pointer in a unique pointer? void method(const string param) { if (auto object = std::unique_ptr<...
You should avoid owning raw pointer, non-owning raw pointer are "fine" (caveat is that we don't know from pointer if it is owning or not). Better would be to change Object* createObject(const std::string& param) { return new Object(param); } into std::unique_ptr<Object> createObject(const std::string& param) { ret...
62,369,119
62,369,463
Why is std::mutex neither copyable nor movable?
Could somebody tell the reasons why std::mutex is neither copyable nor movable? Somebody told me that it has some relationship to avoid resource waste. Why the copy constructor of std::mutex should be marked as deleted? If not, is there any potential problem? Its copy constructor is clearly marked as deleted, but I ha...
Expanding a bit on the other answers, basic locks such as Mutexes are the most basic objects in the language design providing atomic operations, lock and unlock here. These might own an OS implemented handle (native_handle) that is a handle for a hardware implemented object, and might even skip the intermediate handle....
62,369,287
62,369,716
brute force technique for the following problem
Given an integer A which denotes the number of people standing in the queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one perso...
If you are interested in a simple algorithm similar to yours, then please see this example: #include <iostream> #include <vector> using namespace std; int main() { int A = 10, currentSize = A; vector<bool> mark(A, true); while (currentSize > 1) { for (int i = 0, j = 1; i < A; i++) { i...
62,370,027
62,370,190
namespace std:: does not contain optional
i am doing the Vulkan Tutorial https://vulkan-tutorial.com/ #define GLFW_INCLUE_VULKAN #include<GLFW/glfw3.h> #include<optional> struct s { std::optional<uint32_t> num;//Intellisense Error }; int main() { return 5; } I started with an empty project and added includes and libraries; I can compile and run ...
std::optional requires C++17. Live on Godbolt. you can use /std:c++17 flag on MSVC and -std=c++17 on gcc/clang.
62,370,172
62,370,237
Serialization of objects to files - is dumping char* back-and-forth safe?
I would like to write an object to a file, and later be able to read it from the file. It should work on different machines. One simple option is the following: struct OBJECT{ // The object to be serialized / deserialized public: // Members are serialized / deserialized in the order they are declared. Can use bitpack...
This approach is generally safe only if all of the following are true: The type contains only "inline" data. This means only fundamental types (no pointers or references) and arrays thereof. Nested objects that also meet these criteria are also OK. All of the types have the same representation on all systems/compi...
62,370,565
62,371,254
How to create file using ofstream in software's code
I am working on a software I have a task to make changes in software to add certain feature for which I need to log data .I am trying to create a log file using ofstream but I dont know why it is not creating file at any location I tried .I am having code and I am attaching that to existing software process. ofstream k...
If k.open("ko.txt",ios::app); does not works that means you do not have the right to create the file in the current directory or you cannot modify the file Under Windows you can create the file into the directory Documents of the current user, and you can get the user home dir using getenv("USERPROFILE") or get the use...
62,370,655
62,375,992
Concept resolve to the unexpected function template when using std::make_signed_t
Consider the following snippet #include <type_traits> template <typename T> concept unsigned_integral = std::is_integral_v<T> &&std::is_unsigned_v<T>; template <unsigned_integral T> auto test(T) -> std::make_signed_t<T>; //(1) template <typename T> auto test(T) -> int; //(2) int sandbox() { test(1u); // Call to (1...
This is CWG 2369 (unfortunately not on a public list despite having been submitted years ago). I'll just copy the main text here: The specification of template argument deduction in 13.9.2 [temp.deduct] paragraph 5 specifies the order of processing as: substitute explicitly-specified template arguments throughout the...
62,370,813
62,372,639
Passing rows of a MatrixXd to a function to be modified without creating copies in Eigen
This question is concerned with C++ and Eigen. I have a function that computes some vector as Eigen::VectorXd and stores them into the vector passed as an argument. The return value of the function is the number of iterations done in the function. Below is the pseudocode of the function: size_t integrate(Eigen::VectorX...
You can pass writable references to blocks of matrices using an Eigen::Ref object. In your case, since rows of (column major) matrices will have an inner stride, you need to explicitly allow that: size_t integrate(Eigen::Ref<Eigen::VectorXd, 0, Eigen::InnerStride<> > v) { v.setRandom(); // use `v` as if it was a Ve...
62,370,866
62,371,770
std::regex: Match string consisting of digits and white space and extract digits. How?
I want to do 2 things at the same time: Match a string against a pattern and extract groups. The string consists of white spaces and digits. I want to match the string against this pattern. Additionally I want to extract the digits (not numbers, single digits only) using std::smatch. I tried a lot, but no success. For...
The pattern you need to validate is \s*(?:\d\s*)* See the regex demo (note I added ^ and $ to make the pattern match the whole string at the regex testing site, since you use equivalent regex_match in the code, it requires a full string match). Next, once your string is validated with the first regex, you just need to...
62,370,888
62,384,525
Little confusion in both write() and read()
Below program take three details of family members i.e name,age and occupation. Stores them in txt file. #include <iostream> #include <stdlib.h> #include <string.h> #include <fstream> using namespace std; class Dewan_Family { char name[50]; // array for name of the family member int age; ...
In your code you are not checking if read is successful before using it, so the last obj created from a failed read. a possible fix is checking before serializing to an object: case 2: file.seekg(0); while(file) if(file.read((char*)&obj[j],sizeof(obj[j]))){ ...
62,370,904
62,370,949
Derived object created without having default constructor
I was doing a small test in a site and I run to this problem. #include<iostream.h> class Base { int x, y, z; public: Base() { x = y = z = 0; } Base(int xx, int yy = 'A', int zz = 'B') { x = xx; y = x + yy; z = x + y; } void Display(void) { ...
this is because you have default parameters in your c'tor meaning if you don't pass parameters in then it defaults the parameters. Your constructor can handle 0,1 or 2 parameters. If you change: Derived(int xx = 65, int yy = 66) : Base(xx, yy) to Derived(int xx, int yy) : Base(xx, yy) then your compile will fail add...
62,370,978
62,383,400
Getting clang++: error: while compiling code contaning filesystem library
I am trying to use filesystem in native code in android project. But getting this error: FAILED: C:/Users/Johnsnow/AndroidStudioProjects/abc/Application/app/build/intermediates/cmake/debug/obj/armeabi-v7a/libnative-lib1.so cmd.exe /C "cd . && C:\Users\Johnsnow\AppData\Local\Android\Sdk\ndk\21.1.6352462\toolchains\llv...
Support for std::filesystem looks like it will land in Android NDK r22 at the earliest: The implementation for this is now checked in to master and will be in r22. I've forked the remaining testing cleanup into #1265 so I can close this to make it obvious that the part you folks care about is complete without having t...
62,370,979
62,377,169
Is it possible use an rvalue to initialize a data member?
I'm very new to r-value references and move semantics but the tutorials I've read have the attitude "since the temporary is a perfectly well constructed object that's usually copied and destroyed, why not extend its lifetime and move it around?" So I'm picturing a scenario like this: class Foo { Foo m_foo; // Could a...
You cannot keep a data member of type Foo inside class Foo because the object would be infinitely large (because each object of type Foo will have another Foo object inside, which that inner object will have another Foo object inside, and so on. With this change, you can have something like this: class Foo { std::un...
62,371,044
62,371,383
Why copy constructor is getting called?
I have the following piece of code and there are a couple of things that bother me the most: At what point in time does original constructor call happen? Under which circumstances, the copy constructor is getting called? #include <iostream> #include <functional> class Samp { char str[10] = "Default"; public: ...
The arguments to a std::function invocation are passed by perfect forwarding through to the callable object stored inside the std::function object. So the behaviour of o(args...) is not the same as output(args...). Instead it is the same as: output( std::forward<Args...>(args...) ); or in this concrete example, outp...
62,371,491
62,386,465
resizing wxListView with sizer
I'm struggling to resize my wxListView when resizing my wxFrame. I managed to resize ListView's parent panel and wxButton in the same panel also moves with resizing the window as intended. BluetoothConnectFrame::BluetoothConnectFrame(const wxString& title, const wxPoint& pos, const wxSize& size, Frame* parent) : w...
As others have noted in comments, you can do layout yourself explicitly in wxEVT_SIZE handler or (and this is the exclusive or) use sizers. To do the latter, start by removing your OnSize() handler for the frame entirely. What you may still want to have is an wxEVT_SIZE handler for the list view itself, which could res...
62,371,507
62,371,541
How do I assign a value to an enum in constructor with a default value?
I have a class in C++ with a protected enum type and I am having trouble initialising that value in the constructor using a user defined argument, where it also has a default value. Code: class Student { protected: double gpa; enum gradeStatus {freshman, sophomore, junior, senior, blank}; public: Student(double i...
gradeStatus is the name of enum type, but not a name of data member. The error message is trying to tell you that you should initialize a data member, but not a enum type. You might want class Student { protected: double gpa; enum gradeStatus {freshman, sophomore, junior, senior, blank}; // enum type definition g...
62,371,608
62,371,654
Modifying Arguments passed by reference in the function call in a recursive function
Here is a simple code that takes counter as a reference passed argument and then prints it : #include <iostream> using namespace std; void Fun(int &counter, int n) { if(n==0) return; Fun(counter+1,n--); } int main() { int counter = 0; int n = 5; Fun(counter,n); cout<<counter<<endl; ...
In Fun(counter+1,n--); you are not passing counter to the function. You create a temporary from counter+1 that you pass to the function. To extend the life of a temporary taken by reference, it needs to be const, so void Fun(const int &counter, int n) would be compileable. Counter will however be 0 when the function en...
62,371,756
62,371,832
opengl - does glBindTexture overwrite contents of the active texture unit
I was finding the relationship between glActiveTexture(...) and glBindTexture(...) and I found an awesome answer here, the very top answer(the author/user Alfonse) gives us a pseudocode for how the both functions behave, and I understood most of it. But, in it he mentions in calls such as this: glActiveTexture(GL_TEX...
No, texture parameters (set by glTexParameter) are set for a specific texture (the one that's currently bound to the active texture unit), not for a texture unit (not for one of GL_TEXTUREi, that is). Note that your use of glTextureParameteri incorrect. Rather than GL_TEXTURE_2D, it expects a handle of a texture, as r...
62,372,070
62,372,095
How can I initialize a std::chrono::duration constant without using namespace chrono?
I want to use this code static constexpr auto set_time = 1s; But I don't want to use using namespace chrono; Error C3688 invalid literal suffix "s"; could not find the literal operator or pattern of the literal operator " operator ""s"
using namespace std::chrono_literals;
62,372,204
62,372,307
Texturing 3d polygons in OpenGL with C++
I'm new to OpenGL and programming in general and I'm trying to paste any picture on all surfaces of a cube and a pyramid so the picture can move with them and rotate with them I tried a lot of tutorials but most of them focus on 2d or with other programming languages like C# . how can I make texturing to my polygons...
[...] but most of them focus on 2d [...] You have to wrap 2d textures around the 3d mesh. Put different parts of a 2d texture on the faces of the 3d mesh. Each face of the 3d object is 2 dimensional. You have to define the texture coordinate attributes for each vertex of a face (respectively primitive), to select an...
62,372,231
62,377,438
Cannot receive WM_CLIPBOARDUPDATE messages
I am trying to use Clipboard Format Listener for my C++ Console Application. The goal is to monitor every change in the clipboard. I create MessageOnly window, successfully call AddClipboardFormatListener in WM_CREATE, but never get WM_CLIPBOARDUPDATE message in WindowProc function. #include <iostream> #include "window...
Your message loop is wrong. CreateWindowEx() sends a WM_CREATE message before exiting, which is why your WindowProc() receives that message. However, PeekMessage() does not dispatch messages to windows, which is why your WindowProc() does not receive the WM_CLIPBOARDUPDATE messages. Your message loop needs to call Disp...
62,372,375
62,372,530
Pythagorean triple nested loops missunderstanding
Greetings and regards; I was trying to find Pythagorean Triple numbers less than 1000. Fortunately I was able to find the algorithm for it, Here it is: for (int a = 1; a < 1000; a++) { for (int b = a; b < 1000; b++) { for (int c = b; c < 1000; c++) { if ((a * a) + (b * b) == (c * c))...
Pythagorean triplets have only one way of being ordered: if a² + b² = c² then one can prove than a² + c² ≠ b² and b² + c² ≠ a². From the above and a few special cases (a = 0 is excluded by definition, a ∊ (0, 2] are easy to check by hand), it follows that one only has to check triplets for which 2 < a ≤ b < c, and this...
62,372,489
62,372,695
c (arduino) misc function returning char pointer
i found function in some code. Looks like that function generates some random number with variable length and returns char* char* result = (char*)malloc(sizeof(char)*length); randomSeed(analogRead(A0)); for (int i = 0; i < length; ++i) { result[i] = 48 + random(9); } result[length] = '\0'; When i tested it, i was s...
first of all your code does not work. You write outside the array in this line result[length] = '\0'; the code shuold look like: for (int i = 0; i < length - 1; ++i) { result[i] = 48 + random(9); } result[length - 1] = '\0'; char is just an integer type and it can be read or written. if you want make it not writa...
62,372,838
62,383,991
How to run the same google test case with different google mocks?
There are several test cases which was using a service. The test cases are written with google test. The service can be of different types, so I have mocked each one with google mock. How do I write the tests in such a way so they can be run with different mocks without writing the same tests again and again with diffe...
If you use GoogleMock framework to create and control mocks during the tests' execution, you can specify (using e.g. EXPECT_CALLS) how the mock should behave. The object under tests shouldn't care about what type of mock is used in given tests if you use Dependency Inversion Principle from SOLID (i.e. there should be ...
62,372,898
62,372,949
C++ cannot open source file "time.h"
I am trying to use clocks to measure the time of the running program in Visual Studio 2015 (x64) with C++ on Windows in Debug x64 mode. I get errors in these lines: #include <time.h> #include <sys/timeb.h> The errors messages say: cannot open source file "time.h" cannot open source file "sys/timeb.h" What path do I ...
You could try #include <ctime> Refer to this: http://www.cplusplus.com/reference/ctime/ time.h is used is C not C++.
62,372,951
62,375,770
Is the asio strand object thread safe?
I have to develop an asynchronous client that talks to a server. The client runs in a separate thread from the main application and just reads what the server sends using a callback chain. Each read handler registers the next one through a strand (it is a bit more complex since I use a class method as a callback so I n...
Yes. See docs Thread Safety Distinct objects: Safe. Shared objects: Safe. Strands can be copied. In fact, you can create a new strand off another executor and if that was on a strand it will end up representing the same strand identity. Additionally, a mutex on a strand couldn't possibly work because composed operat...
62,373,085
62,373,890
The Eulers Project Problem no 345 Cant understand a few lines of code
I have a problem understanding the below code . I have marked the part i didnt understand with //comment The function 'search()' is recursively called. MaxRemaining[] array has 15 elements, Size is a const with value 15. const unsigned int Size = 15; unsigned short matrix[Size][Size] = { { 7, 53, 183, 439, 8...
I will try to explain the lines you highlighted. Let's start by explaining the columnMask argument - this argument is the bitmask of all the columns used. Obviously, this mask is initially 0. Next: auto mask = 1 << column; In this line of code, we get the bitmask for the column. Next: if ((columnMask & mask) != 0) ...
62,373,098
62,373,352
Flat Window when using C++/OpenGL
Thanks for the answers to my last question, they really helped. I am following the Advanced C++/OpenGL Tutorials playlist, and before tutorial 19, eveything was working fine. But now, I have a flat window, that only has the window title. I don't know the exact reason, and I tried debugging it, but I think it is some...
It's not the right way to post a question, but I'm feeling generous today. Bengine/Window.cpp line 33: _sdlWindow = SDL_CreateWindow( windowName.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, _screenHeight, SDL_WINDOW_OPENGL); Notice how screenWidth is taken from the argument, but _scr...
62,373,799
62,380,472
How do I change terminal display? Visual Code on Mac
When Running my code I really only want to display the code I'm working on. I don't want to display what seems to be the folder address. Is there a way to not display that? I mean when im running my code. I want to see the answer to my code only so to just display 28 .... not the folder name desktop/cpp etc etc
I noticed you were having some trouble with VS-Code. Here's a good list of commands which can complete your task. I noticed you stated that you were on a Mac as well, so more than likely the CTRL + option won't be necessary; try the " ⌘ + " instead! To remove / hide the folder explorer window, simply hit "⌘ + b" To...
62,373,990
62,374,226
SDL_Init_Everything fails in C
I am trying to create a game in C using SDL. After some time of debugging I found an error at SDL_Init: #include <SDL2/SDL_ttf.h> int main(void) { printf("Init attempt\n"); if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "Failed at SDL init: %s\n", SDL_GetError()); fflush(stderr); fflush(stdo...
using the official doc (https://wiki.libsdl.org/SDL_Init) there's a flag that might conflict with your setup: SDL_INIT_HAPTIC i didn't get any error or crash so im not sure, but it is possible that this flag might be included in the EVERYTHING one, and if so: It’s disabled by default if you don’t use ./configure; make ...
62,374,207
62,582,662
Icon in Windows Explorer showing 2 different icons when using resource.rc
I'm trying to change the icon of my Windows application. I'm using the simple window code below and added a resource.h and resource.rc to the solution. I'm using a test.ico and a test2.ico-file which both contain 64x64, 32x32, 24x24 and 16x16 sizes. The when I switch between icon and icon2 by simple changing this line ...
As pointed out by Jonathan Potter: Explorer has an icon cache; if it's showing the wrong icon you probably need to clear the cache. http://leodavidson.blogspot.com/2011/05/clear-icon-cache-1001.html
62,374,350
62,418,024
In Radix Sort, I get munmap_chunk(): invalid pointer and Aborted (core dumped). Why?
After the whole program executed correctly, I get munmap_chunk(): invalid pointer and Aborted (core dumped) message in the terminal. Function for Radix Sort : I've designed the function in the following steps: Find Max value and calculate no. of digits in it. run the main loop for 'd' or no. of digits times. Each time...
I see an issue here, as C[10] is being used as an index, which is beyond last element of the vector. The easiest fix is to make C 1 element larger, and fix the count to index conversion loop: vector<int> C(11, 0); // fix (11) // ... for(int i=1; i <= 10; i++){ // fix ( <= 10) ...
62,374,357
62,383,466
header including error when using C++ file in Swift project
I am using C++ files in swift project, but in swift project, we can't use C++ file directly and should use objective-c file. So I created IFCEngineLib.h and IFCEngineLib.m file for using IFCFileParser.h and IFCFileParser.cpp. And in IFCEngineLib.mm, I include IFCFileParser.h file as following: #import "IFCEngineLib.h" ...
I found the way to solve this problem. I have to import the all header files of objective-C libraries using in the application in IFCEngineLib.m. I used PushKit in application, so I have to import <PushKit/PushKit.h> in IFCEngineLib.m. So IFCEngineLib.m file looks like as following: #import "IFCEngineLib.h" #import <Pu...
62,374,433
62,375,077
Alternatives of getline
#include <iostream> using namespace std; class publication { private: string title; float price; public: publication() { this->title = ""; this->price = 0.0; } void getdata() { cout << "Enter Title: "; getline(cin, title); cout << "Enter price: "; cin >> this->price; } void put...
Unfortunately the behaviour is fully according to the specification. std::getline works as expected. You need to read about formatted input and unformatted input to understand why it is implemented as it is. However, you are looking for solutions. There are basically 3: Use ignore after your formatted input. Unfortuna...
62,374,506
62,375,274
How do I align Glyphs along the baseline with Freetype?
I have written a function that creates an image from a font using Freetype2. My goal is to create an OpenGL-texture with all characters from the font. But first, I want to make sure the texture gets created properly, thus I store it as an image with stb_image_write for now. This is my progress so far: As you can see,...
I solved this issue with a simple fix, after I noticed that the actual height of the image was not calculated correctly. This is because the height of the "tallest" glyph does not represent the actual height of the image. For example, a character might be smaller than the tallest glyph, but placed higher above the base...
62,374,613
62,375,061
Why does declaring this variable in this method overwrite my class member (C++)?
I'm attempting to implement a linked list class. I have a struct called node that has data and a node*, as well as a linked list class that has a pointer to the head node of the linked list as a class member. I have written an insert method for the linked list class that inserts data into the nth position: void inser...
@UnholySheep pointed out the in comments that I just declared a pointer without creating a node object, so what occurs is undefined behaviour. Thank you very much.
62,374,729
62,374,755
ofstream : line break in csv file
I want to write and add a line in my "example.csv" file for each loop. I'm aware that at the moment my code just replaces each line every time. The problem is, I don't know how to add a line every time. Thanks #include <fstream> void loop() { getAngles(); std::cout<<"AngleX="<<angleX-angleX0<<" AngleY="<<an...
Open your file like this: csvFile.open("example.csv", std::ios_base::app); which will append lines to the file instead of overwriting it.
62,374,926
62,375,600
Normal Mapping Issues
I'm attempting to implement normal mapping into my glsl shaders for the first time. I've written an ObjLoader that calculates the Tangents and Bitangents - I then pass the relevant information to my shaders (I'll show code in a bit). However, when I run the program, my models end up looking like this: Looks great, I k...
I can spot 1 obvious mistake in your code. TBN is generated by the bitangent, tangent and normal. While the bitangent and tangent are transformed from model space to view space, the normal is not transformed. That does not make any sense. All the 3 vetors have to be related to the same coordinate system: vec4 bitan = V...
62,375,110
62,375,214
C++ declaration of template parameter shadows template parameter error
I have the following C++ code which I am compiling as below: #include <cstddef> #include <cassert> template<typename T, std::size_t N> struct A; template<typename T> struct Base { T &operator [](std::size_t i); private: template<typename T, std::size_t N> friend struct A; #if !defined(NDEBUG) size_t...
You are using the same name i.e., typename T in the outer and inner template: Outer: template<typename T> struct Base { ... Inner: template<typename T, std::size_t N> friend struct A; #if !defined(NDEBUG) Change either one to fix this. Inner fixed: template<typename U, std::size_t N> friend struct A; ...
62,375,285
62,375,550
Is it possible to call ACPI methods from C + + programs?
I hope to call ACPI methods through C++ library in C#, cause I am writing a uwp app for an OEM company, They provide an ACPI method to control the power supply of a USB device. but I seem to find in this link that ACPI methods cannot be called in C++ library(Correct it, I now know it's completely right). It says: "ACPI...
It’s of course possible to call ACPI from C++ if you run said C++ in kernel context or on bare metal (when your code runs directly on the hardware without an operating system as an intermediary). And you certainly could stick a C# runtime into kernel context and thus call ACPI from C#. It has been done: read up on Proj...
62,375,446
62,375,823
Why can't I reference a pointer to a function of an instantiated object?
EDIT: std::function + lambda to the rescue. See checked answer. EDIT: I added more detail, I want a generic solution, not one bound to Class B's definition. In the example below, I try to set a function pointer in one class to a function (of the same function pointer type) from an instance of another class, and Microso...
A function pointer to a free function and a function pointer to a member-function are two different things. To work around that we need some kind of wrapper. This is one of the good use cases for std::function. It's a type-erased callable with a given signature. To make it more generic you should make set_callback a te...
62,375,566
62,375,622
i want to print the non repeated number using hashmap;
// Driver Code Starts #include <bits/stdc++.h> using namespace std; vector<int> printNonRepeated(int arr[], int n); int main() { int t; cin >> t; while (t--) { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) cin >> arr[i]; vector<int> v; v = printNonRepeated(arr, n); ...
a[j] = x.first; j++; You can't access the jth index of a without having allocated space first. The size of the array needs to be predefined, or you can use push_back so that the vector adds a new element to the end. a.push_back(x.first);
62,376,605
62,376,914
How to check a binary tree is BST or not?
I am trying to determine if a binary tree is BST or not. My idea is while doing inorder traversal if the data is sorted then it is BST otherwise not. So that's why while doing inorder traversal I have inserted the values in a vector. then Checked it is sorted or not. If sorted then return true otherwise return false. v...
There's an easier way. Write a function that checks if a given subtree is a BST and all of the nodes are within a given range. // Checks if the tree rooted at current is a BST and // all nodes are between low and high bool checkBST(node* current, int low = std::numeric_limits<int>::min(), int high = std::numeric_li...
62,376,654
62,377,622
c++ scientific notation, change the digits of exponent
I am using this code to output a scientific notation number to a file: file << scientific << setprecision(10) << num << endl; For example, if the number is 3.0, I get 3.0000000000E+00 from the code. How do I make the digits of the exponent part to be 3 digits? I want to get 3.0000000000E+000.
It seems like as @Bob__ stated that visual studio used to have a function called: _set_output_format which allowed you to change the exponent BUT this was removed in the Visual Studio 2015 version I believe. As quoted in Portable printing of exponent of a double to C++ iostreams. The %e and %E format specifiers format...
62,376,806
62,377,497
print first repeating element using hashmap;
#include <bits/stdc++.h> using namespace std; int main() { unordered_map<int,int>h; int T; int n,i; cin>>T; while(T--) { int flag=0; cin>>n; int arr[n]; for( i=0;i<n;i++) { cin>>arr[i]; } for(i=0;i<n;i++) { h[i]=co...
Since you're using an std::unordered_map, the approach should be very simple: Set the minimum position to a large value. Loop on the number data from first item to last. If the number does not exist in the map, then Add the item and position to the map else Set the minimum position to min(minimu...
62,377,047
62,377,208
How to read *.txt file with non-english letters using c++? (internationalization)
I have a written code which reads text from a file and counts words and how many times they were repeated, as well as cout'ing URL links. But I do not know how make code read Lithuanian letters. I did not find a clear answer to this question on the internet. Any suggestions? Thank you.
The important question is what character encoding is used. You should know that. Today, in 2020, it is recommended to use UTF8 everywhere or at least something related to Unicode. But some computers or operating systems use other character encodings. You need to find out (perhaps by contacting the human who gave your t...
62,377,164
62,377,266
Return the foreground window from two windows
In win32 programming, given two overlapped windows, w1 and w2, how to get the foreground window?
GetForegroundWindow() gets you the actual foreground window (the window with the current focus). There can be only 1 window in the foreground at a time. If neither of your 2 windows are the foreground window, then there is no API available to directly determine which window is higher on the z-order than the other windo...
62,377,188
62,439,463
Need of :: to specify class for functions but not variables?
Why do I need to use :: to denote if a function is a member function but I don't need to do it for the instance variables? I do understand that :: is used to differentiate between standalone and member functions, but I still don't get the variables part. I'll give an example of what I'm talking about. Shape.h # pragma ...
C++ uses a model where it initially assumes everything is in the same namespace/class as what it's declared in unless stated otherwise. So, for example, if you write int getHeight() { return height; } at the top level of a C++ file, the compiler assumes you're declaring something in the global namespace. That mean...
62,377,467
62,377,710
c++ pass member function
I'm trying to make a class that can run a function a large number of times and tell me the average amount of time the function takes to execute. My solution uses template<class T_ret = void, class ... T_args> void RunNewTiming(string outputFileName, T_ret(*function)(T_args ...), int iterations = 1, T_args ... otherArg...
Update: I actually found a solution to this problem, I needed to pass in the caller type and an instance of this object I could then use the type to scope-operate to the correct function, T_caller::*function template<class T_caller, class T_ret = void, class ... T_args > auto RunNewTiming(string name, T_ret(T_caller::*...
62,377,607
62,377,827
*New Coder* Formatting and operators
Hi l just started learning C++ and I have a program for a prompt : It goes along the lines of asking the user for inputs of their assignments one at a time and once they have no more inputs, the program must display "Stop" It must ask the user if they have more scores to enter once each score (boolean type) It must a...
Keep adding other grades in the last lines using else if(your condition). If you want me to add anything else please tell me. using namespace std; int main(){ cout<<"Welcome to the Homework Point Sum Progam!" <<endl; cout<<"How many assignments did you complete?:"<< endl; int numberOfAsssignement=0; ...
62,378,053
62,385,743
How do I interface with extern variables from Cheerp/js?
Cheerp is a C++ to js/wasm transpiler. Screeps is a programming videogame. How do I read in the Game.time variable from my transpiled C++ code? (in screeps) #include <cheerp/client.h> #include <iostream> using namespace std; namespace client { class Game : public Object { public: static volatile doubl...
Classes declared in the client namespace should have no member fields. To access external JS objects properties you need to add methods starting with get_ and set_, to respectively read and write to the property: #include <cheerp/client.h> #include <iostream> using namespace std; namespace client { class Game : pu...
62,378,099
62,488,570
how do to declare a range::v3::View variable from an unknown view
I have almost the same question as a previous post: "How do you declare a ranges-v3 view return value?" But that answer simply said to avoid declaring a return type and use auto instead, which doesn't solve my problem, and I can't find this question anywhere. I need to create a struct that holds some type of view ret...
ranges::any_view was the answer that best solved my problem I'm able to create a structure with a member any_view<value_type> and use it like you would expect from a typical ranges::view, without having to know the exact type
62,378,251
62,378,354
C++: How do I count the number of nodes in a binary tree for which its value module its height is minor to 2?
I'm trying to implement a function which counts the nodes in a binary tree that respect the following condition: ( node->value % height )<2 I know it must be a recursive function and I tried to implement it as it follows: int count(Node* tree, int h=1){ if (!tree) return 0; if ((tree->value%h)<2) ...
With the statement return count(tree->left, h++) + count(tree->right, h++) + 1; you are incrementing h, which means that one of the calls to count might go with a higher value than the other one. Actually it is undefined behaviour, since the order of evaluation of the two h++ is not defined. Write... return count(tre...
62,378,256
62,378,453
How can I make a map where the value is an array of structs in C++
I have the following structure. struct Tourist { string name; string surname; string sex; }; I would like to sort tourists by families. int getMinRoomsAmount(Tourist touristsList[]) { map<string, Tourist[]> families; for (int i=0; i < 40; i++) { families[touristsList[i].surname] = // to append the array...
Map : You could use a map of string and vector of Tourist - map<string, std::vector<Tourist> > families; . Insertion : For adding a new element to a family, just use push_back() method of vector as - families[touristsList[i].surname].push_back(touristsList[i]); . This statement will simply add the family(Tourist st...
62,378,260
62,378,762
How to read data in text file and assign arrays each column c++
I want to learn how to read a text file (contain 3 columns 300000+ rows) and assign each column of the text file to different arrays in c++. I searched this on the internet but i could not find any suitable solution for this. I found a code to do this but the code read only 547 rows. The code is below. #include <iostre...
As mentioned in the comments, you probably have some garbage in the file and you are probably better off storing what you read in one vector. To be able to find garbage more easily, you could throw an exception when reading fails. Example: #include <stdexcept> // a class to store the values on one line in the file str...
62,378,363
62,378,444
How do i load a textfile to QListwidget and also save it back
How do i load a text file into QListWidget , such that each line in the textfile is an item in QListWidget, and once i populate it, i also want to save all items of listwidget into a text file , such that each item of listwidget is in a line in the text file , to accomplish that i am attempting this QString temp; fo...
Qt provides QFile and QSaveFile classes for convenient file input/output operations. QSaveFile is special in as it will only (over)write the destination file when you commit it. For both parsing and writing the file contents, you can use QTextStream, which exposes the file contents as a stream you can read from or writ...
62,378,469
62,378,716
I am getting segmentation fault for three test cases for the question "TWO STRINGS" in hacker rank. What is the reason?
The code is as follows: The link to the question is : Two Strings #include <bits/stdc++.h> using namespace std; // Complete the twoStrings function below. string twoStrings(string s1, string s2) { long long int i,j; long long int m=s1.length(); long long int n=s2.length(); long long int dp[m+1][n+1...
It's helpful to debug problems like this by testing locally, where you can add cout debugging statements throughout the code to figure out when the segfault occurs. If you can download the exact testcase which caused the failure, then you can run that locally. The problem statement states that the input sizes for the...
62,378,592
62,378,603
How to read a file at compile time in C++?
I have been trying to look for a way to store files as const char* at compile time. I tried doing this: #define STRINGIFY(...) #__VA_ARGS__ // va args deals with commas #define INCLUDE(path) #include path // error: '#' is not followed by a macro parameter constexpr const char* source = STRINGIFY(INCLUDE("source.txt"))...
the classic way to do this is to write an awk or perl script that reads the data file and generates a .H file
62,378,831
62,382,219
Changing color of a pushButton in QT
I want to Change the Color of a pushButton in QT after the button is clicked. The Problem is that when I have multiple Buttons all the pushbButton`s Colors Change. How can I make only the one i clicked on Change? PS: I am a beginner so it would be really nice if you could explain your solution in Detail, sry :D. My Cod...
How can I make only the one i clicked on Change? you set the property to the button instance then: call the set style in that button: ui->pushButton-> like doing: void MainWindow::on_pushButton_clicked() { if((i==1)) { ui->pushButton->setStyleSheet("QPushButton { background-color: grey; }\n" ...
62,378,836
62,378,869
When I input 1900 for the year and 2 for the month I get 29 when it should be 28
Write a program month.cpp that asks the user to input the year and the month (1-12) and prints the number of days in that month (taking into account leap years). You may not use switch case or arrays even if you know these language constructs. I understand using namespace std is a bad practice. However, my professor ...
The problem occurs in the if(year%4) statement. I'm guessing that you're meaning to say "when the year is divisible by 4, output 29 days". However, your if-statement does not actually do this. This if-statement first evaluates (year%4) then outputs 29 days if it ends up being true. In C++, an expression is true when it...
62,378,853
62,378,915
What can I do to get rid of this syntax error on using namespace?
I know everyone is going to say to not use namespace on everything but I don't know what I would need to do to get rid of it. I'm trying to create a simple program that has three items that are part of a class and take user inputs for two of the functions. header: #include <iostream> #include <string> using namespace s...
class retailItem { // ... class declaration } Your class declaration is missing the trailing semicolon, here. #include "items.h" using namespace std; An #include statement is equivalent to directly inserting the contents of the included file into the including file, verbatim. So, you are asking the compiler to, ...
62,378,903
62,379,114
Longest Palindromic Substring (C++ Help)
I had trouble printing my output for the longest palindromic substring and have not yet figured out. My code prints out a palindrome if the input is a palindromic string, but is not able to print out the palindromic substring. There is something wrong with the else function of this code and wanted to know where the bug...
The problem occurs in the innermost loop. for(int j = 0; j < size - 1; j++){ for(int k = size - 1; k > 0; k--){ if(str[j] == str[k] && k != j){ for(int i = size - 1;i > 0;i--){ newStr += str[i]; } } k = 0; j = size; } } I think that you're...
62,379,020
62,379,211
Thread calling function with non-static members failing
I created a function void top() to render out an image by sending a ray for each pixel. I wanted to put it on a thread. I used #include <thread> library but when I declared the thread in the main() method it gave me two errors: Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &...
From `std::thread::thread: The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with std::ref or std::cref). So, just wrap each variable that you take by reference in one of the wrappers. Prefer std::cref if y...
62,379,187
62,379,270
How can I use fixed << setprecision(2) only ONCE? Or at least restore to default behaviour?
This is inside of a display function. I want to print the weight using 2 decimal points. Outside of this code block, I don't wan't setprecision to be in effect. For example, 777.555 and 444.2222 should display correctly. // Detect if train has cargo: if (cargo_unit) { // If cargo ...
You can save the previous flags and precision, and then restore them afterwards, eg: // Detect if train has cargo: if (cargo_unit) { // If cargo exists, print output: std::ios_base::fmtflags old_flags = cout.flags(); std::streamsize old_prec = cout.precision(); std::cout << std::fixed << std::setprecis...
62,379,709
62,380,264
Could someone explain in detail on how this palindrome code works?
#include <iostream> // Define is_palindrome() here: bool is_palindrome(std::string text) { std::string reversed_text = ""; for (int i = text.size() - 1; i >= 0; i--) { reversed_text += text[i]; } if (reversed_text == text) { return true; } return false; } int main() { std::cout << is_palindrome("madam") << "\n...
To begin, we define the is_palindrome function to return a bool. Our input string is the function parameter. Then, we reverse the text using the following for loop. std::string reversed_text = ""; for (int i = text.size() - 1; i >= 0; i--) { reversed_text += text[i]; } This code simply defines a string called reverse...
62,379,825
62,379,872
String variable not updating c++
I have a program that basically opens a .sql database file and returns the table names into a string vector. This string vector is stored as tableNames and contains the tables within a given database file. For some reason that I cannot understand, the tableName parameter in the sqlCreateTemp string is not updated, but ...
Your computer executes your code one statement at a time, in a logical manner. string tableName; This creates a new std::string. It is an empty string. string sqlCreateTemp = "CREATE TABLE tempLog AS SELECT * FROM " + tableName + ... This creates another std::string, whose contents includes tableName. Which is empty,...
62,379,959
62,380,173
vector contains extra values beyond its size in c++
I have a vector of a structure, and the structure is a triplet of values. struct Process { int64_t id, arrivalTime, burstTime; }; vector<Process> parseInputFile(string filename, vector<Process> &vec){ ifstream inFile; int64_t arrival; int64_t burst; inFile.open(filename); if (!inFile) { cerr << ...
As the comments mention, you can't just read memory beyond your vector's allocated space and NOT expect garbage. Your RAM will look a bit like this (very simplified): Address | Value --------|------- 0x00001 | garbage 0x00002 | 1 <--- vector vec points here (vec[0]) 0x00003 | 2 0x00004 | 3 <--- three ele...
62,379,989
62,380,085
How do I edit/fix this class?
I wanted to practice building classes. I learned in my class that having leaked memory is never good, When I call this class, am I creating an object and do I need to add a delete function in my destructor to avoid leaks? Thank you!!! #include <iostream> #include <string> using namespace std; class Quadratic { public...
I can see three problems with your code, first of all the destructor: In the destructor you should free any dynamic items created in this case you have none which is good, also you should set your variables to their default value. Reset values for a, b, and c. Secondly the call problem->evaluate shouldn't work. I would...
62,380,006
62,380,056
C++ templated packs, fold twice
I have read some questions that are similar but I don't find the exact thing I am looking for. In a purely mathematical way a list is defined recursively as: (head, rest). Where head is the first element in the list and rest is a list. So for example (1,2,3,4) is represented as (1, (2,(3,(4,[])))) where [] is the empty...
You can unpack the parameters 2 at a time, like this: template <typename T1, typename T2, typename ...Ts> auto sum_products(T1 t1, T2 t2, Ts ...ts) { return t1 * t2 + sum_products(ts...); } and provide a base case overload for no arguments: auto sum_products() { return 0; } and then use it like this: std::cout << s...
62,380,904
62,380,971
Strange behavior when calling std::invoke(std::forward(...)) with address-sanitization in a std::thread with a std::ref
Problem I am trying to pass a lambda-closure to std::thread that calls arbitrary closed-over function with arbitrary closed-over arguments. template< class Function, class... Args > std::thread timed_thread(Function&& f, Args&&... args) { // Regarding capturing perfectly-forwarded variables in lambda, see [1] auto...
Both versions appear to be undefined behavior. It is potluck whether the undefined behavior will be caught by the sanitizer. It is fairly likely that even the allegedly working version will also trip the sanitizer, if the program is rerun sufficient amount of times. The bug is here: std::thread timed_thread(Function&& ...
62,381,589
62,381,778
why i am getting segmentation fault error while calling this function?
Below function receives two arguments one is 'magazine' which contains strings and other is 'note' which also contains note. If 'magazine' contains all the 'note' strings the we have to print Yes else No. void checkMagazine(vector<string> magazine, vector<string> note) { map<string, int> m; int n = magazine.s...
Here is my correct code after refining the errors: void checkMagazine(vector<string> magazine, vector<string> note) { map<string, int> m; int n = magazine.size(); for(int i=0; i<n ; i++){ if(m.find(magazine[i]) == m.end()) m[magazine[i]] = 1; else m[magazine[i]]++; ...
62,382,187
62,382,441
c++ How to initialize char in constructor
#include <iostream> using namespace std; class MyClass { private : char str[848]; public : MyClass() { } MyClass(char a[]) { str[848] = a[848]; } MyClass operator () (char a[]) { str[8...
How to initialize char array in constructor? Use a loop to copy element by element: MyClass(char a[]) { //make sure that sizeof(a) <= to sizeof(str); // you can not do sizeof(a) here, because it is // not an array, it has been decayed to a pointer for (int i = 0; i < sizeof(str); ++i) { str...
62,382,617
62,382,770
collect2: error: ld returned 1 exit status undefined references
This is my code for an online shopping cart containing two items. I'm getting the following linker error. c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\chine\AppData\Local\Temp\ccQnOWnO.o:main.cpp:(.text+0x121): undefined reference to `ItemToPurchase::SetPrice(int) I get similar error...
Make sure SetPrice(int price) is defined in class ItemToPurchase in ItemToPurchase.h.
62,382,741
62,382,833
probleim with sending and receiving file from socket c++
im trying to send a file from server to a client Ive got this function in my server: UINT CServerDlg::sendFile(WPARAM pParam) { if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { return FALSE; } else { if (AfxSocketInit() == FALSE) { return FALSE...
You must to allocate memory for buffer, because first parameter of fread: Pointer to a block of memory with a size of at least (size*count) bytes, converted to a void*. Use malloc or new. I would recommend using std::array to not worry about deleting memory.
62,383,272
64,543,372
VScode setup with ROS and auto complete
I am struggling to configure VSCode with ROS to have the auto-complete function. I am used to using VSCode with Qt and OpenCV and everything worked fine. For example, for OpenCV, I just edited c_cpp_propreties.json like this: { "configurations": [ { "name": "Linux", "includePath": [ "${w...
I had a problem when using the IntelliSense with ROS. It would simply not search the ros namespace, no matter what I did. So I thought of changing the cppStandard (in file c_cpp_properties.json) to gnu++11 (it's only for IntelliSense anyways). It immediately started working. Here are the results with cppStandard set to...
62,383,537
62,383,649
How to use function to copy one object's input into the other
#include <iostream> using namespace std; class MyClass { private : char str[848]; public : MyClass() { } MyClass(char a[]) { for(int i = 0 ; i < 848 ; i ++) { str[i] = a[i]; } } MyClass operator () (char a[]) { for(int i...
You can do it like this: #include <iostream> using namespace std; class MyClass { private: char str[848]; public: MyClass() { } MyClass(const char* a) { for (int i = 0; i < 848; i++) { str[i] = a[i]; } } MyClass operator () (char a[]) { ...
62,384,236
62,384,358
invalid conversion from ‘char*’ to ‘char’ [-fpermissive] How to print?? But inside the variable
struct student{ char name[30]... }; struct element { struct element *ant; struct student databse; struct element *prox; }; Element *no = *pointer_to_pointer; cout<< (*no).datbase.name << endl; I printed the name correctly. Element *no = *pointer_to_pointer; char variable = (*no).datbase.name; c...
The type of datbase.name is char[], which means you can not assign it to a char variable directly. Use char *variable instead: char *variable = (*no).datbase.name; cout<< variable << endl; if you want to print just one character, write: char variable = (*no).datbase.name[0]; //the first character of 'name'
62,384,260
62,384,425
I get this error for having defined a function twice
Error: CMakeFiles\Final_Project_2nd.dir/objects.a(Tab.cpp.obj): In function `Z8Type2IntNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE': C:/Users/Andrea/CLionProjects/Final_Project_2nd/Utils.hpp:37: multiple definition of `Type2Int(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)' C...
You are defining the function in the header, that's the problem. multiple definition in header file The inline solution is fine, in alternative you can keep the declaration in the hpp file and implement it in a separate cpp file - which is the most 'standard' solution.
62,384,317
62,393,648
Particle system: All particles move in the same direction
I'm trying to create a particle system. In the ParticleSystem constructor I create new particles with a random color and velocity. When I run my code, all particles have different colors but move in the same direction #include "stdafx.h" #include "ParticleSystem.h" ParticleSystem::ParticleSystem(){} ParticleSystem::Pa...
for (int it = 0; it < pAtm; it++) { particleVector.push_back(Particle(size, sides, velocity, pAtm)); } You're giving all your particles the same velocity vector. If you want a random velocity for each particle, you need to generate a new random velocity for each particle : for (int it = 0; it < pAtm; it++) { ...
62,384,530
62,384,727
Make compiler to tell what exact pure virtual methods make struct abstract?
struct Base{ virtual foo()=0; virtual bar()=0; }; struct Derived:Base{ virtual foo(){} //bar() is still pure virtual }; static_assert(is_constructible_v<Derived>,"You forgot to override few methods: i do not know what are they.") "i do not know what are they." How to replace this phrase with exact list of me...
Perhaps you simply need to ask the compiler to attempt a compile time instantiation. For example: static_assert(sizeof(Derived[1]),"...");
62,384,664
62,384,974
calling derived class member function
class MyArray { private: string name; string message; string sentence; public: MyArray(string name) : name(name) {}; virtual void display() { cout<<message<<endl; }; MyArray(); ~MyArray(); }; //derived class class MyArrayWithStamp : public MyArray { public: string message; MyArray...
There are some problems: you can't access private members of MyArray from MyArrayWithStamp. You should use protected or a public method. MyArray *p: p is a pointer to variable of type MyArray that doesn't have any member function called input. You should either define input in MyArray or declare MyArrayWithStamp *p = ...
62,384,725
62,385,087
How to initiialise the copy constructor for a map?
I've been banging my head against this for at least two hours, there are probably missing gaps in my knowledge here. Basically, I have to write the function for a copy constructor and I can't get it to work no matter what. I'm absolutely overlooking something here because this doesn't seem all that complicated. // Defi...
Since it is a construction, you probably need to create members with new (which, BTW, there seems to be absolutely no reason to use it here, see farbiondriven's answer). Then you must copy members from the other class. This is breakdown: // Definition copy constructor Members::Members(const Members& mem) { members ...
62,384,730
62,385,429
Bitcoin core libbitcoin_server_a-httpserver.o Error
I'm trying to install a custom fork of bitcoin core from HERE And when compiling, I get the following error: I have installed all the prerequisites i think Making all in src make[1]: Entering directory '/home/muhammad/Programs/SimorghCoin/src' make[2]: Entering directory '/home/muhammad/Programs/SimorghCoin/src' CXX ...
The include for deque is missing in /home/muhammad/Programs/SimorghCoin/src/httpserver.cpp. You can add a line #include <deque> after line 32.
62,384,924
62,386,014
C++ is there a way to force a set of methods to be overriden, if one of them have an override in child class?
It a design question. So, I got an abstract class with a lot of pure virtual methods. Sometimes, I realized I don't need to override these methods, because I'm not interested in these functionnalities. So I changed from pure virtual (=0) to a simple overridable empty method. But now, a child class can override one meth...
A simple solution is to keep the abstract class and to have a default child class, like this: class AbstractMap<TKey, TValue> { public: virtual TValue Get(TKey&& key) = 0; virtual bool TryGet(TKey&& key, TValue& result) = 0; }; class PartiallyImplementedMap<TKey, TValue> : public AbstractMap<TKey, TValue> { p...