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
64,841,399
64,843,018
Identifier "buildTree" is undefined
Have a simple error. Looked at a bunch of posts and checked the causes on my files, but couldn't seem to fix it. The functions being called from my BST.cpp file are throwing the error in the title ("identifier "buildTree" is undefined). The functions in question are 'buildTree' and 'performSearchBST'. The CPP file is i...
You have a simple error here. First and foremost, your compiler doesn't know what is buildTree(String). You have a non-static member function whose name is BST<T>::buildTree(String). Secondly, as said in the comments, you cannot use such a non-static member function without an object of that type, since it operates on ...
64,841,542
64,841,649
do while loop without {}
Is the below syntax of writing do while loop containing single statement without using braces like other loops namely while, for, etc. correct? I'm getting the required output but I want to know whether this has any undefined behavior. int32_t i = 1; do std::cout << i << std::endl; while(++i <= 10);
The original resource to answer this question should be the C++ standards: http://www.open-std.org/jtc1/sc22/wg21/docs/standards. In C++17, 9.5 Iteration statements [stmt.iter] says do takes a statement: do statement while ( expression ) ; So this is definitely fine. 9.3 Compound statement or block [stmt.block] says ...
64,841,633
64,841,827
C++ merging linked list issue
So I'm a beginner to C++ and I have a school project to create a linked list and I'm working on the merge method right now and I'm not sure why it's not working. I identified the problem to be in the second if in the while loop where instead of changing the head_ list node it's changing the list1 list and I don't know ...
I find working with linked lists easier with references and recursion over the list iterators. This version makes sure the second linked list is left in a valid state (though maybe changed), and no new memory is allocated. template <class T> bool List342<T>::Merge(List342<T>& list1) { merge(head_, list1.head_); } te...
64,841,670
64,841,748
Unknown behavior of Round function in C++
#include <iostream> int main() { double number1 = 1.4999999999999999; double number2 = 1.499999999999999; std::cout << "NUMBER 1 => ROUND (" << number1 << ") = " << round(number1) << std::endl; std::cout << "NUMBER 2 => ROUND (" << number2 << ") = " << round(number2) << std::endl; std::cin.get(); } Output f...
#include <iostream> int main() { double number0 = 1.5; double number1 = 1.4999999999999999; double number2 = 1.499999999999999; std::cout << (number1 == number0) << " " << (number2 < number0) << std::endl; } The above outputs 1 1 on platforms that use IEEE-754 for representing floating points. In th...
64,841,681
64,842,538
c++ variadic parameter join path
I try to write a join path function with variadic template. Here's how i do it: template<typename T> T&& join_path (T&& path) { return path; } template<typename T, typename ... Args> std::string join_path (T&& path1, Args&& ... paths) { static_assert(std::is_same<typename std::decay<T>::type, std::string>::val...
You might use std::string_view since C++17: std::string join_path(std::initializer_list<std::string_view> paths) { std::string res; const char* sep = ""; for (auto p : paths) { res += (!p.empty() && p[0] == '/') ? "" : sep res += p; sep = "/"; } return res; } template<typena...
64,841,705
64,851,627
Control C++ Standard Revision in visual studio 2019
So I am using the visual studio 2019 for my C++ projects, I wanted to control the C++ version when compiling. I have changed it from "project > properties > C/C++ > Language > C++ Language standard > " It was on Default (ISO C++14 Standard) I used this to check the version: #include<iostream> using namespace std; int...
According to Microsoft Docs: The __cplusplus preprocessor macro is commonly used to report support for a particular version of the C++ standard. Because lots of existing code appears to depend on the value of this macro matching "199711L", the compiler does not change the value of the macro unless you explicitly opt-i...
64,842,140
64,843,020
std::vector inaccessibility with const onject
I was trying to overload the << operator for the Histogram class, whose header file is: #ifndef HISTOGRAM_H #define HISTOGRAM_H #include<bits/stdc++.h> class Histogram{ private: std::vector<float> listOfElements; std::vector<float> sortedListOfElements; std::vector<float> bucketValues; ...
In the provided code you are not using "using namespace std" in the header, which is correct, so ostream is not defined (unless it is made a member of the global namespace in bits, which would be bad) and the compiler may treat the two occurrences of ostream as different types so the friend operator<< declared in Histo...
64,842,186
64,842,222
template or member function selection
I've been trying to understand the way C++ selects templates or member functions. Consider the following code sample: #include <iostream> #include <string> struct Test { template<typename X> explicit Test( X&& s){ std::cout << "1" << std::endl;} explicit Test( const std::string& s) { std::cout << "2"<...
The constructor template's parameter is declared as forwarding reference. When being passed an lvalue such as line, the template parameter X is deduced as std::string&, and after reference collapsing the parameter type is std::string&, i.e. an lvalue-reference to non-const std::string. It's an exact match and wins in o...
64,843,150
64,850,238
C++ Decompressing a file, then compressing the decompressed data does not give the same file as a result
I'm using ZLib along with header files from https://github.com/mapbox/gzip-hpp to handle gzip files. I have been trying for days now. I have a file say "abc," and as I decompress it, I compress it back and save the compressed result in another file "xyz." Now, theoretically, data of "abc" should be equal to "xyz," but ...
There is no reason to expect nor any need to be able to reconstruct the same compressed data. What is guaranteed for lossless compression is that x -> compress -> decompress -> y will result in y being exactly the same as x. There is no guarantee for p -> decompress -> compress -> q that q is the same as p, or similar ...
64,843,971
64,850,271
C++ priority_queue of tuple is slow
I need to process a dynamic sorted list of events in C++. Each event is composed of 3 variables: the time (used to sort the list) and 2 others. I process data events by events, take the first one in the sorted list (with the lower time variable), process it, and then remove it from the list. During the processing of ev...
The std::priority_queue is for all intents a heap, lg2 N push and pop. Note for a million items that would be 20KM, K small constant, M memory accesses. Memory usage 8MB, for a single core, so time to upgrade to a CPU that gives L3 access to at least that much memory. This can be improved to lg lg N (the Thorup equival...
64,844,096
64,846,253
Vector building optimization using std::move
I'm building some std::vector<Obj> where Obj are large objects which can be move constructed and assigned (think eg of Obj being large vectors). The code is typically a loop such as std::vector<Obj> v; while (...) { Obj foo = some client code(...); // ... some complicated stuff modifying foo v.push_back(foo...
The compiler is not allowed to call the move constructor or elide the objects without you explicitly moving (ie, casting to an rvalue reference; possibly by std move) except under very specific situations. A) the object is a temporary unnamed object. B) The object is being returned from a function. There are a few othe...
64,844,256
64,844,404
Memory problem, converting string into char and getting this " invalid conversion from 'char*' to 'char'"
I have an assignment where it is very important to save memory. I have done this function ( truly not me, but a guy in a question I did some days ago Conversion from english to morse,and then to binary- code doesn't display anything ), String getMorse( char character) { // if character is a space, a long space ...
This code char morse_code[27][5] defines morse_code as a two-dimensional array of char elements. Or (maybe a more precise definition) an array whose elements are arrays of 5 char elements. If you take one element of the 2-D array using code like morse_code[...], it will be a 5-element array of char. In C++, any array ...
64,844,656
64,845,107
How can I declare same object name for different class?
Normally this is my code #include <iostream> using namespace std; class On { public: int value; }; class Off { public: int value; }; int main() { On push; push.value = 1; cout << push.value << endl; return 0; } Here is added two classes named On, Off. I want to create the same obje...
You can use scopes: #include <iostream> using namespace std; class On { public: int value; }; class Off { public: int value; }; int main() { { On push; // 'push' object for the class -> On push.value = 1; cout << push.value << endl; } { Off push; // 'push'...
64,845,041
70,001,526
Dart ffi - Call Dart From C++
I am making a flutter application where I have my backend as C++. Through dart ffi I am signalling a load call when user enters a certain screen. My problem is Im loading audio in C++ but I want to signal dart that the loading has finished so that I can stop showing a loading screen. AFAIK, there is no way to call dart...
Currently, the only way to make asynchronous callbacks is through the native ports in dart_api_dl.h (and dart_api.h). Sample code: Dart code C/C++ code For more info see the issue for adding support for async callbacks to dart:ffi.
64,845,756
64,978,664
Displaying two different images in OpenGL
I just started working on OpenGL recently. I need help when it comes to displaying two images in separate objects with two different texture units. The first image is rendered twice instead of getting two different images. Please what do you think could be wrong? int width, height, width1, height1; unsigned char* ...
You are using two different texture units when drawing, but the same texture unit when binding and loading the 2 textures. Either remove glActiveTexture(GL_TEXTURE1); from before drawing or use glActiveTexture(GL_TEXTURE1); before your second texture load
64,846,269
64,848,315
Cast shellcode inside function pointer
I am trying to perform a system call on 32-bit, but there is an issue. I originally had a naked function as my stub and used inline assembly, but when I tried to turn it into shellcode, despite it being a 1-to-1 copy of the naked function (When looking at it in Visual Studio's disassembly), it does not function (Access...
As noted by Micheal Petch, the shellcode was wrong. I only missed one byte (0x0C) that should be 0xC0. If anyone will ever attempt something so stupid and useless like I did, double-check your shellcode first!
64,846,291
64,867,284
Lua library doesn't linking
I get undefined reference to 'luaL_openlibs' when I try to execute the following code extern "C" { #include "../lib/lua.h" #include "../lib/lualib.h" #include "../lib/lauxlib.h" } int main(int argc, char *argv[]) { lua_State *L = luaL_newstate(); luaL_openlibs(L); return 0; } this is my VSCode tasks ...
You're getting 32-bit and 64-bit mixed up. If your gcc builds 32-bit executables, then you need to use the 32-bit binaries from http://luabinaries.sourceforge.net/download.html, not the 64-bit ones. When I mixed these up on purpose, I got the exact error that you're getting, and when I used the right ones, it compiled ...
64,846,318
64,851,805
Excessive cursor reference highlighting VS Community
so I have been using VS Community for a while now to code in c++ and somehow must have activated reference hightlighting. Now every time my cursor is inside a word it highlights every occurence in the entire file. This gets very confusing especially inside nested loops: I tried looking for reference highlighting but c...
If you want to disable all cursor highlighting, you could set True in Tools->Options->Text Editor->C/C++->Advanced->References->Disable Reference Highlighting. If you want to customize the cursor highlighting, here is a solution for reference. This tip was proposed by Sairama Jamalapuram. Syntax coloring for user-defi...
64,846,521
64,846,565
How do I allocate an array in a function that is at the same time an input argument?
I'm busy with an assignment, but I'm not sure how to tackle a problem. As a part of a program I need to write an add function. The goal of the program is to: Read two integer values n1 and n2 from the command line. Allocate two integer arrays array1 and array2 of size n1 and n2 inititalize the two arrays with values...
You need to allocate the array inside the function, but also return the allocated array through the "output parameter" array3. To return something through an output parameter, the parameter needs to be a pointer; but to return an array, the array itself is also a pointer. So what we need is indeed a pointer to a pointe...
64,846,587
64,846,767
How to create templatized wrapper class in C++
I am invoking a function from many places in the project. Only difference is that one of the parameters is of different data types. I was asked to create a templatized wrapper class. Could someone help me how to do that? I am invoking the below function from different places. Here when invoking this function, the secon...
According to your specification, it should be something like: template <typename T> std::shared_ptr<CCallListImpl> CCallListImpl::handleCallCollectionEvents(Events f_eCallEvent, const T& f_strCallid) { shared_ptr<CCallListImpl> l_hObj = nullptr; return l_hObj; }
64,846,957
64,852,821
Is there any difference between auto and __auto_type?
I've been using __auto_type in C for sometime now and I was wondering if it's any different from auto in C++. Are they implemented differently? I've tried searching for this, but it doesn't yield any results, since searching for __auto_type in C returns articles about auto in C++. It feels like a forgotten keyword.
As StoryTeller commented, it's a GCC extension in C mode. It doesn't work in C++ In GNU C, but not GNU C++, you may also declare the type of a variable as __auto_type. In that case, the declaration must declare only one variable, whose declarator must just be an identifier, the declaration must be initialized, and the...
64,847,270
64,847,314
Lambda black magic taking different types
Trying to find yet another way to simply serialize my code, I had the stupid idea to try this impossible thing. But it worked. I really wonder why: template <typename C> void f(C c) { int a = 1; float b = 1.5f; c(a); c(b); } int main() { f([](auto v){ std::cerr << v << "\n"; }); ret...
This call: f([](auto v){ std::cerr << v << "\n"; }); is passing a generic lambda to f, as the argument c. A generic lambda is one that has a templated member operator(), because of the auto parameter. So when you make the following calls: c(a); // int argument c(b); // float argument the compiler will i...
64,848,122
64,848,172
The attributes of a user made object won't print (C++)
I am trying to make an object with a series of user inputs but it doesn't seem to be working. Here is the code: (No Errors occur) Making the class and using a constructor function so if it wasn't user made it would be easier to enter details: #include <iostream> using namespace std; class Person{ public: strin...
Your constructor has the initializations the wrong way around. Try this: Person(string aFirstName, string aSurname, string aGender, int aAge, double aMoney){ FirstName = aFirstName; Surname = aSurname; Gender = aGender; Age = aAge; Money = aMoney; }
64,848,362
64,848,629
when I execute linked list using class it shows an extra zero
#include<bits/stdc++.h> #include<vector> using namespace std; class Node { public : int data; Node *next; Node() { data = 0; next = NULL; } Node (int a) { data = a; next = NULL; } }; void push(Node **head_ref , int n) { Node *new_node = new Node(); ...
Node *head = new Node(); Creates the extra node. Instead use Node *head = nullptr; or, if using an older compiler, Node *head = NULL; to point head at a safe location until legitimate nodes are added.
64,848,817
64,848,848
Binary String to Integer Stack
Struggling to separate a string into a stack containing 1's and 0's. Currently I am trying to iterate through the string and parse them into integers to add to a stack. I am entering 1010, in which the result is 1010 , 010, 10, 0 instead of the desired stack being 1, 0, 1, 0 I have used atoi and stoi along with indexin...
stoi(&input.at(i)) should be input.at(i) - '0' or, since you are only dealing with zero and one the even simpler input.at(i) == '1' also works (as do many other variations). Your mistake was taking functions that are intended to convert a sequence of digits to a number (stoi and atoi) when all you wanted to do is co...
64,849,123
64,849,248
Generic "sqr" function
I'm trying to figure out how to write "fully generic function" for sqr operation (it's actually can be multiply, division, add, does not really matter). Consider the following code #include <iostream> struct A { int val = 2; A() = default; A(const A&) = delete; // To make sure we do not copy anything ...
auto&& sqr(auto&& val) { return val * val; } sqr above always returns a reference. But returning a reference to a local is always wrong. Let the return-type deduce to a non-reference by using auto instead. auto sqr(auto&& x) // return type is non-reference or trailing noexcept(noexcept(x*x)) // propagate noexcept ...
64,849,187
64,849,302
make error: “g++: error: bin/main.o: No such file or directory”
I'm trying to compile a program I wrote, and the structure of the directory is the following: ctrace > bin, include, src, makefile bin> include > Agent.h, Graph.h, Session.h, Tree.h src> Agent.cpp, ContactTracer.cpp, Graph.cpp, main.cpp, Session.cpp, Tree.cpp, Virus.cpp The error I'm getting is the following: g++: err...
You are missing bin/main.o as dependency for cTrace target. That's why make does not compile it, and resulting object file is missing. Just add bin/main.o to your list of dependencies in line 4.
64,849,244
64,849,277
Vector<double> as class member variable
Just like I'm creating member variables for x, y, and theta, how would I create member variables for the type vector<double> in the constructor? What I'm doing below doesn't seem to work. Positioning::Positioning(double x, double y, double theta) { this->globalX = x; this->globalY = y; this->globalTheta = t...
This works Positioning::Positioning(double x, double y, double theta) { this->globalX = x; this->globalY = y; this->globalTheta = theta; } All your class variables are created automatically, you don't have to do anything special to create them. The code in the body of the constructor above is not creating ...
64,849,343
64,849,469
Is there any conversions when storing/reading integers of different size to/from union?
Reading Rapidjson code I found some interesting optimization with "type punning". // By using proper binary layout, retrieval of different integer types do not need conversions. union Number { #if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN struct I { int i; char padding[4]; ...
So is it legal in C++? No, it isn't legal in c++ (Wikipedia also already stated "While not allowed by C++ ..."). In c++ a union is just reserving memory for the contained union members, such that it is enough to fit the largest member. That memory is shared by all members. Accessing a different member from the union ...
64,850,087
64,850,375
Open terminal from gVim
I was wondering if there is a way to compile a c++ file in gVim and then to run it by pressing a button and to open a terminal with the corresponding cpp .out file. Now I have this 2 lines in my .vimrc for compiling and runing: map <F5> :<C-U>!g++ -O2 -DLOCAL -std=c++11 -Wall -Wextra -Wno-unused-result -static %:r.cpp ...
You can change map <F9> :<C-U>!./%:r<CR> to map <F9> :<C-U>!x-terminal-emulator -e ./%:r -hold<CR> In fact, you can use any of your favorite terminal. Just check how to pass in commands to the terminal. In most of the cases, it is -e. -hold is to hold the terminal from vanishing. To get more insight, read How can I m...
64,850,250
64,850,345
N queens solution is incorrect and im not sure why
So I am solving the N queens problem, where you have to find the number of possible solutions to have a number N queens on an NxN chess board without them being able to attack each other. I am doing it using recursive backtracking. I have implemented my solution in code already, but for some reason I am not getting the...
Your problem is with the isSafe function where you are not checking fully the diagonals: bool isSafe(vector<vector<int>>board, int row, int col){ //checks column for queens int n = board.size(); for(int i=0; i<row; i++){ if(board[i][col]==1){ return false; } } //checks right diagonal for queens(\) fo...
64,850,300
64,850,711
VMMap reports ~100 GB allocations
I have an application, I am afraid that there is a memory leak. Investigating it with VMMAP I see that most of allocation are reserved memory. It should not influence on performance....? Still the question is - what could be the reason for such amount of reserved memory (how can I investigate it?)Can it influence a per...
This Microsoft documentation page can explain what reserved memory means - https://learn.microsoft.com/en-us/windows/win32/memory/page-state: Reserved The page has been reserved for future use. The range of addresses cannot be used by other allocation functions. The page is not accessible and has no physical storage a...
64,850,437
64,850,525
How to construct makefile to compile AND run the binary?
I would like to compile and run in one rule. Now I have : CC = g++ %: %.o $(LINK.c) $^ -o $@; ./$@ But the make only compiles the source to binary, but do not run it. How to construct make to do this in one step? Having file foo.cpp. Applying the makefile: user@Host:~/Desktop/bin/2$ make foo g++ foo.cpp ...
I suspect you are being tripped up by the implicit rules in make. It already knows how to a) make an object file from a C++ source and b) how to link. So I suggest to rewrite the Makefile to be more explicit. One example would be all: g++ -c hello.cpp g++ -o hello hello.o ./hello where I redefine the defa...
64,850,573
64,850,695
When i use cout.tie(NULL), program doesn't print anything for my code, but if i print endl, program works fine
#include <bits/stdc++.h> using namespace std; void scan_a_line_indefinitely() { // scan line indefinitely string input_line; while(getline(cin,input_line)) { cout << input_line ; **// doesn't print if i use this line** //cout << input_line << endl; **// if i use this line, it works fi...
std::cout will flush under these conditions: An input-stream which is tied to std::cout tries to read input. You removed the ties. iostreams are synchronized with stdio, thus effectively unbuffered. You disabled the synchronization. The buffer is full. That takes a bit longer. The program ends normally. That comes ...
64,851,252
64,852,128
Trouble using Python ctypes to run C dll function (array output with unknown size)
I'm trying to execute a C function using Python ctypes, but I'm doing something wrong. The C function was originally converted from MATLAB to C code using MATLAB coder. The function gives as output an array of undefined length, which depends on the input. This is the MATLAB code: function a = array_output(n) %$codegen ...
The second argument of array_output is a emxArray_real_T *, but you're trying to pass the structure by value as if it were just a emxArray_real_T. To fix that, change dll.array_output.argtypes = [ctypes.c_double, DataStruct] to dll.array_output.argtypes = [ctypes.c_double, ctypes.POINTER(DataStruct)] and dll.array_outp...
64,851,852
64,852,188
C++ : Access of a child member from a parent class
Assuming I have this class below : (I minimized the program as much as I could and deleted the private members and functions that are not related to the issue ). class CBookings { public: CBookings() = default; private: std::vector<CPerson *>Persons; }; Where CPerson is a parent class : class CPerson { publ...
Not really giving you access to child member, but this is a more OOP approach. If the only thing you were trying to do is to print the different types of Person classes, then a more proper way of doing it is to define a virtual print function in Person class, then override print function in each child classes, and call...
64,852,344
64,868,786
Multiply vectors of 32 bit integers, taking only high 32 bits
I want to multiply two 512-bit __m512i vectors of 16 unsigned 32 bit integers together, and take only the high 32 bits from the 64 bit result of the multiplications. Although the Intel intrinsics guide says _mm512_mulhi_epu32 exists, it wouldn't compile on my machine. The answer here claims that _mm512_srli_epi64(_mm51...
vpmuludq aka _mm512_mul_epu32 takes the even source 32-bit elements (0, 2, 4, etc)1. This lets it execute efficiently, within each 64-bit chunk feeding the low 32 bits of the inputs to the FP mantissa multipliers. It's a widening aka full multiply, not high-half multiply, so of course it has to ignore some of the inp...
64,852,359
64,852,671
Segmentation Fault (core dumped). In a Hash Table using separate chaining. (C++)
I am currently creating a Hash Table that uses separate chaining as a collision resolution. I implemented a next pointer to the next node in the struct similar to how a linked list would be structured. Whenever I attempt to access the next node's word I get a memory error saying Segmentation Fault (core dumped). cout<<...
Node hashTable[10]; leaves its contents uninitialized. This makes some of the stuff in hashInsert a bit more of an adventure than you want to see in a computer program. Use Node hashTable[10] = {}; to Zero Initialize the array and get more predictability. But this doesn't solve all of the problems. Zero Initializin...
64,852,393
64,852,881
Better way in C++ to keep a big plain struct atomic?
I have a big plain struct without any methods. It includes many fields and another container(std::vector). I need to make it atomic, so as to let one producer thread and many consumer threads can access it concurrently. consumers don't modify the data, they just read the data. there is only one producer that adds/modif...
I suggest you make your BigStructs effectively immutable, and store them like this: std::map<std::string, std::shared_ptr<BigStruct_2> > all_structs2; In order to make an update, the writer-thread would allocate a new BigStruct_2 (using std::make_shared or whatever), set it equal to the object it wants to modify, then...
64,852,635
64,852,651
Where is the memory allocated if I declare a=5 then return &a?
int* a() { int a_ = 5; return &a_; } int main() { int* p = a(); return 0; } Is a_ (aka p here) allocated on the stack?
Where is the memory allocated int a_ = 5; Automatic storage is allocated for a_, int* p = a(); Automatic storage is allocated also for p Note that after a has returned, the duration of the storage that was allocated for a_ has ended and therefore the pointer returned by a is invalid. That's from C++ and abstra...
64,852,789
64,853,572
LNK2019 error for Visual Studio - unresolved external symbol
I am a beginner and running into the above-said error. The following is the complete code from three files: ball.h: #ifndef BALL_H #define BALL_H namespace { inline constexpr double gravity{ 9.81 }; } double getInitialHeight(void); double calculateHeight(double, int); void printHeight(double, int); ...
When you add header file, you could right click Header Files and select Add->New Item. When you add .cpp file, you could right click Source Files and select Add->New Item. Then, add the following code in Source.cpp. #include <iostream> #include "ball.h" int main() { solve(); return 0; } Finally, it works fi...
64,852,895
64,853,280
why this java code takes less space and time compared to cpp
class Solution { public: void inorder(TreeNode* root, int low, int high, int& res){ if(root != nullptr){ inorder(root->left, low, high, res); if(root->val <= high && root->val >= low){ res += root->val; } inorder(root->right, low, high, res); ...
After a bit research I found it is related to the platform itself. Leetcode: Is java faster than C++ According to one comment "they remove compile and other procedure runtime from the benchmark for Java. Which means for C/C++ solutions, compile time was counted in the runtime" Not sure how much dependable this is.
64,853,128
64,853,314
How to translate integer error-codes into human-readable strings?
IBM goes to great lengths documenting the possible error-codes for different MQ-related functions, but I cannot find an existing library function to translate the integer codes into human-readable strings. Something like libc's strerror(3) or OpenSSL's ERR_error_string(3)... I suppose, the programmers and operators are...
You can convert the number, e.g. 2035, into a string such as "MQRC_NOT_AUTHORIZED" using the MQRC_STR function that is shipped in header file cmqstrc.h. If you want more than just the string representation of the constant, you could look into calling the mqrc executable that is shipped with distributed platform version...
64,853,472
64,870,182
How to input an integer followed by a String in C++?
I am stuck on how to use std::cin to read in an integer, followed by a space, and a String that comes after it. Here is the store.txt file: 2 Hello how are you 6 Oh no 1 Welcome 5 We are closed How do I read in a number at the start, followed by a space, and then read in the string after it? For example, when I cin ev...
You can use map for storing strings In the map the keys will be the numbers whereas the values will be the strings You can simply store them in a map by using cin function for the numbers first then followed by getline function for the string and storing them to map After doing this you can access the string by numbe...
64,853,765
64,853,828
Can't display binary search tree C++
I tried creating a binary search tree, using youtube and examples from my professor to help, but display in Driver.cpp doesn't show any node of the tree except "null" (which was intended to represent nullptr). I think it's because my "root" remains as nullptr, even though I've inserted a new node. The output should be ...
You should pass pointer to pointer to root in your insert function like: void BinaryTree::insert(Node* newNode, Node** p) { if (*p == nullptr) { *p = newNode; } else { if (newNode->data < (*p)->data) { insert(newNode, &(*p)->left); } else if (newNode->data > (*p)->data) { ...
64,854,368
64,860,015
XCODE exec file only runs after stopping the program
I have recently been building a C++ program "SFML_start" on XCode utilizing the SFML library which was going good. Ever since I upgraded to macOS Big Sur yesterday, whenever I run the C++ program the exec file doesn't run at all but the message dialog says "Running SFML_start" after the build is complete. I have notice...
SOLVED: This problem still persisted even when I updated Xcode to the latest version compatible with macOS Big Sur. However, after completely creating a new duplicate project "SFML_refined" under the updated SDK and rebuilding it, the exec file was successfully run. It is worth noting that the "SFML_start" however stil...
64,854,677
64,856,688
C++: Problem with array of strings old C-style (as Char**)
Good morning friends, I am currently working in a big chunk of code (CFD solver) as part of a collaborative development. I am not an experienced developer and therefore the question may seem stupid, but I have come with a problem that I am unable to solve. I am trying to modify an array of old-style C-Strings (char**)...
All m_variablesName[count] in this snippet are allocated by for (MInt i = 0; i < PV->noVariables; ++i) { m_variablesName[i] = new MChar[10]; } These C-style strings can not be assign directly, you should use functions such as strncpy, to copy contents into: for (MInt s = 0; s < m_noSpecies; s++) { memset(m_vari...
64,854,691
64,854,713
Do I need to delete the pointer returned by std::localtime?
This is currently how I am getting system time: void Sum_AnalogClock::GetSystemTime() { std::time_t t = std::time(0); // get time now std::tm* now = std::localtime(&t); angleSeconds = now->tm_sec; angleMinutes = now->tm_min; angleHours = now->tm_hour; if (angleHours > 12) angleHours -...
No, according to [1] it points to an internal data structure, so you don't need to delete it. [1] https://en.cppreference.com/w/cpp/chrono/c/localtime
64,854,703
64,858,408
Usefulness of post-incrementing a weakly_incrementable?
I studied the weakly_incrementable concept recently and I am wondering what the post-increment operator is good for, given that the concept does not define any requirements for the result of the operation. Is it actually okay to return void for operator++(int)? void operator++(int) { ++(*this); } It seems in line with...
That design decission is documented in P0541. Is it actually okay to return void for operator++(int)? Yes. It is. A specific straw poll was taken, as stated in the paper. Removing the postfix increment in its entirety was also considered but: The authors of the Ranges TS strongly prefer keeping the postfix increment...
64,854,957
64,857,181
DirectX : cannot create an directx11 device even though my system says it supports it
I open the dxdiag app, select the display tab to check supported feature levels here are the results I have low RAM today as one my chips got blown and am now operating on 2GB ram So It looks like my device supports directx feature level 11 great Jump to visual studio 2019 i try creating an D3D11 Device D3D_FEATURE_LE...
As suggested in the comments removing the lowest supported feature level i.e 9_1 was the answer. From the docs if the feature level array is null then the default array D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_9_1, D3D_F...
64,854,973
64,855,712
What is the best way to override istream for large object (over 30 fields)?
I have a very large text file that has over 11 million entries/lines. Each line has 35 values in it, each value is separated/delimited by a "|". For each line that I am reading in, I am creating an object, "Record". I am storing them in a vector of Records because I need to be able to sort them based on the values in a...
I really wanted to find a use for pointer-to-member syntax for once, so... You can use pointer-to-member syntax with a set of overloaded helpers to let compiler choose the correct convertor: struct Record { int x; std::string y; double z; void readInput(std::istream& in, int Record::*var) { ...
64,855,696
64,857,740
Differentiate between shared_ptr and normal type on compile time
I try to create a templated class, which saves the template argument as a member variable (msg_). Now the input of the class should allow normal types like int and shared_ptr<int>. template <typename T> class Foo { public: Foo<T>() {}; private: T msg_; }; My problem is if the class gets initialized with shared_p...
You might have specialization template <typename T> class Foo { public: Foo() {} private: T msg_; }; template <typename T> class Foo<std::shared_ptr<T>> { public: Foo() : msg_(std::make_shared<T>()) {} private: std::shared_ptr<T> msg_; }; or create function to initialize (with overload) template <typen...
64,855,748
64,855,966
GetTokenInformation returns ERROR_INSUFFICIENT_BUFFER in the first call
From the MS docs i read that you should call the func twice, first time is to get the token length and the second is getting its info. My problem is that it fails in the first call(error 122) but still writes a length of 32. const char* CSystemHelper::ReturnUserByProcessHandle(const PROCESSENTRY32 &PENTRY) { HAND...
Yes. It is normal operation. When TokenInformation parameter is null, GetTokenInformation function returns 122(ERROR_INSUFFICIENT_BUFFER). So your code must be changed like this. DWORD len = 0; // this call fails, but len is set to 32 if (GetTokenInformation(hToken, TokenOwner, NULL, 0, &len)) { ErrorCode ...
64,855,803
64,855,962
Why does scanf ask twice for input
#include <stdio.h> #include <stdio.h> int main(){ char karakter1, karakter2, karakter3; printf("Input 3 karakter terserah\n"); printf("Input karakter :\n"); scanf("%c ", &karakter1); printf("Input karakter :\n"); scanf("%c ", &karakter2); printf("input Karakter :\n"); scanf("%c ", &karakter3); p...
This should work fine for you now. #include <stdio.h> #include <stdio.h> int main(){ char karakter1, karakter2, karakter3; printf("Input 3 karakter terserah\n"); printf("Input karakter :\n"); scanf(" %c", &karakter1); printf("Input karakter :\n"); scanf(" %c", &karakter2); printf("input Karakte...
64,855,843
64,856,074
Why constexpr should be static?
After reading this and this I still feel confused about this kind of expressions: static constexpr int = 0; AFAIK, in C++: static ensures life-time memory address along whole execution and safe initialization with concurrent threads constexpr ensures time-compilation evaluation as rvalue, which means it shall have no...
static has a number of meanings. In classes (per your comment), it means that the member is associated with the class, and not a specific instance (object) of that class. For a constexpr, that makes a lot of sense. That's typically initialized by a value known to the compiler, and not from ctor arguments.
64,855,850
64,870,793
This->DataContext not working in uwp c++/cf in visual studio 2019 in C++
I am using UWP to create an app for a server application and I have made a class serverclass.h in c++ in which I have a string output. Now I want to print this output in a textbox in xaml. I have attached the codes below. When I'm using this->DataContext=ser; it is giving me an error:"function Windows::UI::Xaml::Framew...
If you want to print your string output in a textbox in xaml, you could use data binding referring to the document and sample. For the scenario mentioned by you, you could check the following code: serverclass.h namespace YourAppName{//Put the serverclass into the namespace public ref class serverclass sealed : Windows...
64,856,364
64,856,426
C++ Order of class members when smart pointers are involved matters
Consider this snippet: struct A { A(std::unique_ptr<int> somePtr_) : somePtr{std::move(somePtr_)}, someInt{*somePtr} {}; std::unique_ptr<int> somePtr; const int& someInt; }; Here, a unique_ptr is passed and stored. Then a reference to the underlying data is also stored. When an object of...
Order of members matters always. The presence of the smart pointer is a red hering. The crux in your example is just that initialization of one member depends on some other member already being initialized. Members are initialized in the order they appear in the class definition. Always. Even if you list them in differ...
64,856,516
64,858,385
wxWidgets: wxButton with label on top of bitmap
I would like to have a button with a text on top of the image that I can change. It does not seem like there are any label alignments that support this (only wxBU_LEFT | wxBU_TOP | wxBU_RIGHT | wxBU_BOTTOM). The closest workaround that I have found is to resize the button so that the image does not get offset by having...
By "on top" do you mean "above" or "over"? If it's the latter, you should create your own bitmap and draw the original bitmap and then your label on it using wxMemoryDC (if it's the former, this approach would also work, of course, but just using wxBU_TOP is much simpler).
64,856,629
64,856,713
How to call function pointer for class member function
I tried to implement a function pointer calling to the class member. I have implemented the sample and assigned the function pointer successfully. But if I try to call the function pointer it is throwing an error. Kindly refer below sample code of what I implemented and assist me on this. #include <iostream> using nam...
myval(1, 2); This cannot work because you haven't passed the implicit instance argument. A pointer to member function is called like a member function, except in place of the function name, you have indirection operator and the pointer to member function. Example: (a.*myval)(1, 2); The parenthesis are needed becaus...
64,856,791
64,859,029
Extracting normals of a CGALTriangulation
In a 3D CGALTriangulation I'm trying to get the normals by this way Vector n = CGAL::normal(p1, p2, p3); Code in context: for (CGALTriangulation::Finite_facets_iterator it = T.finite_facets_begin(); it != T.finite_facets_end(); it++) { std::pair<CGALTriangulation::Cell...
The orientation of a facet cannot be found that way. To set p1, p2, and p3, use that piece of code: const auto cell = f.first; const int i = f.second; const Pointt& p1 = cell->vertex(T.vertex_triple_index(i, 0)->point(); const Pointt& p2 = cell->vertex(T.vertex_triple_index(i, 1)->point(); const Pointt& p3 = cell->ver...
64,857,175
64,893,204
Setting node bounding box size in OGDF
I'm attempting to layout and visualise a code flow graph in Qt using the OGDF library and the Sugiyama layout. The version I'm using is v2020.02, which should be the latest at the time of writing. My issue: When creating nodes, I set them to various sizes, but after calling the SugiyamaLayout algorithm all node sizes a...
After some more research, the OGDF Mailing List provided me with the answer. This behavior is indeed caused by a bug in HierarchyLayoutModule.h, where the correct bounding box sizes aren't preserved. The corresponding Github issue can be found here and will be fixed in the next release. In the meantime, it can be fixed...
64,857,371
64,857,434
Why variable, passed to a function by reference, doesn't immediately change its value?
So here is the code (the program calculates the area of ring with specified outter and inner radiuses, nothing too special): #include <iostream> bool f(double ro, double ri, double &s) { const double eps = 1e-12; if (ro > ri + eps) { const double pi = acos(-1); //s = pi * (ro * ro) - pi *...
Order of evaluation rules have evolved, in particular, in C++17 for E1 << E2. std::cout << f(ro, ri, s) << ' ' << s << '\n'; is guaranteed to be evaluated in expected order (left to right for E1 << E2 ) in C++17 whereas it was unspecified before.
64,857,449
64,857,507
How do I iterate through nested vectors?
I have a rather complex ordered internal Grammar representation of my productions consisting of typed std libarary classes: class Grammar { std::tuple<int, NonTerminal, std::vector<std::vector<Symbol>>> productions; } Now I would like to create LR0-Items from this representation. From inner to outer: std::vector<...
To iterate a vector whose elements are of type T you can use a range based for loop: std::vector<T> vect; for (const auto& element : vect) { // element is a const reference to elements of vect // put code here } Now, if T is again a vector, you just replace //put code here with your code to iterate that vector...
64,858,240
64,858,362
Non-type template parameters and requires
I am learning concepts, and I can not figure out a way to restrain the value (not type) of non-type template parameter. Example of code that compiles, although I wish it did not(due to failed requirement): #include <cassert> enum Bla{ Lol, Haha }; template<Bla b> requires requires{ // my guess is that th...
If you only have a boolean condition and nothing else, do this: template<Bla b> requires(b > 1) void f() {} Alternative longer syntax, if you need to check more things in the same requires-expression: template<Bla b> requires requires { requires b > 1; // ^~~~~~~~ } void f() {}
64,859,347
64,860,752
Visual Studio - C++14 compiling embedded code with /clr option => function cannot be compiled as managed. C2711, C3820
in an Software-in-the-loop test-environment project I use VisualStudio2019 to compile embedded software (C++14, with etl (embedded template library)) for the VisualStudio Unittests (C#). Hence, the embedded software is (stubbed/mocked) at the HAL and OS-Layers and compiled with CLR support (/clr). Now i am stuck at a l...
Finally I found a way to get things compiled. I had to modify the code (minor modification) by putting the array initialization into a function which is decorated by pragma managed see below. Now it compiles fine! Decorating a single statement like the array initialization with the pragma doesn't work, it has to be a f...
64,859,366
64,860,335
Passing callable in lambda capture
While reading SICP's section about "Formulating Abstractions with Higher-OrderFunctions" I was curious to implement a simple, root solving procedure using Newtons' Method in C++. However my implementation is faulty but I cannot figure out why. The code compiles but I got a runtime crash due to stack overflow because th...
Your issue is int truncation from double with return findRoot([x](int y) {return y * y - x; }); So when you compute derivative, you obtain 0. Change to return findRoot([x](double y) {return y * y - x; }); Demo
64,859,844
64,862,133
Use ARMv8 CRC Extension to calculate CRC-32/MPEG-2 Checksum
I am currently attempting to use ARMv8 CRC Instructions to accelerate the calculation of CRC32/MPEG2 Checksums. The only examples I found about using these Instructions calculate regular CRC32 Checksums. uint32_t ZLIB_INTERNAL armv8_crc32_little(unsigned long crc, const unsigne...
"Reflected" is referring to bits. For a non-reflected CRC with the same polynomial, you would need to reverse the bits of every byte you feed to it. You could use a table to do that. You would then need to reverse the bits of the resulting CRC. It would be interesting to know if that plus the hardware instructions is f...
64,860,114
64,860,347
is there other way to fill in array in C++ without vector
So I have array A and B, two of them contain random numbers and I need to write in the C array initially even numbers of A and B and then odd. I have made this wtih vector but I wonder if there is other way to do it like in Javascript there are methods like .unshift(), .push() etc #include<iostream> #include<vector> us...
I would suggest interleaving A and B initially: for (int i = 0; i < n; i += 1) { C.push_back(A[i]); C.push_back(B[i]); } And then partitioning C into even and odd elements: std::stable_partition(C.begin(), C.end(), [](int i) { return i % 2 == 0; });
64,860,501
64,860,566
How to update Qt-GUI form view with implemented code?
For demonstration I created a simple simple widget in Qt-Creator. widget.h widget.cpp main.cpp widget.ui I added a QPushButton to Design-Form by drag-and-drop Implementing QFont expression to widget.cpp: // widget.cpp #include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent),...
No, there is no way. The Qt Designer preview only renders the GUI built based on the .ui.
64,860,514
64,880,807
QTableWidget: signal itemChanged fires too late (after signals for other actions, close, etc.)
I am using a QTableWidget to represent some user editable data. Upon editing, the internal representation of the data is updated by connecting to the table's itemChanged(QTableWidgetItem*) signal. I have a menu action "save" which saves the data and also if the user tries to close the window, I check if there current d...
In your case, when the save action is triggered, you can first set focus to the QTableWidget object. The editor will lose focus and commit the data. I consider this a better way than the one I suggested in the comment (since it assumes the editor to be a QLineEdit object and uses dynamic_cast). #include "mainwindow.h" ...
64,861,092
64,861,398
Use auto for only one variable with structured binding
I am trying to update a variable passed to a function with a structured binding: #include <iostream> #include <tuple> #include <utility> std::pair<int, double> func(double y) { return {1, 1.3+y}; } int main() { double y = 1.0; auto [x, y2] = func(y); y = y2; std::cout << "x = " << x << ", y = " <<...
To answer your question narrowly: No, you can't reuse an existing variable in a structured binding. Structured binding always declares new variables. That being said, there are other options - like std::tie, as @Robert A has demonstrated.
64,861,549
64,871,775
Why can't I use my function in the header file?
main.h: header #ifndef _MAIN_H #define _MAIN_H #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct ComplexNum { double real; double img; }mc; char *JustShow(mc ); #endif // _MAIN_H cal.cpp : function defined in another file called #include<stdio.h> #include<string.h> #in...
I'm going to call the third piece of code "main.cpp". why can't I use the function JustShow when I had already added "main.h". Header files only inform a compiler that a function, variable or constant exist. You need to compile cal.cpp with main.cpp: g++ main.cpp cal.cpp -o main I am also confused why should we defi...
64,861,586
64,861,629
Using Curly Brackets and Parentheses
So i'm doing a beginner c++ course and i'm confused about something regarding parenthesis and curly brackets.. #include "Savings_Account.h" Savings_Account::Savings_Account(double balance, double int_rate) : Account(balance), int_rate{int_rate} { } Savings_Account::Savings_Account() : Savings_Ac...
No. The choice of brackets is not what determines whether you're delegating to another constructor or not. The choice of brackets isn't entirely arbitrary, and it can make a difference to some things, but not for this. It's unfortunate that the code's author has chosen to be confusing, by mixing initialisation styles, ...
64,861,625
64,863,927
Why declaring a QImage as static const produces an invalid value?
I have a QGraphicsItem object called ItemView which I am creating many instances of, and they all show up as a QImage on my QGraphicsView. I have it working by creating a new QImage for each instance of ViewItem, but now I'm trying to convert that property to a static field to optimize because I really only need one, a...
Note: For me this is a XY problem. I will provide a solution to the X problem and I suggest you to think about your Y problem and probably ask another question, which targets it explicitly. Cause You initialize ViewItem::IMAGE with a QImage, constructed from a fileName. As per documentation: If the loading of the imag...
64,861,763
64,861,872
(C/C++) Initialize and return array in the same line
I was wondering how I could initialize and return an array on the same line using c/c++. My intuition says that the syntax should look somewhat like this: return (int8_t*) {hours, minutes, seconds}; Am I correct? Is the cast mandatory? Or is there another/better way of doing this? EDIT: I'm asking this because I cannot...
This will not work as you expect. The exact syntax for what you're trying to do would be: return (int8_t []){hours, minutes, seconds}; Which creates a compound literal of array type. However, this literal has the lifetime of the enclosing scope. So when the function returns, the returned pointer is now pointing to i...
64,862,197
64,862,281
No class template specialization for array of bool?
According to https://en.cppreference.com/, std::vector<bool> has a class template specialization, while std::array<bool, N> does not. Which are the reasons why it is not provided?
When std::vector was introduced, a specialization for bool was considered a good idea. Basically, at that time, the average computer had 4 MB of memory, so saving computer memory was quite important. Nowadays we just say "memory is cheap" (quote from Uncle Bob). Later it turned out that this specialization creates more...
64,862,350
64,862,542
How do you create a smart pointer from 'this'?
In a non-const member function, I want to pass 'this' to a function, but the function takes a shared_ptr. When I try to pass it like this: std::shared_ptr<Piece>(this) I get weird exceptions saying: "Chess.exe has triggered a breakpoint" Am I converting from 'this' to shared_ptr in the wrong way?
If you are already using shared pointers to manage the object's memory then this is what std::enable_shared_from_this<T> is for e.g. #include <memory> class Piece; void takes_a_shared_piece(std::shared_ptr<Piece> ptr) { //do something } class Piece : public std::enable_shared_from_this<Piece> { public: Piece...
64,862,374
64,862,559
Functions returning lvalues, always return lvalue references
Scott meyers in item 3 of effective c++ says Applying decltype to a name yields the declared type for that name. Names are typically lvalue expressions, but that doesn’t affect decltype’s behavior. For lvalue expressions more complicated than names, however, decltype generally ensures that the type reported is an lval...
It means what it says! There is no way to make a function, such that its return type is not T&, yet calling it results in an lvalue expression. Every other return type results in the function call being an rvalue expression. This is intuitive when you consider that the only way to "return" something that already exists...
64,862,593
64,862,715
Cout calls a method with operator <<
#include <iostream> using namespace std; int main() { char sample[] = "something really weird about c++"; cout << sample << " - huh?"; return 0; } Here is simple c++ code that print something on screen, as I'm from python, it seems really weird for me that an object (according various sources 'cout...
Also in Python you can overload operators. For example you can implement the special method __add__ and then call it via a + b (see eg here for details). In principle the answer wouldn't be that different if your question was about Python instead of C++. Applying an operator is calling a function. This cout << sample...
64,862,858
64,934,867
Visual Studio Code g++ does not compile with c++17 when debugging
I want to compile the active file in the current workspace folder. With a C++11 file there is no problem I just hit run->start debugging and the right launch.json and tasks.json is generated. However with a file which contains C++17 code I run in trouble. I thought adding the flag -std=c++17 in tasks.json would compile...
It looks like there is "built-in" task with name "C/C++: g++ build active file", so that even if it's not defined in tasks.json but used in launch.json, it is launched anyway... with some default configuration you can't change, of course. Try to remove this task from tasks.json to find out that's true. This built-in ta...
64,863,080
64,865,755
Shared locks from multiple threads can starve a single thread looking for an exclusive lock
Let's say I have several threads reading from shared memory. All of these threads repeatedly grab a shared lock on a shared mutex to access this memory. Let's say I have one thread that writes to this shared memory that grabs an exclusive lock. Given enough read threads there may never be a point in time where that one...
This should work. Its not sophisticated and does not provide any gurantees on order if you have more than one writter. But it should work. #include <condition_variable> #include <mutex> class RWLock { std::mutex lock; std::condition_variable writeWaiters; std::condition_variable re...
64,863,464
64,863,822
deleting object through pointer to base without virtual destructor
I have the code: class A1 { public: A1() { cout << "A1"; } virtual ~A1() { cout << "~A1"; } }; class A2 { public: A2() { cout << "A2"; } ~A2() { cout << "~A2"; } }; class B : public A1, A2 { public: B() { cout << "B"; } ~B() { cout << "~B"; } }; int main() { A1* pa1 = new B; delete pa...
Without virtual the destructor is resolved statically, based on the declared type of the pointer. The compiler sees an A1 * so delete pa1 will call the ~A1 destructor, and nothing else. we don't have an instance of A1, so ~A1() should not be invoked as well. B is derived from A1 so an instance of A1 exists as a subob...
64,863,479
64,863,669
Using goto function one of my user inputs won't work (c++)
I am writing a program that lets the user make their own person (as an object) with a series of user inputs and multiple choice. I have a confirmation system at the end using the goto function but when i go back to making making the person if they don't like it the user input for the fist name won't work but the rest d...
I recommend using loops for error correction and functionality continuations: bool continue_program = true; while (continue_program) { //... std::cout << "Continue program (Y/N)?"; char response; std::cin >> response; response = tolower(response); if (response != 'y') continue_program = false; } You can al...
64,863,511
64,867,945
Why does arduino uses macros for certain 'functions' like min(), max(), constrain()?
Though I am a fan of macros in general, I am not getting why the Arduino makers chose to use macros instead of actual functions for some of their arithmatic "functions". To name a few examples: min() max() constrain() Their website informs one not to call functions from within these "functions" or to use pre/postfix i...
Arduino is built based on much older codes and libraries such as AVR-libc where macros are used extensively way before Arduino even existed. In modern programming, macros are not recommended (versus inline functions) as it does not do type checking, does not check compile errors and if not craft carefully could lead to...
64,863,684
64,864,098
Finding a row of 2D array in which max sum of elements is c+
I am having trouble with find in which row of 2D array the maximum sum of elements is, Here is the code, could someone give me any suggestions. Thank you ! int sum=0; int maximum =0; for(int i=0;i<n;i++) { for(int j=0;j<b[i];j++) { sum = sum+a[i][j]; } if(sum>maximum...
int main() { int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; int n =3; int b = 4; int maximum =0; int sum = 0; ...
64,863,818
64,864,051
Why is the custom QObject returned by my Q_INVOKABLE method undefined in my QML?
I have a MasterController QObject with a Q_INVOKABLE method that returns a const reference to an object of MyType, another type derived from QObject. I register both in main(). I instantiate a MasterController and add it to the root context in main as well. In my QML, I import the registered module containing the tw...
QObjects are not copyable so you cannot pass the reference of a QObject but rather the pointer: Q_INVOKABLE QObject* getData(); QObject *MasterController::getData() { return &_myData; }
64,864,092
64,864,372
Converting argv arguments to double
I have created a .srv file in Ros. Which is structured as follows. float64 a float64 a --- bool response Now I try to read the chars which are in the argv as float. My output is always the same no matter which values I pass. Output: check Numbers a: 94290532670520 b: 0 Where is my mistake? Thanks in advance. int main...
argv[0] is the program name; you probably meant argv[1] and argv[2]. Your log output is wrong; %ld means long int, not float or double. Try %f.
64,864,805
64,867,409
why compiling vs2019 Simple C++ console app source requires windows sdk to compile? any workaround?
#include <iostream> #include <string> using namespace std; int main() { cout << "hello world!\n"; keep_open_window(); } inline void keep_open_window() { char c=0; /*cin >> c;*/ } I just don't installed WINDOWS SDK from vs2019 install option and now try to compile a simple CPP source file but it gets error C:\P...
The reason this fails to build is quite simple: The Windows 10 SDK contains the "Universal C Runtime" which is required for the Visual C/C++ Standard Library. C:\Program Files (x86)\Windows Kits\10\Include\<version>\ucrt C:\Program Files (x86)\Windows Kits\10\Lib\<version>\ucrt See The Great C Runtime (CRT) Refactorin...
64,864,808
64,865,000
How to add to variable using SSE2?
How to "add to" variable using SSE2? I've recently been working with SSE2 in C++ to optimize a few math functions up, but ran into a problem when attempting to add to existing variables. I have a function which intakes variables like so: _m128d v1 {}; // Note: Global variable. _m128d v2 {}; // Note: Global variable. ...
Intel's site: https://software.intel.com/sites/landingpage/IntrinsicsGuide/. Select SSE2, Artithemtic, and you'll get half a page of arithemtic instructions. You obviously want an m128d add, but the problem you have is that you need to specify how those 128 bits are organized. That could be anything from 16x8 to 2x64. ...
64,864,955
64,865,660
Casting QObject to and from void pointer looses data?
I try to cast my object to and from a void pointer. This is how my class inherits: #ifndef EVERYTHING_H #define EVERYTHING_H #include <QString> #include <QObject> struct Base { public: const QString name; explicit Base(const QString& n) : name { n } {} }; class A : public QObject, public Base...
When casting a pointer up or down an inheritance hierarchy, it's not guaranteed that the underlying memory address in the pointer remains the same. Depending on the inheritance details involved, an adjustment might need to be made to ensure the resulting pointer ends up pointing to the proper part of the object. (For i...
64,864,961
64,865,032
How to match all string types with std::is_same_v
I'm trying to use templates to generify a method. However I'm struggling to match string types like string char * literals. See the following code example: template<typename ValueType> void match_data_type(ValueType value) { if constexpr (std::is_same_v<std::remove_cvref_t<ValueType>, bool>) { std::cout << ...
String literals are constant. The type of "hello" is char const[6], which would decay (since you're taking by value) to char const*. You have to check against that, not char*. For the rest of the code, the char check isn't useless (you could certainly call match_data_type('c')) but the char[] one is -- the parameter w...
64,865,334
64,865,391
Const char *pointer questions?
I have some questions related to this simple snippet of code. #include <string.h> #include <stdio.h> int main() { const char *str1; str1 = "hello"; printf("%s \n", str1); return 0; } I want to ask you: Is it safe to make an assignement to a const char pointer like that? Considering that str1 will never c...
Is it safe to make an assignement to a const char pointer like that? Considering that str1 will never change. Yes. In fact, it's the right thing to do. The pointer itself is not const; the type const char* means that the thing it points to is const. If your pointer were const char* const str1 (a const pointer!) then ...
64,865,338
64,905,185
Cereal - unable to deserialize a json string - unhandled exception
This is my json string { "connectionString" : "MyConnectionString", "value" :"MyVal" } This is my class struct Settings { std::string connectionString; std::string value; template<class Archive> void serialize(Archive& ar) { ...
The code expecting that outer object is put there by the default JSON "prologue" and "epilogue" behavior: https://github.com/USCiLab/cereal/blob/10d9a29c225fe9a843d043bfe9f13c5f958844dc/include/cereal/archives/json.hpp#L837 From the documentation: These functions are given a reference to the active archive and a const...
64,865,861
64,865,907
Why does this code works on one platform but doesn't work on another?
I've written a long and complicated server program on windows. Used visual studio 2019. Then I've created a CentOS 8 operating system on vm virtualbox and transferred all the code there. And rebuilt an executable with visual code. That works okay except one part. Here is the code that causes the crash: //clients is ...
for (const auto& kv : clients) { This iterates over the range using iterators. After the loop body is executed each time, the iterator is incremented. int i = kv.first; clients.erase(i); This invalidates the current iterator. When the invalid iterator is incremented after the loop body, the behaviour of the progr...
64,865,906
64,866,110
C++ primer 5th edition: Difference between the deleter of a shared_ptr and of unique_ptr's
In "C++ Primer, 5th Edition", it is said that the type of the deleter of a shared_ptr is not known until runtime, because the deleter is not stored directly as a member, but as a pointer that can point to a deleter. The type of the deleter in a unique_ptr is known at compile-time, because it is a part of the unique_ptr...
in my opinion, the type of the deleter in SharedPtr is known at compile time (void(*)(T*)) but the value is not. That is true of your SharedPtr. That is not true of std::shared_ptr. on the other hand, the type of the deleter in UniquePtr is really known at compile time too, but again the value may not be. When you ...
64,866,037
64,866,381
Error: "this declaration has no storage class or type specifier" in c++
I am trying to write some code that will make it easier for me to make SDL programs because I am learning and frequently start new projects. It basically needs to do all the standard SDL stuff. This is the code namespace engine { class Engine { private: SDL_Renderer* renderer; SDL_Window* w...
I'm gutting Engine to make the example smaller. We don't need any of the SDL stuff in the class to show how to fix this up. Other than that, Engine looks pretty good. Don't need to change anything. namespace engine { class Engine { private: bool initialised = true; bool quit = false; ...
64,866,134
64,882,121
Handling interactions between different derived class objects
I have a program where I have a vector of pointers to a base class where I store instances of multiple different derived classes. All these objects interact with each other in different ways depending on their type and I'd like to implement these interactions in a smart way. I'd prefer to have a mediator class where to...
Since I can't seem to avoid using an ugly switch statement or a chain of if-else if, I think I'll just do something like the following where I don't need to introduce enums to the classes or modify them otherwise. #include <iostream> #include <vector> class Gesture { virtual void foo() {} }; class Rock : public G...
64,866,150
64,902,493
Cython: Why can I use vector in pxd files?
When I want to use .pxd and .pyx files to use my C++ code within Python, I can use vector after importing libcpp.vector within the pxd file. Is it possible to write own C++ classes and use them in pxd files like vector is used (for example use std::array)? On the one hand, libcpp seems to contain the pxd file for vecto...
There are two parts to Cython's wrapping of types such as std:: vector: The .pxd files it defines for your to cimport (e.g. https://github.com/cython/cython/blob/master/Cython/Includes/libcpp/vector.pxd). These are provided for your convenience (to save everyone the effort of re-writing the same files). They use stand...
64,866,346
64,866,572
How does this memory allocator get the address of the block?
So, I'm reading Writing a memory allocator on this website: http://dmitrysoshnikov.com/compilers/writing-a-memory-allocator/ I'm confused by this part, where the helper function retrieves the block's address: /** * Returns the object header. */ Block *getHeader(word_t *data) { return (Block *)((char *)data + sizeof...
A memory allocator needs to maintain metadata about the size of each allocated block and where the available unallocated memory is. It is common for an allocator to maintain that metadata longside the allocated regions themselves. That is what the example allocator is doing. struct Block Represents an allocated bloc...
64,866,353
64,866,401
What is the influence of parentheses on array pointers?
While writing a program I found out that the output of (*array3)[i] is different than *array3[i] I don't really understand why. Could somebody explain to me what is happening in the computer? The first snippet does what I want, namely: indexing through the array. In the last snippet, first the indexing is done and la...
In (*array3)[i], the * dereference operator is first applied to array3, and then the [] subscript operator is applied to the result. In *array3[i], this gets treated as *(array3[i]) because the [] subscript operator has a higher precedence than the * dereference operator. So, the [] subscript operator is first applied ...