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
67,240,617
67,262,873
function type when used with decltype
I was looking into decltype and std::is_same_v and tried them on functions. template<typename T> void func(T t){} template<typename T> using f = decltype(func<T>); template<typename T> using ff = decltype((func<T>)); template<typename T> using fff = void(*)(T); template<typename T, typename U, typename Z> void tes...
Your code is similar to: f<int> f1; // `void f1(int);`, function declaration ff<int> ff1 = func<int>; // `void (&ff1)(int) = func<int>;`, reference to function fff<int> fff1 = func<int>; // `void (*fff1)(int) = &func<int>;` pointer to function, // decay of `func<int>` to poi...
67,240,830
67,240,858
Why can't std::endl be passed as a function argument?
#include <iostream> void f(auto x) { std::cout << x; } int main() { f(std::hex); // okay f(std::endl); // error // candidate template ignored: // couldn't infer template argument 'x:auto' } Why can't std::endl be passed as a function argument?
Because std::endl is a function template, and std::hex is not, it's a single non-overloaded function. Passing a function that refers to an entire overload set as an argument is done by resolving to a single concrete type. Here what happens is that the caller wants to resolve a type by attempting to make the f function ...
67,240,970
67,243,417
Why is a template base class' public member types hidden by default?
template<typename T> struct A { using U = T; }; template<typename T> struct B : A<T> { B(typename A<T>::U) {} // okay B(U) {} // error: unknown type name 'U' }; int main() { return typename B<int>::U{}; // okay } Why is a template base class' public member types hidden by default?
The search term for further research is "two-phase name lookup". In short, the compiler tries to resolve as many names used by the template as possible at the point where the template is defined. Some names - so-called "dependent names" - cannot be resolved at this point, and have to be deferred until the template is a...
67,242,093
67,242,849
How to avoid restarting the polygon when redraw?
I'm writing the program that continuously draws a polygon until the user clicks right-click, but when I continue to draw something else on the screen the polygon disappears, how can I avoid this? This is my program: float mouseX, mouseY; vector<float> vecX(40); vector<float> vecY(40); int numPoints = 0; int closed = 0;...
Once a polyline is finished, you need to store it to a container. Use a std::vector of polylines. The type of a polyline is std::vector<float>. At the begin, just 1 empty polyline is in the container: std::vector<std::vector<float>> polylines(1); When you left-click, a new vertex coordinate is added to the last polyl...
67,242,115
67,242,283
Finding out if a Linked List has a Cycle [Code Wars Problem]
bool hasCycle(Node * head) { Node *p = NULL; Node *q = head; while(q) { q = q->next; if(q->next != NULL) q = q->next; p = p->next; } return p == q ? true : false; } My code works for most of the solutions, but it fails one test case for some reason. Can someone take a look at my code and exp...
The logic behind this problem is to use two pointers: a fast one and a slow one. If there is a loop, the fast will catch up with the slow. If there is no loop, the fast will reach the end first. Your code didn't exihibit the logic like this. I don't know what you are trying to do. Here is my code: bool hasCycle(Node * ...
67,242,269
67,242,299
Why the compiler is showing true?
The output should be false, as false&&true is false. However, the compiler is giving 1 as output. #include<iostream> using namespace std; int main() { int a = 10; int b = 13; bool flag = true; cout << ((b - 4) < a) && !flag; return 0; }
This is because << has higher precedence than &&, your expression should be: cout << (((b-4)<a) && !flag); A more detailed explanation: One of the first things that any C++ compiler does when processing your source code is to construct an abstract syntax tree (AST) representing your source code. The AST is a tree stru...
67,242,305
67,243,235
Braced initialisation of std::any
When declaring std::any object of a class type the below three ways of initialising the object works properly. class B{ }; std::any a; a.emplace<B>(); std::any b = std::make_any<B>(); std::any c(B()); But when used with braced initialisation like std::any d{B()}; The class's destructor gets called twice resulting...
{ std::any d{B()}; } two instances of B are created in the above block, and two are destroyed. One temporary B() and one within the any. Odds are you violated the rule of 0/3/5, and do not have a correct copy/move ctor. std::any c(B()); c is a function, not a variable. That is vexing, but it is a legacy rule for ...
67,242,693
67,242,863
Do we have a static initialisation order fiasco while initialising variables inside the class
I am trying to refactor our old code from c++98 to c++14. And the need to compile with both older gcc(c++98) and newer gcc(c++14). This is how our older code looks like (This is completely made up example, of our complicated code. The static consts fromthis class is used in another class). // BankAccount.h namespace ba...
(Update: As the question has been changed to static const members) By declaring them static const, it is safe for integer variables. In modern C++, there is no difference to declaring them as static constexpr. It is guaranteed by the language that you will not run into problems of accessing non initialized (or rather z...
67,242,820
67,242,861
how is pointer to member able to bind to T U::*
I was going through std::is_member_pointer in cpprefernce. template< class T > struct is_member_pointer_helper : std::false_type {}; template< class T, class U > struct is_member_pointer_helper<T U::*> : std::true_type {}; template< class T > struct is_member_pointer : is_member_pointer_helper<typename...
It's easier to understand if you spell the types with words. T U::* is a "pointer to member of class U that has type T". int(cls::*)(int, int) is a "pointer to member of class cls that has type 'a function with parameters (int, int), returning int'". Hence U is cls, and T is a "function with parameters (int, int), retu...
67,243,391
67,243,838
How to initialize tuple of vectors out of a variadic template pack and list of objects which use the same template types?
Below is a simplified description of what I intend to do and the code with which I'm approaching it. I have a structure TEmitter<Ts...> where Ts... is a list of components stored in a std::tuple inside of TEmitter. Lets say there are two emitters: e1<A, B, C> e2<A, B, C> I'd like to create a class EmitterMemory<Ts.....
Not exactly as you asked... with a variadic list of elements instead of an initializer list... but adding an helper method, should works as follows template <typename T, typename ... Ems> static std::vector<T> getVect(Ems const & ... ems) { return { get<T>(ems)... }; } template <typename ... Ems> EmitterMemory (Ems c...
67,243,483
67,243,524
User input not pushing in to vector correctly
I'm attempting to allow the user to push an unlimited amount of integers in to a vector, however when i print the vector to the console, i receive -1414812757-1414812757 rather than the numbers pushed in. This applies whether i enter multiple numbers 5 4 2 or just one number 5. What am i missing here? Thanks Here is my...
You only input one number. There is no loop around: std::cin >> userinp; inputs.push_back(userinp); That means that your access is out of bounds when you do this: std::cout << inputs[1] << inputs[2]; You program therefore has undefined behavior and it could print just about anything - or make your computer explode (s...
67,243,555
67,243,809
c++: Reason of "No instance of overloaded function"
I am trying to sort a vector of arrays using "Insertion sort" method. But I am facing error shown at the bottom referring to these two lines: vec.insert(j , vec[i]); vec.erase(i+1); complete code: #include<iostream> #include<vector> /* I could do it recursively */ void ins_sort(std::vector<int> vec ); int main(){ ...
A quick and dirty workaround: vec.insert(vec.begin() + j , vec[i]);//inserting vec[i] into the right position vec.erase(vec.begin() + i + 1); //erasing vec[i] which now is vec[i+1] after insertion Also, please return the sorted vector from the ins_sort function
67,243,764
67,245,759
How to eliminate the extra asterisk shown from the prime factorization output?
The following code inputs an integer (n) from the user and outputs the prime decomposition of n. I need to have the following output (as an example), but can't reach it: Input: 98 Output: 2*7^2 The actual wrong output, which has an extra "*" is: 2*7^2* ^ Maybe there is another solution using functions, which I do...
So one of the possible solutions to my question, according to @Jonathan Leffler's comment is as follows: #include <iostream> #include <cmath> using namespace std; const char *pad = ""; int main() { int n, countA = 0, countB = 0; cin>>n; while(n % 2 == 0) { n /= 2; countA++; } if...
67,244,026
67,244,259
Why the code does not loop when user enter incorrect lowercase letter
I am writing a code that generates a random number then assign the number to a letter in string letters then user has to guess the letter. I am trying to loop the the question "Enter one lowercase letter: " if the user enters a letter that does not match randomLetter, but at the same time I have to make sure the letter...
The specific problems you highlighted is caused by the looping condition, while(letterGuess.length() != 1) here when the user in the first iteration enters just one letter, the letterGuess string will have size = 1, and hence will cause breaking of loop. Another problem is the fact that randomNumber remains 0, for it ...
67,244,134
67,272,534
How to pass *& and **& parameter to C++ dll from C# code
I have C++ dll as par below Function prototype and structure definition extern "C" int __declspec(dllexport) DoOPeration(DataStruct *&, DataStructInfo **&); typedef struct { int count; float CountData; bool flg; BYTE* data; char info[100]; }DataStruct; typedef struct { ...
I got the solution with below approach. C# side code DLL import, structure definition [DllImport(@"C:\TestDll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int DoOperation(ref IntPtr all, ref IntPtr[] part); [StructLayout(LayoutKind.Sequential)] public struct DataStruct { public int co...
67,244,174
67,244,285
How to implement a Queue using Linked List in C++ by classes only
I have a Linked List class, implemented like this (and tested too): template <class T> class LList { LNode<T>* head; LNode<T>* tail; int size; // proporciona muitas vantagens LNode<T>* rCopy(LNode<T>* right); public: LList() : head(nullptr), tail(nullptr), size(0) {} LList(const LList& other) : ...
Initially the tail, head are nullptr so when the first element is inserted, you attempt to access tail->next in insertAtBack where tail is nullptr causing the error (probably an uncaught exception), if the tail is nullptr, simply assign it the tmp value. place a nullptr check for the expression like so.. // O(1) v...
67,244,237
67,245,177
Error when building C++ application using KXmlGuiWindow
I was following an introductory tutorial for using the KDE Framework and ran into problems when compiling. The code is the same as in the tutorial. The compiler outputs: fatal error: KXmlGuiWindow: No such file or directory My first thought was that I am simply missing a package so I used apt-cache search to search for...
Its hard to answer a question with rather a small amount of important data, but I'll try to give you some hints how to fix the problem First, what is the complete error message? Does it come from the compiler or linker? I guess it's the compiler. So most likely the line that makes the compiler unhappy is this: #incl...
67,244,250
67,245,048
I'm trying to delete a node from list with the least value, but i have problems with rebuilding a link between nodes
As I said i want to delete from list node with minimal value, to do that i have second function(which works) and it just returns an int, which is a minimal node value in a list. I'm passing this int to the function which should search list for this value and delete a node which contains it, but i have problem with rebu...
The loop ends one iteration before the node I want to delete so I have to iterate the prev and tmp node one more time, then the link needs to be rebuilt with the next node from tmp so iterating to the next node is once again needed. void Edge_List::Delete_Minimal_Weight_Edge(int min_weight) { Edge* tmp = new Edge; ...
67,244,685
67,245,113
Displaying items in QTableWidget
I need to add items to the QTableWidget,The Items are QList qList, I tried some code as int row = 0; QList<Players>::iterator j; for (j = qList.begin(); j != qList.end(); ++j){ ui->tableWidget->insertRow(qList.count); ui->tableWidget->setItem(row, 0, new QTableWid...
I cannot comment if there is some issue with something else without seeing the entire code but this line seems wrong ui->tableWidget->insertRow(qList.count); From qtablewidget documentation void QTableWidget::insertRow(int row) Inserts an empty row into the table at row. qlist.count appears to be the total length of...
67,244,861
67,244,980
constexpr, or not constexpr, that is the question
I was playing around with constexpr in C++ and noticed a strange behavior that I wish to understand. Consider this code from 5.19 section of Standard. constexpr int f1(int k) { constexpr int x = k; // error: x is not initialized by a // constant expression because lifetime of k ...
A function that's constexpr means that the function potentially can be evaluated at compile-time. The function must however also be callable with a run-time value, and produce a run-time result. A variable that's constexpr has to be a compile time constant. Period. What that means for your validateIP function is that y...
67,245,631
67,245,736
Unable to use stb_image
I was working on a project and I was trying to get an image to load so I could use it as a texture, but I ran into an issue when I tried to include stb_image. I put stb_image.h in src/vendor/stb_image/ , made a cpp file named stb_image.cpp with #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" in the file, and p...
The file which contains the implementation of the stb methods (src/vendor/stb_image/stb_image.cpp) is not part of your compilation as can be seen by checking which cpp files are mentioned in your build command. The reason for this is that the cmake file is set up to only compile files in the src folder, but not files i...
67,246,056
67,246,085
How do I split a string by character? C++
I'm working on a fun random ICAO translator program and I'm almost done with it but I'm having one little problem. How do I go about splitting a string by each character? For example the output I want is; The word mike translated in the ICAO alphabet is: m: Mike i: Indiana k: Kilo e: Echo So far I just get; The word mi...
If I understand your post correctly, you don't want to split a string but to iterate through its characters. In C++11: for (char& c : word) { // switch (c) }
67,246,672
67,246,811
How to add a certain amount of elements in a vector without using a loop C++
I'm trying to add 100 elements in a vector located inside a class, but I can't use a for loop because the vector is defined outside of a function. Is there any way for me to add the values without having to manually list them? class Player { vector<bool> able; // set 10 values to 0 vector<bool> tertiary; // set...
Values of bool should really be trueor false although 0 will convert to false. If you want to set your members as indicated in your code you can do that this way: class Player { std::vector<bool> able = std::vector<bool>(10, false); std::vector<bool> tertiary = std::vector<bool>(100, false); void other_fun...
67,246,858
67,247,974
Optimal producer/consumer thread pattern in Qt
I have implemented a producer/consumer pattern using Qt threads. Multiple producer threads generate data that are combined by a consumer. Communication is implemented using signals/slots and queued connections. This works fine as long as the consumer is able to consume the data faster than the producer threads produce ...
I think you should move away from using Qt in this case because while the event handling is quite fast, it has clearly not been designed for HPC workloads targeting many-cores (because of the centralized sequential event queue). So I think you should use a fast atomic muti-producer/multi-consumer (MPMC) queue. While yo...
67,247,503
67,255,573
Qt/c++ call for a second window
I am creating a desktop application in qt using c++ and am struggling with linking two projects together. The first project is a chess game and the second one is from where i want to start . I want to add a new QPushbutton "Play a game" then a new window will open showing the game . I added all .cpp and .h file from th...
You do not need .ui files. You just have to write the function yourself. I don't know what the main widget that owns the button is called so I'll call it TLWidget for now. and use ... to represent some other code that may be in there. #include<QtWidgets/QDialog> #include "game.h" // this is the widget you want in a n...
67,247,593
67,247,629
error: too many arguments to function 'int rand0_toN1()'
I can't understand the problem, I am trying to learn c++, but I never got this error before, other answers regarding this type of error were too advanced for my level and for me to follow I use Code Blocks 20.03 on windows 10 #include <iostream> #include <math.h> #include <iomanip> #include <stdlib.h> #include <time.h>...
You have declared with no parameter int rand0_toN1(); // Add parameter here Your definition has a parameter int rand0_toN1(int n){ return rand() % n; }
67,247,952
67,262,056
Flying camera using glm is acting weird
I´m working on a Vulkan application and want to implement a "flying camera" which can move around anywhere freely. I placed a cube in the middle of the scene that I can fly around. The camera position works perfectly but the rotation acts weirdly as soon as I move around the cube. When I´m on the opposite side of the c...
It looks to me as if you were rotating the camera in world space (but I can't tell for sure because the code that invokes Camera::rotate is not included in your question). If my assumption is correct, rotating in camera space should solve the problem. I.e. assuming that Camera::rotate performs a rotation relative to th...
67,247,965
67,248,025
Overloading function template based on lambda arguments
I am trying to create a function where callers can pass in lambdas with a certain set of known parameters (the return type can be anything the caller wants) Let's say the possible lambda signatures are T (Widget*) T (Widget2*) I've tried a couple things but I can't get any of them to work struct Widget2{ int coun...
You can use enable_if to sfinae away the wrong overload template<typename Fn, std::enable_if_t<std::is_invocable_v<Fn, Widget*>, int> = 0> auto doIt(Fn&& fn) { return fn(_sibling); } template<typename Fn, std::enable_if_t<std::is_invocable_v<Fn, Widget2*>, int> = 0> auto doIt(Fn&& fn) { return fn(_other); } N...
67,247,968
67,248,378
Sparse matrix-dense vector multiplication with matrix known at compile time
I have a sparse matrix with only zeros and ones as entries (and, for example, with shape 32k x 64k and 0.01% non-zero entries and no patterns to exploit in terms of where the non-zero entries are). The matrix is known at compile time. I want to perform matrix-vector multiplication (modulo 2) with non-sparse vectors (no...
I'm not sure why though - is the sheer codesize slowing it down that much? The problem is that the executable is big, the the OS will fetch a lot of pages from your storage device. This process is very slow. The processor will often stall waiting for data to be loaded. And even the code would be already loaded in the...
67,248,308
67,324,438
How vtable pointer is chosen among other vtable pointers in a class?
I am quite interested about virtual inheritance and this thing creates mystery for me. Let's consider an example with virtual inheritance: struct Base { virtual void v() { std::cout << "v"; } }; struct IntermediateDerivedFirst : virtual Base { virtual void w() { std::cout << "w"; } }; struct IntermediateDeriv...
Bjarne Stroustroup wrote a detailed paper on solving the "diamond problem" in multiple inheritance using C++: Stroustrup, B Fall 1989, 'Multiple Inheritance for C++'. Computing Systems, Vol. 2 No. 4, p. 367-395 With the 'virtual Base' declared in both IntermediateDerived classes; you are guaranteed to get only a single...
67,248,510
67,248,565
How to get the key from an unordered_map with the highest value?
I have the following code that looks if a key exists and if so, returns the key and the value: std::unordered_map<std::string, int64_t> id_to_last_observation({ {"apple", 10}, {"lily", 12}, {"avocado", 2}, {"derry", 5}, {"elephant", 13}, {"monkey", 33}, {"pineappl...
No, there is no built-in method that does this. That's what "unordered" means. By definition: the values in an unordered map are not stored in any specific order. Even for a regular, ordered std::map: the only thing that its available methods will give you, if used wisely, is the range of the keys, but you will still n...
67,248,733
67,248,767
Using process to get data from C++ program to Python program
I'm trying to continuously send a string from a C++ program to a Python program using subprocess. The C++ program runs continuously. Here's my C++ program: #include <iostream> #include <math.h> #include <unistd.h> int main(){ std::printf("This Sucks"); } And here's my Python Program: import os import signal from subpr...
The python program is expecting to read a single line at a time. Each line is terminated by a newline character. Your C++ program prints the same string endlessly, but without a trailing newline character. So, to the Python program this looks like an unending line, so it just keeps reading, and reading it, until it run...
67,248,772
67,248,982
Why does using a reference member prevent deleted constructor errors?
Context I have two classes (simplified to the relevant declarations): #include <string> #include <fstream> class Lexer { std::ifstream file_; Lexer(std::string &file) : file_(file){}; }; class Parser { Lexer lexer_; Parser(Lexer &lex) : lexer_(lex){}; }; This fails to compile with the error error: u...
ifstream does have a default constructor. The error you pasted it because of the deleted copy constructor. The code you wrote will not work, because Lexer can not be copy constructed with the default, because ifstream is not copyable. So, to answer you questions: Your understanding is incorrect; though not a bad guess...
67,248,990
67,249,062
Transfer Dynamic Array to new Dynamic Array, Delete Dynamic array filled with Dynamic Objects
If i create a dynamic array of Zebras, and then say, i make a new Temp array where i want to transfer the objects in the original array. I then move pointer from original Array to Temp. do i need to delete the old array items before move array = temp? Also, I seem to leak but not sure why, i appear to delete both arra...
You have what you are deleting backwards, you want: delete[] array; array = nullptr; array = temp; for (int i = 0; i < 10; i++) { delete array[i]; array[i] = NULL; } delete[] array; array = NULL; Note, you also had a mismatched use of delete[] where delete alone should...
67,249,960
67,254,428
Unable to connect remotely to a windbg server, possibly because of a dll version mismatch?
My goal is to control a running instance of WinDbg from another C++ program. I saw that the API DebugConnectWide can let you connect remotely to a debug client, so I tried using it and I made sure to start a server from the running windbg client by entering this command: .server npipe:pipe=testname. I am able to open a...
yes you need the version of the dbgeng.dll that the server is running normally installing same windbg versions in server and client and running the application from clients windbg installation folder will work or you can copy the dbgeng to the local folder where exe is situated copy c:\prograxxxxxx\dbgeng.dll . to the ...
67,250,126
67,250,244
How to declare n linked lists using a for loop in C++?
I am trying to get n from the user which will decide the number of linked lists. I will add elements to these linked lists, create a vector of linked lists and pass the vector to a UDF. I am unable to declare n linked lists using a for loop itself.
From what I understand from the question, maybe this will work for you. Just initialize a vector and keep pushing the new Lists in it. #include <bits/stdc++.h> using namespace std; struct Node { int data; Node* next; Node (int data) { this->data = data; this->next = nullptr; } }; ...
67,250,649
67,250,855
Unable to understand what is happening in a two-dimensional array pointer
I am a newbie to pointers and am facing some problems while trying to understand them. Now I looked up this problem over here. I was not 100% satisfied with the solution. So I did some checking on my own to see what happens. I wanted a pointer to a two-dimensional array so I tried: int arr[2][3] = {{12,23,4},{323,43,3}...
Arrays can decay to pointers. Actually you used that fact when you wrote: int (*ptr)[3] = arr; ptr is "a pointer to the first element of array". The 2D array arr did decay to a pointer to its first element when you used it to initialize ptr. When you dereference ptr you get the first element (of arr), a one-dimensiona...
67,250,973
67,251,427
python's 'connect_ex' equivalent in C++
I'm trying to check whether an address is available for connection in C++. In python it's quite simple, I make a socket and call 'connect_ex' like so: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) res = s.connect_ex((other_host,other_port)) if res == 0: print("connection available") Is ...
Python connect_ex is actually C/C++ connect. Both Python connect and connect_ex do essentially the same, i.e. connecting to the given peer. The only difference is that connect throws an exception if the connection fails while connect_ex simply returns an error. From the documentation: Like connect(address), but return...
67,251,179
67,251,288
While merging two arrays, if array size is taken as input from user then its fine but if sizeof() operator is used, then its a segmentation fault?
//cin>>m>>n; //this makes the programme work I am not getting why is this happening. sizeof() will allot the same value to m and n as (cin) would, then why is there a fault..? #include<iostream> using namespace std; int * merge(int A[], int B[], int m, int n) { for(int i=m,j=0; i<(m+n);i++, j++...
The problem with your code is that you try to write to A after its allocated value. If you want to add values to A you would need to create a new array with the new value, and assign to that. We could change your code to work like this #include <iostream> using namespace std; // 1. Merge does not return anything, so ...
67,251,199
67,251,428
Access class template arguments in member function
I'd like to have a HandlerGroup that can wrap a bunch of handlers to be used later. Here's my designed API: void handler1(Data* d) {} void handler2(Data* d) {} void handler3(Data* d) {} using Handler = std::function<void(Data*)>; template <typename... Handlers> struct HandlerGroup { void run(Data* data) { // ...
Since C++17 you should use auto... as template parameters,by this you can instatiate your template with passed pointers to function. Then you can create in based-range for loop initializer list with unpacked Handler(functionPointer), and just call function wrapper: using Handler = std::function<void(Data*)>; template ...
67,251,672
67,253,683
Automating explicit template instantiation
To reduce compile times in a template-heavy project, I'm trying to explicitly instantiate many templates in a separate compilation unit. Because these templates depend on enum class members, I'm able to list all possible instantiations. I want all other cpp-files to only see the declaration. While I'm able to do this, ...
If the compiler sees that code isn't referred to, even for static initialization with side effects, it can eliminate it, and I think that's the case in your example. It can "prove" those class instantiations are not used, and so the side effects are lost. For a non-standard solution, but one that works on g++ (and pre...
67,251,966
67,258,301
Minimum XOR problem, exceeds the time limit and gives different answers in few cases
I am trying to solve the Minimum AND xor OR problem (here) from the hacker rank, it runs well in the sample case but in the 1st input case scenario where the number of test case(T) is 1000 it provides 20 wrong answers Ex.: The input array of 10 numbers [853, 864, 10, 547, 954, 235, 822, 429, 628, 569] gives the result ...
Both problems, the erroneous results and the time limit exceeded, appear to be caused by this routine: void sort(int arr[], int N) { int temp; for (int i = 0; i < N - 1; i++) { for (int j = i + 1; j < N - 1; j++) { if (arr[i] > arr[j]) { temp = arr[i];...
67,252,131
67,252,598
CMake build error: undefined reference to 'deflateEnd'
I'm trying to use zlib in my project. The CMakeLists.txt is as follows: cmake_minimum_required(VERSION 3.5) project(cmake-demo LANGUAGES CXX) # The version number. set(CMDemo_VERSION_MAJOR 0) set(CMDemo_VERSION_MINOR 1) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) include(${PROJECT_SOURCE_DIR}/buil...
The thing is, that you have to set the path to the library file as the target_link_libraries argument. According to the documentation, if you want to link the library, each argument of target_link_libraries can be: A library target name A full path to a library file (e.g. /usr/lib/foo.so) A plain library name (e.g. fo...
67,252,336
67,252,575
How to use shared_ptr to manage an object placed with placement new?
A fairly common thing I need to do is allot an object and some memory it'd like, in a strictly contagious region of memory together: class Thing{ static_assert(alignof(Thing) == alignof(uint32), "party's over"); public: ~Thing(){ //// if only, but this would result in the equivalent of `free(danglin...
std::shared_ptr accepts a deleter function as a second parameter, so you can use that to define how the managed object will be destroyed. Here's a simplified example: class Thing { public: ~Thing() { std::cout << "~Thing\n"; } static std::shared_ptr<Thing> create() { char * data = new c...
67,252,342
67,252,357
How can I iterate through unordered_map which is in struct?
I have the following struct: struct Node; typedef unordered_map<char, Node*> Table; struct Node { Table table = {{'\0', nullptr}}; bool terminal = false; }; which I use in the class to store the items. So I am trying to write the destructor. My idea was recursively iterate through all nodes until we reach a ...
You should check for unequality. while (it != cur_node->table.end()) {
67,252,437
67,252,461
Why is the "if" not executed within a loop?
The cout << "Fin", it is never executed int main(){ int num, suma=0, divisor=0; cout<<"Escribe un número"<<endl; cin>>num; cout<<num<<": "; while(divisor<num){ if(num % divisor==0){ cout<<divisor; } } cout<<"Fin";
num % divisor with divisor=0 does division by zero, which typically leads to aborting. You should give another initial value (maybe 1 or 2 looks good, depending on the purpose) to that. Also, as @KfirVentura pointed out, you should update divisor (or num) in the loop, or the loop will run infinitely if divisor<num init...
67,252,440
67,262,642
wxWindows 2.4.2 configuration failed saying checking for toolkit... configure: error: Please specify at most one toolkit
I am new to Linux environment, we have task to migrate a Windows wxWidgets(version 2.4.2) GUI application to Linux platform(RHEL8 or 8.3).The application is successful on Visual studio 2017&2019(Compiler MSVC++ 14.1 and 14.2) using the wxWindows-2.4.2(very old one). But when i try to build wxWindows2.4.2 on Linux( g++ ...
You can successfully run the configure phase by first performing dnf install gtk2-devel, and then configuring with ./configure --enable-gtk2. However, (not surprisingly), wx 2.4.2 will not successfully build on RHEL8 (I tried); there will be a bunch of compilation errors. Those are not impossible to fix, but I wonder i...
67,253,303
67,253,359
Function returning Int instead of float
I am experimenting with function pointers and lambdas in C++ and my function definitions are as follows - float max(float a, float b){ std::cout<<"In float max"<<std::endl; return (a > b) ? a : b; } int max(int a, int b){ std::cout<<"In Int max"<<std::endl; return (a > b) ? a : b; } template<typename ...
template<typename type1, typename type2> int compareNumber(type1 a, type1 b, type2 function){ return function(a, b); } There is you code, you have change "int compareNumber" to "type1 compareNumber" because you don't know what type of variable you will get template<typename type1, typename type2> type1 compareNumber(t...
67,253,396
67,253,561
C++: check if the value stored in std::any is integral
There's a value stored in std::any and I want to know if it's an integral value (char, short, int, long, both signed and unsigned) or a floating point value (float, double), or something else. If I only had to check for int values, I would do this: std::any a; if (a.type() == typeid(int)) { // do some logic for int }...
std::any is a type erasure class. It only remembers the exact type, and the ability to cast back to that exact type (plus how to copy/move/destroy it). If you want to remember other facts about a type stored, you have to do the work yourself. There is no way to get at the T within std::any without checking for that exa...
67,253,779
67,253,829
Is it possible to take the class method as comparator?
I have a private comparator in Level class: bool positionCmp(Entity* a, Entity* b); and when I try to use this in another Level class method: void Level::drawEntities(std::vector<Entity*> entities) { sort(entities.begin(), entities.end(), positionCmp); for (int i = 0; i < entities.size(); ++i) entities[i]->...
Declare the member function static, and use either syntax. A member function bool positionCmp(Entity* a, Entity* b); in class Level effectively has a third implied parameter with type Level* for the this pointer, even if the definition doesn't actually use this or any members of this. So it can't be called without an a...
67,254,095
67,254,544
What is the purpose of libSDL2main.a?
Some sources say to have -lSDL2main.a as one of the files to link against while building SDL2 programs but some don't. The program works fine in either cases. What is it for?
Its purpose is to make entry point the same on all platforms - int main(int argc, char **argv), with UTF8-encoded arguments. While it is so on e.g. linux (where SDLmain doesn't exist or empty), other target systems may follow different scheme. For example, windows programs may have different entry points - main, WinMai...
67,254,154
67,254,480
How to UPDATE_COMMAND_UI with SendMessage
I want to enable/disable menu items at some events, what is independent from UPDATE_COMMAND_UI handlers, so, I have not a CCmdUI object, so, I want to send a message, what invokes the handler. I tried this: SendMessage(WM_COMMAND, CN_UPDATE_COMMAND_UI, ID_VIEW_SYNTAXHIGHLIGHT); Is this good? If do not, what is the...
No, this in not correct. You need to go to the Class View, then go to the Events tab and add an ON_UPDATE_COMMAND_UI handler. Inside the implementation, you call pCmdUI->Enable() and/or pCmdUI->SetCheck() or pCmdUI->SetRadio(), depending on the functionality you want the UI items to have. What is so much great with thi...
67,254,453
67,255,863
A more effective way to apply std::set_difference for std::map
https://en.cppreference.com/w/cpp/algorithm/set_difference I want to find the differences of 2 maps -- just by comparing the keys. map<string, int> m1 = { {"abc", 1},{"ttt", 2}, {"ccc", 3}, }; map<string, int> m2 = { {"abc", 3},{"bbb", 2}, {"ccc", 3}, }; std::vector<std::pair<string, int>> diff; std::set_difference(m1...
If you just want to store the keys of the pairs produced by set_difference, you can use the range-v3 library: namespace rv = ranges::views; auto diff = rv::set_difference(m1, m2, [](auto& a, auto& b) { return a.first < b.first; }) ...
67,254,558
67,254,737
semaphore and memory ordering
Does std::counting_semaphore from C++20 behave like a mutex / atomic operation? i.e. is semaphore.acquire() an acquire operation (regarding the memory ordering), and is semaphore.release() a release operation?
Acquire and release memory operations ultimately define "happens before" relationships between executions, and it is the "happens before" relationship that permits observing side effects. counting_semaphore::release bypasses acquire/release semantics by just declaring that the release call "strongly happens before" any...
67,254,995
73,539,886
gRPC(C Base) polling engine is built with 'epollex' despite being under linux kernel version 4.5
I have a question about gRPC Core(C Base). I have been implementing servers with gRPC(C++) async API in CentOS7. I have been analyzing the gRPC internal code(tag: v1.35.0) for my curiosity. I have recently read a document about poller engine. This document explains as follows. epollex (default but requires kernel vers...
TL;DR RHEL7/CentOS7's kernel 3.10.x may have EPOLLEXCLUSIVE. epollex engine does NOT exist in gRPC source anymore. Details CentOS, or RHEL seems to have EPOLLEXCLUSIVE backported into its kernel 3.10.x, which is available in release >= 7.3. https://bugzilla.redhat.com/show_bug.cgi?id=1426133 gRPC has kernel feature...
67,255,583
67,255,760
Input comma-seperated line of numbers from file to a struct vector container?
I ran into an problem while working on my school assignment. I have an input file from which I should construct objects of a structure. int student_count = 0; struct Student { string name; string surname; int ID; vector<int> grade; } students[50]; int main() { ifstream inp; inp.open("PODACI.txt"); while...
First of all, as was mentioned in a comment under your post, you shouldn't use while (!inp.eof()), use while (inp >> yourVariable(s)) instead, you can read about that in the mentioned link. Second, from you input file example you stuck with the grades part, I guess there are two problems you can't overcome You don't k...
67,255,736
67,255,824
Is there an STL algo that takes predicate for summing up the elements of a vector in C++
I've been working on an assignment to understand all STL algorithms given in C++ library and we're supposed to avoid using for_each and for loop for solving the questions. For the most part I was able to find applicable STL algorithms but I couldn't remember any which summed up a collection or a range while using a pre...
I would use std::accumulate. Example: #include <iostream> #include <numeric> #include <vector> int main() { std::vector<int> v{1,2,3,4,5}; auto result = std::accumulate(v.begin(), v.end(), 0, [](auto x, auto y) { return y%2==0 ? x+y : x; }); std::cout << result << '\n'; // ...
67,255,737
67,255,816
Error in passing the address of a pointer holding array elements to a function in c++
I created an array of characters and then assigned them to a pointer. Then I passed that pointer address to a function which would reverse the array character by character and print them out. I can not understand the error in my code. // ConsoleApplication1.cpp : This file contains the 'main' function. // Program exec...
You call the reverse function 18 times in a loop, and each time you pass a pointer to the next character of the char array, so after the second loop you are already accessing elements out of the bounds of the array. Call reverses only once, and print the characters after the reversion is complete. void reverses(char* p...
67,255,790
67,255,830
C++ problems with class inheritance
I have base class with some variables and functions and multyply child classes. I want to minimaze amount of code required in child classes as much as possible. Example of my code: #include <iostream> class base{ public: int a = 10; int b; void print() { std::cout << a <<std::endl; } }; class chi...
It is a significantly major mistake to override variables from the base class in your child class. This is going to bite you back just so amazingly badly. What is happening is that ch.a is from the child class (the overwritten version), but the print function is part of the base class, so it's going to print that versi...
67,256,088
67,256,498
how to correctly apply std::map
I've read that std::map is often used to map function's pointers but i don't really understand how it works, here is the code where i would use that: // here go all the functions to call int main() { std::array<bool, 4> exercises; int chosenExercise; exercises.fill(false); do { std::cout << ...
First of all, I recommend a quick recap on std::map and std::function. Now, maps have a key and a value. By std::map::operator[] or std::map::at(), you enter a key and a reference to the value is returned. In your case, the key is something like std::string and the value is an std::function pointing to whatever functio...
67,256,173
67,256,296
How to properly store an array of constant data?
My question is particularly pointed towards what's neat and efficient and won't get me made fun of as a programmer. So basically I want to store a huge file of names of PNGS. So of course I'd use an array of strings in order to store all those names. But my question is should I store these strings in something like a b...
A character is 1 byte, whether you write a text file or a binary file. The only savings would be if you did some encoding or compression to it, and text does compress nicely since not all the bits in the chars are usually used. But one pragmatic rule for programming is, "remember the power of plain text". Binary is n...
67,256,325
67,256,667
Texture Aliasing problem while rendering large chunks: OpenGL
Texture rendering is good without any texture error when the world size is small, but when it increased to some extend then it shows texture error. tried several texture mapping techniques but none helped(or may be I am doing it wrong) The issue is similar with shadow acne but it not shadow acne(That i am sure), as I h...
Your texture minification filter is nearest neighbor box sampling. As soon as the sampling frequency falls below half the highest spatial frequency in your texture (the so called Nyquist frequency) you're going to get sampling aliasing artifacts. The solution: Create complete set of mipmap levels that are properly low ...
67,256,527
67,257,169
Should SPIDs of OpenMP thread change if altering the number of threads in 2 sections?
I have 2 OpenMP parallel regions (I am using C++ under gcc under Linux) with different numbers of threads - let's say 4 in one and 8 in the other. Then, if I run ps -T $(pidof name_of_process), 4 SPID are the same all the time, but remaining 4 change for every invocation. A sample output: The first output PID SPID ...
It is probably new threads yes. This is totally dependent of the platform and the OpenMP implementation. Moreover, this is unspecified by the OpenMP specification and so a compliant behavior. However, the GCC runtime (GOMP) and Intel/Clang one (IOMP) tend to reuse the threads as much as possible in practice. On my mach...
67,257,025
67,257,059
Why is wrong constructor being called in parent class?
When I create an object that inherits another class I want the constructor taking the same parameters to be called like in java. class Shape { public: int width, height; Shape(){ std::cout << "in def"; width = 0; height = 0; } Shape(int x, int y){ std::...
The language says that the base class constructor with no arguments is called by default. If you want to call any other specific constructor, you need to do it explicitly: Rectangle(int x, int y) : Shape(x, y) { // ^_________^ call base class constructor // taki...
67,257,227
67,257,383
Determining null pointer
I have function that returns pointer to child object. Function prototype: ObjClass* ObjClass::getChildFromParent(ObjClass* parent = nullptr); This function has default parameter as null pointer and I want to check this parameter anyway, because if pointer is null I will return nullptr but if it's not I will return poi...
According to the C++ 14 Standard (5.10 Equality operators) 2 If at least one of the operands is a pointer, pointer conversions (4.10) and qualification conversions (4.4) are performed on both operands to bring them to their composite pointer type (Clause 5). Comparing pointers is defined as follows: Two pointers compa...
67,257,340
67,265,916
Is it possible to derive the declared function from DUMPBIN /SYMBOLS command?
Can you derive the function declaration from the output of the following command DUMPBIN /SYMBOLS command ? I ran this command as follows: DUMPBIN /SYMBOLS libinfinityhook.lib and got the following from the dump: IfhInitialize@@YAJP6AXIPEAPEAX@Z@Z (long __cdecl IfhInitialize(void (__cdecl*)(unsigned int,void * *))) Wha...
Microsoft Visual Studio comes with a utility called undname.exe which will reverse most decorated names into undecorated names. GNU Binutils has c++filt which will do the same for GCC name mangling. LLVM has llvm-cxxfilt the symbol name demangler, which is compatible with GNU Binutils c++filt because LLVM and GCC use t...
67,257,390
67,263,312
How can Intellisense completion be enabled in Visual Studio for C++?
Intellisense suggestion works perfectly but I want the suggestion to be highlighted. In C#, all it takes to toggle this feature is to press: Ctrl+Alt+Space Or pressing the following button: Is there no such option in case of C++?
As far as I'm concerned, you couldn't use Toggle Completion Mode in c++. Refer to the Doc: IntelliSense features in C++ You can use the menu items and keyboard shortcuts shown in the following image to access IntelliSense. (You couldn't use Toggle Completion Mode) And I suggest you could refer to the thread: Intellise...
67,257,404
67,752,752
Trouble Adding Box2D to Xcode (12.4) project
I have a project that I can open up with Xcode 12.4 (using cmake -G Xcode ..) and I want to be able use Box2D with it. Like some other people, there seems to be a problem with just running brew install box2d (which installs 2.4.1) and then trying #include <Box2D/Box2D.h>. However, I haven't found much help for more rec...
What works for me, in XCode 12.3 at least, is in XCode's Build Settings for the build target: Add -lBox2D to "Other Linker Flags". Add /usr/local/include (the path to where Box2D's include files got installed) to "Header Search Paths". Add /usr/local/lib (the path to where Box2D's library got installed) to "Library Se...
67,257,607
67,257,669
what happens if I reset a unique_ptr with a shared_ptr pointing to it?
I would be surprised if this is not answered somewhere already. But I have not found it. Anyway, as the question says I want to know what happens if I create a shared pointer from a unique pointer. I saw some suggestions from here: // Factor that returns unique_ptr std::unique_ptr<ModelObject_Impl> factory(); // Store...
where I have an owning-object that has a function that returns some internal object by unique_ptr - and I make a shared_ptr out of it (perhaps as suggested in the link). Then later if that owning-object Stop. You have contradicted yourself. If object X owns object Y, and it returns a unique_ptr to Y, it no longer own...
67,257,781
67,257,856
Is there any way to add char in string?
have string "cdfrcs". I want to get string *c*d*f*r*c*s(add stars before every symbol). How should I do it?
You can use regex_replace to add an asterisk before every character in an input string: auto result = std::regex_replace(input, std::regex{"(.)"}, "*$1"); In the regex (.), the . matches every character, and () captures it in capture group 1. The replacement string *$1 specifies that every captured character $1 is rep...
67,257,979
67,258,580
How does inheritance works in case of factory methods in cpp?
I'm trying to solve this simple riddle at codingames and I thought i will exercise in OOP However, it seems I've forgotten how CPP works in this field and I got an error I do not comprehend. /tmp/Answer.cpp:82:1: error: invalid abstract return type ‘Sign’ 82 | Sign from_str(const int value, const std::string& s) ...
You are sufferring from object slicing, both in your return type from from_str and in your vector <Sign>. Like it or not, you are going to have to use pointers, but if you use smart pointers then the pain will go away. So, first change your from_str function like so: std::unique_ptr <Sign> from_str(const int value, co...
67,258,208
67,265,087
Remove duplication in equivalent const and non-const members when returning optional reference by value
This answer explains how to remove duplication in equivalent const and non-const member functions which return by reference. It doesn't help, however, in the case where your function returns an optional reference to another type. Is there a solution for this case? E.g., class Foo { const boost::optional<const Bar&>...
You might do something similar to: class Foo { boost::optional<const Bar&> get_bar() const; boost::optional<Bar&> get_bar() { auto opt = static_cast<const Foo&>(*this).get_bar(); if (opt) return const_cast<Bar&>(*opt); return boost::none; } };
67,258,888
67,259,255
Can I reuse host buffer memory ad libidum or should I re-map it every frame?
My app has a VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT buffer and a permanent command buffer that uploads the memory to a VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT buffer. I have two questions about this setup. This is question 1, question 2 is separate. For better performance, resources (buffers, buffer memories, memory mapping,...
What happens when memory pressure triggers virtual memory pages to be paged out to disk? Um... that's not a thing that happens, actually. Virtual pages are never "paged out"; only physical storage gets paged out. The storage underneath a virtual address range can get paged out, but the actual virtual addresses are fi...
67,259,068
67,993,627
How to detect window resize in Linux
I'm working on a TUI (Text User Interface) library for C++, and I have a function for detecting the size of the console window. Is it possible for me to detect a window resize? I would prefer if it would work with any terminal emulator, but if it matters I am using Ubuntu Budgie 20.10, and my terminal emulator is Tilix...
I found a way by constantly checking the screen size. If the screen size changes, it will be recorded and the screen redrawn.
67,259,197
67,259,336
How to properly call functions?
I'm working on my gematria project that I was asking about before and I managed to fix my main issue there, however I'm trying to break the program down into methods, and I'm getting a error with it and am having trouble figuring out how to fix it. Here is my current code. #include<iostream> #include<unordered_map> #in...
There are two issues with your function call. You are attempting to call a function before it has been declared / defined. Either move AskGematria above PrintGematria or add a prototype declaration for AskGematria ahead of PrintGematria: std::string AskGematria(); The proper way to call the function is std::string ...
67,259,253
67,300,437
How to get the BUILD TYPE while using Android NDK built via CMAKE?
I'm pretty new to integrating Android NDK. I'm trying to return different text while calling a native function to my main app. I have two build types - release and debug. How do I send different strings to my main app for different build types? Below is the code : native-lib.cpp extern "C" JNIEXPORT jstring JNICALL Jav...
add to CMakeLists.txt: if(CMAKE_BUILD_TYPE STREQUAL "Debug") add_definitions("-DMY_DEBUG") else(CMAKE_BUILD_TYPE STREQUAL "Debug") add_definitions("-DMY_RELEASE") endif(CMAKE_BUILD_TYPE STREQUAL "Debug") after that you can use #ifdef in your code another option is to pass arguments to build from gradle script debug { ...
67,259,458
67,266,155
Doubly Linked List in C++ (Pointer being freed was not allocated)
Can someone please tell me where I'm going wrong here? I believe the issue is with the clear() function but am not entirely sure. The goal is the create a doubly linked list. I still need to add some functionality, but feel that i've added enough to run what i've supplied in the main(). #include <iostream> using namesp...
The following offered the correct implementation: Changed doubNode(T data = T(), doubNode<T>* prev = nullptr, doubNode<T>* next = nullptr) : data(data), next(next), prev(prev) {} to doubNode(T data = T(), doubNode<T>* next = nullptr, doubNode<T>* prev = nullptr) : data(data), next(next), prev(prev) {}
67,259,574
67,259,667
How is the child access another child's protected member via member method
How is this compiled? variable d inside protected. How child class method works able to modify another instance of child class protected member variable? Can the child access another child's protected member via member method #include <iostream> using namespace std; class Parent { public: void print() { ...
protected and private keywords limit which classes can access a member-variable, not which objects can access it. As such, code in the Child::works() method is able to access the protected Parent::d member-variable of any Child object, because Child is a subclass of Parent.
67,260,190
67,260,224
Where is mistake in my Merge Sort implementation?
I'm learning sorting algorithms and trying to implement merge sort. I'm using the C++ programming language. The entire sorting algorithm is splitted into two functions -- mergeSort (splitting an array into smaller pieces) and merge (merging already sorted arrays). Please take a look on my code below #include <iostream>...
Your merge(arr, left, right) call in mergeSort doesn't actually merge left and right into arr. It returns a new array instead. Instead, write: arr = merge(arr, left, right);
67,260,305
67,260,382
How to return negative value from function?
Below is the code snippet of reversing a positive of a negative number.But it always returning positive number of all negative numbers.If anyone know what's happening please do let me know. code: int reverse(int x){ int sub=0; if(x<0){ while (x!=0){ sub = sub*10 + x%10; x = x/10; ...
Well: return (sub * -1); Sub will be -321 at this time. And -321 * -1 = 321.
67,260,531
67,260,879
Why can we use arrow with pointer?
I know that the arrow operator -> is used to dereference objects, but I'm quite confused with its usage on this piece of code from Visual Studio .net framework: private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { if (txtDisplay->Text->Contains("-")){ //this could be phrased like (*tx...
You're confusing C++ with the .NET framework and its C++ extensions. The txtDisplay object has a Text property which is likely a System::String^ which means it's a managed object. So you can 'assign' values to a managed object much like you can assign values to any other assignable type or that have the assignment oper...
67,260,686
67,263,045
Cache friendliness of randomly accessing a contiguous array
So I'm writing a custom scripting language specifically for ECS like applications, and as the whole point of ECS is to minimize cache misses I figured I might as well apply that to the scripting language as well. Currently my interpreter uses a virtual stack (std::vector<std::byte>) to store all of it's variables. I wa...
Contiguous memory is nice, because many parts of the memory subsystem benefit from locality of reference. But the scale at which the various parts work varies. Typically CPU cache lines are smaller than the page size, e.g. 64 bytes vs 4096 bytes. Your vector will likely span multiple cache lines, so contiguity at that ...
67,260,910
67,261,065
C++ program will not start when trying to redirect console output to text file
I am trying to run a C++ program and redirect the console output to a text file. From my understanding, this is achieved by: ./program > console.txt I am able to compile and run the program using ./program fine and get the console output I am expecting. When I run ./program > console.txt nothing happens, I simply ent...
If you are redirecting to stderr, do ./program 2> console.txt. 2 is the file descriptor number for stderr. stderr should only be used for error output.
67,261,052
67,261,243
malloc in C++ for performance
I'm optimizing a computationally intensive part of a program that has performance as a priority. Currently I am using std::array for various types of data and caches that cannot be initialized immediately. I would like to allocate the memory for the cache without default initializing the elements for the sake of perfor...
Allocate an array of bytes that is large enough to hold the maximum number of elements you want to eventually construct. You can then use placement-new whenever you want to construct an object at a given byte offset within the array. You can alternatively use std::aligned_storage as the array element type instead of us...
67,261,082
67,261,114
How do i check if theres 2 substring in a string?
I want to check if 2 substrings in a string exist like for example: string main_string = 'Hello "sir"'; I want to check if that string included 2 ",must included 2. And also I want to check this: string main_string = 'Bruh (moment)'; I want to check if that string included both ( and ).
In both cases, you can use std::string::find(). std::string main_string = "Hello \"sir\""; std::size_t pos = main_string.find('"'); if (pos != std::string::npos) { pos = main_string.find('"', pos+1); if (pos != std::string::npos) { ... } } std::string main_string = "Bruh (moment)"; std::size_t p...
67,261,125
67,261,610
C++ What memory order do I need for the atomics in this MPMC queue?
This is my implementation of a lockless, waitless, multithread-safe MPMC queue using only atomics: template <typename T, int32_t SIZE> class queue_mpmc { T ar[SIZE]; std::atomic_uint64_t start; std::atomic_uint64_t end; std::atomic_int32_t precount; std::atomic_int32_t postcount; public: queue...
If the other bugs are fixed, most likely start, end, and precount can all be memory_order_relaxed in all uses. postcount is the variable that signifies that a value has been written to the queue. ie it controls the publishing of the value, and the reading of the value. So postcount needs memory_order_release ("publish"...
67,262,197
67,262,305
C++ Can't access parent method from derived template specialization despite public access
I'm trying to access a parent method from a derived template class, but despite using public access everywhere, and "this->" to be safe, I'm getting the error. error: 'class Derived<TagTypeA, int>' has no member named 'insert' I don't know if I'm making a stupid mistake somewhere, but I can't work out why the Derived ...
Compiler needs a suspect base class to contain method in question in order to consider the code legal. The class described by template specialization template<typename T> class Derived<TagTypeA, T> { public: void call_parent_insert(const T& v) { this->insert(v); } }; declares that type Derived<TagTypeA ,T> does...
67,262,415
67,308,071
`std::call_once` always segfaults on Clang 12 on Windows (when using libstdc++)
I'm looking for a workaround, which will probably involve patching libstdc++ headers. Preserving binary compatibility is preferred but not obligatory, since I'm not using any precompiled C++ code except libstdc++. I want to keep the std::call_once interface, since I'm trying to compile third-party code that uses is, wh...
This was fixed in Clang 13, in commit 0e4cf80. (Thanks @mstorsjo.) If you're stuck with Clang 12, you can patch libstdc++ headers as a workaround. The patch below replaces global thread-local variables with static function-local thread-local variables, which are not affected by the bug. To apply, save following to pat...
67,262,512
67,262,803
C++ vector push_back not making a copy?
vector<minHeap> letters; letters = countLetters(text); while (letters.size() >= 2) { minHeap first = popMin(&letters); minHeap second = popMin(&letters); minHeap third('$'); third.count = first.count + second.count; third.left = &first; third.right = &second; letters.push_back(third); } I...
You're storing &first and &second, which become invalid pointers when the current iteration ends. If you dereference them after that, your program has undefined behaviour. @molbdnilo So I changed my code to : vector<minHeap> letters; letters = countLetters(text); while (letters.size() >= 2) { mi...
67,263,136
67,263,386
Can we use pair as the name for a vector?
I came across an expression that states: vector<int> pair(n). As pair is an inbuilt structure in itself, can we use it as a variable name in c++ and why??
As pair is an inbuilt structure in itself, can we use it as a variable name in c++ and why? That is not correct. The Standard Template Library provides a class template called "pair" but that is not an inbuilt type and, furthermore, "pair" is neither a keyword nor a reserved word in the C++ language. Furthermore, the...
67,263,438
67,263,491
C++ destructor called after calling constructor
By looking at the example: #include <iostream> int wow=0; class Foo{ int cow = 0; public: Foo(){ std::cout << "Foo +\n"; cow = 0; ++wow; } Foo(int n){ std::cout << "Foo has " << n << "\n"; cow = n; ++wow; } ~Foo(){ std::cout << cow << " ~ Foo -\n"; } void print(){ std:...
In this assignment statement *a = Foo(10); there is created a temporary object of the type Foo that is assigned to the object specified by the expression *a using the default copy assignment operator (neither copy or move constructor is called here). After the assignment the temporary object is deleted. The undeclare...
67,263,586
67,263,773
Is compiler language support common to all compiler ports
I'm using GNU Arm Embedded Toolchain 10-2020-q4-major (arm-none-eabi-* 10.2.1) and I would like to take advantage of modern c++ features. So I'm trying to find out which c++ features (language core features as well as libstdc++ features) are available with this particular toolchain. I read through this matrix https://g...
As you can see on the gcc.gnu site you listed, all of the C++17 and C++20 features are listed. The "Available in GCC?" specifies which version of the GCC compiler is required to have a given feature available. It is essentially not your toolchain, but the compiler (as part of that tool chain) that defines your feature ...
67,263,792
67,263,905
What is the word() function?
I am trying to convert some C++ function to use in my python script and stumbled upon this: int Crc16(args...) { // Some calulations return (int)word(~ByteHi,~ByteLow) } This is the end of a CRC16 calculator which I need, I have no idea what this return does? Especially the "word" function. The ~ is the Bitwise...
After viewing the project's readme, we know it's possible to be an Arduino related utils, then check the doc here: https://www.arduino.cc/reference/en/language/variables/conversion/wordcast/ Description Converts a value to the word data type. Syntax word(x) word(h, l) (word)x (C-style type conversion) Parameters x: a...
67,264,007
67,264,100
How can you assign a const reference to a non const variable?
Consider following code, onData callback invoked and then I assign the const reference to a variable. I want to understand how it works. I was told you can't modify const references but here it looks like you can by assigning to a non-const variable. void onData(const evpp::TCPConnPtr &socket) { evpp::TCPConnPtr con...
In simple terms, a reference is just an alias to the referenced object. When a reference is const it means you may not modify the object via that reference (the object can be modified via other means, this distinction is important, especially with multithreading). Copying a const reference is like copying the reference...
67,264,046
67,610,042
Bresenham line coding not drawing a line
I tried to use the following code Bresenham line drawing but by OpenGL GLUT project. I have successfully run the code but no outcome result. I'm trying to draw to points between the two points p1(5,8) and P2(9,11). But seems have a problem with my for loop. int x1,x2,y1,y2; void drawline(int x0, int y0, int x1, int y1)...
I had double global variables which I didn't notice. Thank you all for your support.
67,264,213
67,531,183
Using a c++ library in my PHP Extension: undefined symbol: mpfr_get_emin_min
Trying to compile my own MPFR Module for PHP, using the mpfr.so library. My extension itself has a simple ping function, which simply returns "pong" to verify, that the extension is actually loaded, and another function, which returns the following: return ("MPFR library: %-12s\nMPFR header: %s (based on %d.%d.%d)\n",...
Your extension does not know of the function. You have to include the mpfr lib into your extension, so it will be compiled / loaded into it.
67,264,816
67,266,105
static const variable from a another static const variable gives compile error?
Why this compiles: static const short test_value = 0x0100; static const uint8_t *is_big_endian = ((const uint8_t *) &test_value); but this doesn't: static const short test_value = 0x0100; static const uint8_t is_big_endian = *((const uint8_t *) &test_value); with the error: expression must have a constant value I m...
The C standard does not require compilers to figure out the bytes that make up an object while evaluating expressions for initializers. So, while *((const uint8_t *) &test_value) might have a logically determined value that you can figure out from knowledge of test_value, the compiler is not required to figure it out. ...
67,265,082
67,265,376
C# to C++ function equivelent - .tostring("X4")
Is there a functional equivalent for the C# function .tostring("X4"), to C++? I've been scratching my head for a few days wondering why my sensor is reporting a different serial number to what the manufacturer software (written in C#) and what my C++ code reports. The serial number is also written on the sensor, which ...
There's is no readily available equivalent function in C++, but you could create one that works in a similar way: #include <iostream> #include <sstream> #include <string> template<class T> std::string tostringX(unsigned len, T v) { std::ostringstream os; os << std::hex << v; auto rv = os.str(); if(rv.s...
67,265,088
67,265,292
C++ Member Initializer Lists Problem: Declaration Order on Private Member Variables
This is my first ever question posted on Stack Overflow, hope someone could explain it. So basically the two classes are the same except the order of the private member variables. The output is 10 20 10 0 I cannot understand why the order of declaration affects the output. #include <iostream> using namespace std; clas...
Class members are initialized in the order of their declaration. Initialization Order of Class Data Members #include <iostream> class MyClass{ public: MyClass(int value): b(value++), a(value++){ std::cout << b << " " << a << " " << std::endl; } private: int b; int a; }; class YourClass{ public...
67,265,333
67,265,689
Getting the standard deviation of a Eigen::vector
I need to have standard deviation of a vector in Eigen library. I have not found it. So i tried it: Eigen::VectorXd ys(5); ys << 1, 2, 3, 4, 5; double std_dev = sqrt((ys - ys.mean()).square().sum() / (ys.size() - 1)); // Error with minus sign (ys-ys.mean()) But getting error. error: Severity Code ...
An Eigen::VectorXd is defined as typedef Matrix<double, Dynamic, 1> VectorXd; so it is a special form of an Eigen::Matrix. You are trying to subtract a scalar ys.mean() from a vector ys which is an coefficient-wise operation. The Eigen::Matrix class is not intended to be used with coefficient-wise operations but for li...