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
73,719,092
73,719,154
How to reopen the winapi window?
I have WinAPI application with menu. I click "Graphics" and choose open or draw. It doesn't matter what exactly. Then I close the child window. When I try to open it again, it doesn't work. Maybe I should put somewhere ShowWindow(hWnd, SW_HIDE). But I don't understand, where it should be. Maybe there is another solutio...
RegisterClassW(&GraphClass) doesn't work the second time, because the window class is already registered, because you already registered it the first time. It returns false to tell you that it didn't work, then your code doesn't open the window. To reiterate: You told the computer, that if RegisterClassW(&GraphClass) d...
73,719,101
73,720,808
Connecting a C++ program to a Python script with shared memory
I'm trying to connect a C++ program to python using shared memory but I don't know how to pass the name of the memory segment to python. Here is my C++ code: key_t key = ftok("address", 1); int shm_o; char* msg = "hello there"; int len = strlen(msg) + 1; void* addr; shm_o = shmget(key, 20, IPC_CREAT | 0600); if(shm_o ...
Taking the liberty to post a working example here for POSIX shared memory segments, which will work across C/C++ and Python on Linux/UNIX-like systems. This will not work on Windows. C++ code to create and write data into a shared memory segment (name provided on command line): #include <sys/mman.h> #include <sys/stat....
73,719,982
73,720,304
Helper function to construct 2D arrays
Am I breaking C++ coding conventions writing a helper function which allocates a 2D array outside main()? Because my application calls for many N-dimensional arrays I want to ensure the same process is followed. A prototype which demonstrates what I am doing : #include <iostream> // my helper function which allocates ...
There is a difference between allocating 2D arrays like this and what you get when you declare a local variable like int ary[10][10] that based on your statement My concern is that this operation may not be memory-safe, since it appears that I am allocating memory for an array outside of the function in which it is us...
73,720,038
74,635,915
Why would SECBUFFER_EXTRA point to the inside of SECBUFFER_STREAM_TRAILER after calling DecryptMessage?
We have a client application on a Windows 7 SP1 VM with the appropriate hotfixes and registry settings to enable TLS 1.2 communication. We have a server application on a Windows Server 2019 Datacenter VM. The client and server establish a TLS 1.2 session (according to QueryContextAttributes) and the negotiated stream t...
The negotiated stream sizes represent the maximum possible value of the header and trailer. The actual values may be less. When the client was sending TLS application data messages, Schannel would sometimes construct a trailer that was smaller than the negotiated size but our application would always send the [maximum ...
73,720,206
73,720,263
Why does underflow with floating points happen at 2⁻¹²⁶?
When representing a float, why does the exponent face underflow when it hits 2−126 if 8 bits can hold everything from −127 (incl.) to 128 (incl.)?
Exponents range from −126 to +127 because exponents of −127 (all 0s) and +128 (all 1s) are reserved for special numbers. wikipedia
73,720,552
73,814,304
CPPZMQ - Publish and subscribe with standard vector
From the documentation at: https://brettviren.github.io/cppzmq-tour/index.html#intro, it seems that it is possible with CPPZMQ to send and receive a standard vector by using messages or buffers. However, I have not been able to use the vector from the subscriber, I get an error when trying to access it: Segmentation er...
Constructing zmq::message_t directly from STL vector is ok, because iterator based constructor will be called. std::vector<float> v({0.1, 0.2}); message_t msg(v); It will internally copy the content of the vector to the underlying zmq_msg_data casted to float*: std::copy(first, last, data<value_t>()); // value_t == f...
73,720,619
73,721,052
This code that is supposed to get the largest and average of input numbers is not giving me the desired output, what did I get wrong?
I've been trying to get this code to give me an output of "20 9.50" when I input "15 20 0 3 -1" but it keeps giving me the output "20 0.55". This is the code I've made: #include <iostream> #include <iomanip> using namespace std; int main() { int largest = 0; int number = 0; int count = 0; double avg = 0; ...
I am not sure if you are supposed to maintain the average "on the fly". The better, less error-prone, approach is to maintain a total for the life of the loop. Then, after the while loop, you should average by dividing the total by the count. FYI, for everyone else: The -1 ends the while loop and total & count should n...
73,721,288
73,721,442
How to execute a slot or a function with two signals in QT?
I'm working on a QT project. I was wondering if is possible to create a connection using two signals to execute a method. I have three classes: A, B and C. Class A emit a signal when a button is pressed (connected in Class C), also in Class C a QProcess is created (from an instance of class B). In class C I have a conn...
You can store the state of both events and check them both whenever one of them changes. // These should probably be defined in the header of your class. bool processFinished = false; bool buttonClicked = false; void checkState() { if (buttonClicked && processFinished) { doSomething(); } } connect(obj...
73,721,865
73,722,343
c++ async multiple tasks implementation
I have used the tasks in c# in this way: static async Task<string> DoTaskAsync(string name, int timeout) { var start = DateTime.Now; Console.WriteLine("Enter {0}, {1}", name, timeout); await Task.Delay(timeout); Console.WriteLine("Exit {0}, {1}", name, (DateTime.Now - start).TotalMilliseconds); return na...
A more or less direct translation would probably use C++ std::futures returned by std::async. Disclaimer: I don't have bit of C# knowledge and just read about its Tasks a bit just now. I think this is what you are going for. In C++ we use std::chrono::durations instead of plain ints. The resolution of the clocks is of...
73,721,970
73,722,549
How to construct a zip file with libzip
I try to create a compressed file and insert an xml file in it using two libraries (pugixml / libzip), everything goes without error, but when I open the xml file, the encoding at the beginning of the file is weird : Main.cpp : #include <iostream> #include <sstream> #include <zip.h> #include <pugixml.hpp> #include <mem...
The posted program has undefined behaviour due to reading already freed memory. In the example you posted the zip_source_t gets creatd with freep = 0, so you need to make sure that the provided buffer remains valid for the entire lifetime of the zip_source_t object: zip_source_buffer zip_source_t * zip_source_buffer_c...
73,722,250
73,723,722
Qualified names for Julia's `Base` functions/types
Some C++ developers strongly suggest to never use using namespace std, as they prefer to explicitly include the namespace of every function in their code. Reasons for this include clarity when reading code as well as preventing shadowing definitions with equal identifier. According to Julia's documentation, all modules...
Is there a style consensus among Julia programmers whether to use fully qualified names for Base functions and types when writing modules? The consensus is not to use fully qualified names. Does Julia Base have that same issue? No. Package developers are aware of names in Base, and to not overshadow them. Edit See ...
73,722,302
73,723,285
Determine if a generic type is a primitive or enum with underlying primitive at compile time C++ in a function
I'm trying to determine at compile time within a template function if the type T is either a primitive type or an enum with underlying primitive type. In code, I'm trying to do this template <typename T> bool foo(T& input) { bool isPrimitive = std::is_fundamental<T>::value || (std::is_enum<T>::value && std::is_...
Beside the fact that enums support only integral types you could write: template <typename T> bool foo(T& input) { constexpr bool isPrimitive = [](){ if constexpr (std::is_fundamental_v<T>){ return true; } if constexpr (std::is_enum_v<T>){ using underlying_type = type...
73,722,798
73,771,325
ImGUI Popup not showing up but executing the code
I am making a program using ImGui and I want to display a PopUp if the input on one window is bad after clicking the button "OK". It enter the IF statement and execute the code but the popup doesnt show up. ImGui::OpenPopup("Error Creating Image"); // Always center this window when appearing ImVec2 center = ImGui::GetM...
Does the entire code you are showing only run once, when the error occured? The ImGui::BeginPopupModal and the associated if block has to run every frame, otherwise the popup won't get drawn. Something like this: void foo() { // 'foo' runs every frame. if (ImGui::Button("Show popup")) ImGui::OpenPopup("The...
73,723,010
73,723,063
Assigning a class variable in class definition versus at class instantiation
What are the ramifications of assigning a class variable when defining the class versus in the class constructor? Is the variable assigned in the class definition accessible by all class instances? Example of assignment at instantiation: class Foo { private: int x; double y; public: Foo...
In this code snippet int x = 0; double y = 1.; there is no assignments. There are initializations. In this code snippet Foo() { x = 0; y = 1.; } there is indeed used the assignment operator. In general for objects of complex types it can be 1) impossible (either the default constructor or the assignment opera...
73,723,151
73,723,663
How to achieve encapsulation in C++ project
I'm currently learning about OOP design patterns and I'm working on a project whose main class is roughly organized as follows: class MainClass { public: MainClass(int something, CrazyTypeOfAlgorithm algoType); double getResult(); private: std::vector<double> _numbers; CrazyTypeOfAlgorithm...
A common approach would be to make Algorithm a pure virtual (interface) class with various implementations (like AlgorithmSimpleSum below), a bit like this: // Pure Virtual Interface class Algorithm { public: virtual ~Algorithm() = default; virtual double process(double const* begin, double const* end) const =...
73,723,352
73,728,329
Drag and Drop Item list not working properly on ImGUI
Im using ImGUI and I want to implement a layer menu for the images and to move them im using Drag to reorder items in a vector. Sometimes it works just fine but others the images just jumps from the current position to a random one. for (int i = 0; i < this->Images->size(); i++) { ImGui::Image((void*)(intptr_t)thi...
The problem lies at !ImGui::IsItemHovered(), there is small spacing between the lines (cell, selectable,... ), so when the mouse hovers over that spacing, the item isn't hovered but still is actived, and therefore will execute the swap and reset mouse delta multiple times making it goes to the top or bottom of the list...
73,723,354
73,850,966
How to compile with c++ <execution> standard library
The issue I am trying to use the execution policies in the standard algorithm library. However, when I try to compile I get the following error message c:\mingw\lib\gcc\mingw32\9.2.0\include\c++\pstl\parallel_backend_tbb.h:19:10: fatal error: tbb/blocked_range.h: No such file or directory After looking at various othe...
Yes you were correct. By using the package mingw-w64-tbb. You can use -ltbb12 instead of -ltbb. As the library files are related to ltbb12. For using -ltbb option, you should set the Intel oneAPI environment. It can be used by downloading Intel oneAPI Base Toolkit.You can set the environment by sourcing setvars.sh file...
73,724,674
73,724,727
Avoid Overriding method from library
I want to have the same name has the method from the C++ library cmath in a class method but without overriding it by my own method. I know I could just change the name but that is not what I want to do. Is this possible ? calculator.cpp: #include <calculator.h> #include <cmath> int Calculator::pow(int entier, int pui...
You are not overriding anything. Your pow function is in a different scope than std::pow (or the global ::pow). The standard library pow is still there, unchanged by your definition. It is just that unqualified name lookup will only find the functions with the name declared in the inner-most scope where a declaration f...
73,724,841
73,724,861
Why does this variable have different values in different source files?
I have the following code: main.cpp #include "Test.h" int main() { Create(); } Test.h #pragma once #include <iostream> #include "Function.h" class Test { public: Test(); }; extern Test* g_pTest; inline void Create() { g_pTest = new Test; std::cout << "On Test.h: " << std::endl; PrintAddr(); }...
int main() { Create(); } main calls Create(), which does this: g_pTest = new Test; Test gets newed first. g_pTest gets assigned after Test's constructor finishes and the object is constructed. Test's constructor calls PrintAddr which prints the value of g_pTest because it is still nullptr: Test* g_pTest = nul...
73,724,866
73,724,948
Exclude Macro, What can I use like inline function in C++
I don't want to edit the common part of the source code repeatedly. So I separate the other parts with different functions as below. /* Origin */ void MyClass::threadFunc_A() { // many variables in this function ... // do something A ... } void MyClass::threadFunc_B() { // many variables in this f...
No there is no way to do that. C++ has lexical scoping. What you want would be (at least partially) more like dynamic scoping. The point of a function is that it separates some part of the logic into a self-contained block of code that can be reused. If you make the name resolution in the function dependent on the decl...
73,724,906
73,750,649
Output for specific test case in linked list deletes two numbers randomly
I'm working on a linked list program that takes an input for the data of each node like: Sample Input: 2 18 24 3 5 7 9 6 12 Then it takes each group of even numbers like "2, 18, and 24" and reverses it to be "24, 18, and 2." It seems to work on a larger scale according to these unit tests, but this particular one out...
So I figured out it was a minor oversight on my end. The code within reverse_Groups returns head when it's done. I was printing the list from the temp variable rather than the head, so it wasn't printing the first two numbers. Once I figured this out, I added a getHead function that returns the correct head after the r...
73,725,046
73,725,196
When does the conversion happen when passing arguments to thread function?
When reading a book about c++ multi-thread programming, I came across one example below. void f(int i,std::string const& s); void oops(int some_param) { char buffer[1024]; sprintf(buffer, "%i",some_param); std::thread t(f,3,buffer); t.detach(); } In this case, it’s the poin...
As you are saying the array argument is decayed to a char*, which is then copied for the thread. To be more specific the newly created thread executes basically the following expression: std::invoke(auto(std::forward<F>(f)), auto(std::forward<Args>(args))...) where f and args are the parameters of the std::thread cons...
73,725,254
73,725,415
C++ Recursion and Exception Handling with Fibonacci Sequence
This program seems to work for the Fibonacci Sequence using recursion and exception handling. (Yes I want to do it with recursion, I know I can use loops). It is supposed to throw an error if the next result is out of range for long long. Which it works, if I put in most numbers, but if I put in number 91, it shows one...
This line of code is invalid: if((numberOne + numberTwo) < 0) per Is signed integer overflow still undefined behavior in C++? you are relying on Undefined Behaviour, which is a mistake. You can replace your condition with: if( std::numeric_limits<long long>::max() - numberOne < numberTwo ) or more generic: if( std::...
73,725,569
73,725,605
Getting unexpected output when writing a program to find the first perfect square with two odd ending digits
I'm a beginner taking a C++ class. Thanks for your help. So I have to write a program that finds the first perfect square which ALSO has two odd digits, and it doesn't produce the expected output. #include <iostream> #include <cmath> using namespace std; int main() { for (int i = 1; i < 1000; i++) { //...
int secondToLastDigit = i % 100; gives two last digits. Thus lastDigit % 2 != 0 && secondToLastDigit % 2 != 0 tests are equivalent tests of the odd number. Example with 121: secondToLastDigit is 1, secondToLastDigit is 21. 21 % 2 is 1 % 2 is 1. You might want int secondToLastDigit = (i / 10) % 10;.
73,725,881
73,726,346
How can we decide that an integer is power of 2 by using bit manipulation?
For example if the given number n = 16 If it is power of 2 then the output should be true else false, i want the answer by using bit manipulation.
The solution mentioned by @TimRoberts is the most simple way of using bit manipulation. Just check if (n & (n - 1) == 0). Why does this work? Assume n = 8 (1000 in base 2), then n - 1 = 7 (0111 in base 2). If you do a bitwise AND of these two, you get 0. This is true for n equal to any power of 2. So you function shoul...
73,726,579
73,726,660
c++ how to use while properly
I am learning c++ around two weeks and therefore have a lot of questions. It feels like i learn a new sport. My body in my thinking already moving much better than any other olympic players, but the actual movement is so poor. what i want to know is if i can use "while" in cout together. int main() { struct { strin...
You can use an array with elements of type Candidate and then loop through the array and print the values as shown below: //class representing a Candidate info struct Candidate{ string engineType; string brand; int price; int range; }; int main() { //create an array witht element of type Candidat...
73,726,748
73,728,927
IDispatch null pointer exception while creating Active Directory user
I am writing a C++ native method to create an Active Directory user. I am getting a null pointer exception . This code is exactly the same as the code in the official Microsoft documentation. I have mentioned in a comment on which line I get the error: HRESULT CreateUserFromADs( LPCWSTR pwszName, LPCWSTR pwszSA...
You are asking ADsOpenObject() for an IADs* interface pointer, but you are storing it in an IADsContainer* variable. That is a type mismatch, IADs and IADsContainer are unrelated interfaces. So, when you call pUsers->Create(), you are not actually calling IADsContainer::Create() at all, you are actually calling IADs::S...
73,726,828
73,731,890
Use button from a qml to control(interact) the size of Rectangle which is in another qml file [QML] [JS]
I recently start to learn Qt and QML for prototyping some UI and experienced some issue. Basically, I have a Rectangle (id: myItem) in TestB.qml which is considered as a button. I also have another Rectangle (id:changedrect) in TestA.qml. The functionalities I want to implement is when myItem is clicked, the width and ...
The only time that I see your resize function called is when you construct a TestA object. You're getting two printouts of "yes, resize is excuted" because you've created two instances of TestA. From the code you've shown, it will not execute that code when you click on TestB. There's plenty of ways to fix this. My rec...
73,727,407
73,921,271
Make 2D Sprite Face Camera Using Vertex Shader - DirectX 9
Currently, I'm calculating the world matrix in C++ and then pass it to the shader to make the sprite always face the camera: static D3DXVECTOR3 up(0, 0, 1); D3DXMATRIX world, view, proj; // get the world, view and projection matrix g_pd3dDevice->GetTransform(D3DTS_WORLD, &world); g_pd3dDevice->GetTransform(D3DTS_VIEW,...
SimpleMath in the DirectX Tool Kit includes Matrix::CreateBillboard and Matrix::CreateConstrainedBillboard which is specifically designed for creating this kind of transformation matrix. inline Matrix Matrix::CreateBillboard( const Vector3& object, const Vector3& cameraPosition, const Vector3& cameraUp, ...
73,727,501
73,727,628
Run C++ code in mac without Xcode, and use custom header bits/stdc++.h
Trying to run C++ on Vscode on a Mac, but the stdc++.h library is not found. I want to setup bits/stdc++.h instead of the custom header of clang++. fatal error: 'bits/stdc++.h' file not found. It will help if someone give me the c_cpp_properties.json file and settings
stdc++.h setup on mac (without xcode) Assuming that you've installed the homebrew and C/C++ compiler extension. Then follow the steps. As the bits/stdc++ is a GNU GCC extension, where OSX uses the clang compiler. brew install gcc gcc --version go to the /Library/Developer/CommandLineTools/usr/include directory (go t...
73,727,951
73,839,488
Create boost::spsc queue in boost managed shared memory with a runtime size
Shared-memory IPC synchronization (lock-free) My use case aligns very closely with what has been described in the above question. But I wanted to go a step further in creating the spsc queue dynamically with a user defined runtime size. I tried implementing it with the following code: void create_shared_spsc_queue(size...
For posterity: I figured, I was calling the ctor of spsc_queue in wrong order of arguments. The following works: queue_dynamic_ = segment_.construct<ring_buffer_dynamic>(rbuff_name)(sz, string_alloc_); Source: https://www.boost.org/doc/libs/1_80_0/doc/html/boost/lockfree/spsc_queue.html
73,728,232
73,728,413
Converting Integer Types
How does one convert from one integer type to another safely and with setting off alarm bells in compilers and static analysis tools? Different compilers will warn for something like: int i = get_int(); size_t s = i; for loss of signedness or size_t s = get_size(); int i = s; for narrowing. casting can remove the war...
You can try boost::numeric_cast<>. boost numeric_cast returns the result of converting a value of type Source to a value of type Target. If out-of-range is detected, an exception is thrown (see bad_numeric_cast, negative_overflow and positive_overflow ).
73,729,045
73,729,073
Declaring a template class as friend
Here is an MCVE: template <typename T> class A { public: friend class B; }; template <typename T> class B {}; int main() { A<int> a; B<int> b; return 0; } Very simple thing and I dont know why this is giving compiler errors. I am new to using templates. I also tried changing the friend declaration to...
It depends on what you want, if you want to make B<T> a friend of A<T> then friend class B<T>; was right, but it needs a declaration of B: template <typename T> class B; template <typename T> class A { public: friend class B<T>; }; template <typename T> class B {}; int main() { A<int> a; B<int> b; re...
73,729,290
73,729,404
CMake only build lib when compiler supports C++20 or higher
in our project we are using the highest available C and CXX standard by setting set(CMAKE_C_STANDARD 17) set(CMAKE_CXX_STANDARD 20) However the project is also build with some old compilers that do not support C++20. Some libs on the other hand require C++20. How can i configure my project so that these libs are o...
Well, the variable name speaks for itself. https://cmake.org/cmake/help/latest/variable/CMAKE_CXX_STANDARD_REQUIRED.html set(CMAKE_CXX_STANDARD_REQUIRED YES) You should prefer set_target_properties. My expectation is that old compilers automatically skip building the c++20 lib So do not add target if we don't have C...
73,729,659
73,729,787
std::conditional_t, How to conditionally define the type of variable when both branches do not compile at the same time?
I have a templated function which treats 2 types of classes (with old or new format). I want to define a variable that will have its type defined at compile time like: template <typename T> using MyType = std::conditional_t<isNewFormatCondition<T>, typename T::subClass::Format, typename T::Format::reference> template ...
std::conditional_t is not SFINAE, all template arguments must be valid. You can either use SFINAE or simple specialization: #include <type_traits> #include <iostream> template <typename T,bool> struct MyType; template <typename T> struct MyType<T,false> { using type = int; }; template <typename T> struct MyType...
73,730,002
73,732,987
Generalizing std::conditional_t<>
I have a function that computes a certain object from a given parameter (say, an important node from a graph). Now, when calculating such an object, the function might allocate some memory. Sometimes I want the function to just return the result, and sometimes to return the result plus the memory used to compute it. I ...
I don't think you should use std::conditional at all to solve your problem. If I get this right, you want to use a template parameter to tell your function what to return. The elegant way to do this could look something like this: #include <vector> enum class what { what1, what2 }; template <what W> auto compute() { ...
73,730,354
73,732,944
Initialisation in Singleton
So, I am creating a small testing library for some simple tasks. I use the self-registration method to define the tests, but I am getting a segfault that I don't understand where is coming from. My project looks like this Lib | |__include | |__lib.hpp |__src | |__lib.cpp |__examples | |__example.cpp |__Makefile Thi...
So, after careful analysis, it seems like the example.o file was not being generated successfully. I basically added them as a requirement for the executable recipe, and updated the clean recipe. I believe the .a file could also be passed as an input to the final g++ command. LIBNAME := libIntegration.a CXX ...
73,730,634
73,731,011
removing nested paths from vector of strings
I have an std::vector<std::string>paths where each entry is a path and I want to remove all the paths that are sub-directories of another one. If for example I have root/dir1/, root/dir1/sub_dir/ and root/dir2/, the result should be root/dir1/, root/dir2/. The way I've implemented it is by using std::sort + std::unique...
Your predicate is symmetric. Let p be your predicate (the lambda), and a and b some strings, different from each other, but such that p(a, b) is true. Then either a.starts_with(b) or b.starts_with(a). If a.starts_with(b), then p(b, a) is true because s2.starts_with(s1) is true in the lambda. Similarly, if b.starts_with...
73,730,636
73,731,842
objects that're usable constant expressions
I have the following code that demonstrate my problem: int main(void) { const int ci = 42; constexpr int j = ci; } The above program compiles fines. But I'm expecting it to be ill-formed. First, the initializer 42 is an integral constant expression converted to int via identity conversion; then, the converted...
By the definition of "constant-initialized" ([expr.const]/2), the following is constant-initialized because 42 is a constant expression. int ci = 42; By the definition of "potentially-constant" ([expr.const]/3), the following is potentially-constant because the variable is a const-qualified integral type. const int ci...
73,731,493
73,731,571
Why does virtual not call the overridden function here?
#include <iostream> struct MemA { virtual void tellClass() { std::cout << "I am member of class A" << std::endl; } }; struct MemB : public MemA { void tellClass() { std::cout << "I am member of class B" << std::endl; } }; class A { MemA *current; public: A() : current(new MemA()) {} void getMemClass() { cu...
current in A is a different member from the current in B, i.e. there are two members A::current and B::current. B has both of them as member. The former is only hidden in as so far as naming current unqualified in the context of class B refers to B::current instead of A::current. In the context of class A (where you ar...
73,731,776
73,731,915
How to initialize the array-like member variable in the constructor?
How to initialize the array-like member variable? The visual studio code says: no matching function for call to 'Node::Node()' gcc line 12 col 9 const int N = 100; struct Node { int val, ch[2]; /** void init(int _val) { this->val = _val, this->ch[0] = this->ch[1] = 0; }*/ Node (int _val):...
The problem is that when you wrote tree[N] you're creating an array whose elements will be default constructed but since there is no default constructor for your class Node, we get the mentioned error. Also, Node doesn't have a default constructor because you've provided a converting constructor Node::Node(int) so that...
73,732,145
73,732,292
std::function template with multiple template parameters
When looking for documentation on std::function, I found several pages, that list two implementations of std::function for C++11: https://en.cppreference.com/w/cpp/utility/functional/function template< class > class function; /* undefined */ template< class R, class... Args > class function<R(Args...)>; https://w...
that list two implementations of std::function for C++11: No they don't. That isn't what they're showing at all. template< class > class function; /* undefined */ is the base template, which (as it says), is never defined. For example, std::function<int> would never make sense, so there is simply no template defined...
73,732,857
73,732,910
C++: 2D Dyanamic Arrays, outputting all values in one line
so I'm starting to write a program that multiplies two square matrices using dynamic 2D arrays. I'm just learning how dynamic arrays work, so I'm testing to make sure everything is storing properly. When I run my code, it outputs the two matrices on a single line each, rather than like a matrix with rows and columns. H...
Just add one more statement cout << endl; in your for loops like for (int I=0 ; I < n; I++ ) { for (int K=0 ; K < m; K++) cout << setw(4)<< C[I][K]; cout << endl; } cout << endl; for (int L=0 ; L < p; L++ ) { for (int Z=0 ; Z < q; Z++) cout << setw(4)<< D[L][Z]; cout << endl; } cout << endl;
73,733,203
73,777,523
How to read protobuf FileOptions in C++?
In the Google proto3 examples they show both global and nested custom options, including: extend google.protobuf.FileOptions { string my_file_option = 1001; } option (my_file_option) = "hello file!"; and extend google.protobuf.MessageOptions { optional string my_option = 51234; } message MyMessage { option (my_o...
To get the proto's options rather than a Message, you need to load the proto from the DescriptorPool // Create descriptor pool of all loaded protos google::protobuf::DescriptorPool descriptorPool(google::protobuf::DescriptorPool::generated_pool()); // Find specific proto file you want the options from const google::pro...
73,733,691
73,739,057
How to manually override the automatic quotation of strings
I am writing to a YAML file with jbeders/yaml-cpp and I am writing IP addresses to a file. When I write the wildcard IP "*" to the file, it automatically gets quoted (since '*' is a special character in YAML). But when I want to write the IP 10.0.1.1, it does not get quoted. This is how I assign the node for the asteri...
You should edit your question for conciseness, such as 'Using the yaml-cpp, how to serialize a map not quoting its keys but quoting its values?'. To the point, you should manually iterate a map alternating string formats like the following. yaml_out << YAML::BeginMap; for (auto p : ip_map) { yaml_out << p.first; ...
73,734,068
73,735,251
Compiler ignores my if statement in while(true)
here's my code for sending messages every 3 seconds for 10 times. but it ignores all of if statements in while(true) double current; double freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); QueryPerformanceCounter((LARGE_INTEGER*)&current); float totalTime = 0.f; float counter = 0.f; while (true) { double pre...
It is likely that the problem is due to deltaTime being significantly smaller than 3.f and 30.f. Since, unless either if branch is taken, the loop body doesn't do anything except measure a clock, the time between iterations is likely to be very small. Initially, this won't be a problem and deltaTime will be correctly a...
73,734,381
73,747,412
accessing class member regardless of it being a function or a data member
I want to write a generic accessor for a class member regardless whether it is a function or or a data member: #include <type_traits> namespace traits { template <typename T, typename = void> struct _name; template <typename T> struct _name<T, std::void_t<decltype(std::declval<T>().name)>> { ...
You seem to be reinventing std::invoke. This function embodies the definition of Callable concept, and that definition has two special cases: a pointer to data member is "callable" like a function taking the object as its single parameter: std::invoke(&C::dataMember, obj) is equivalent to obj.*dataMember a pointer to ...
73,734,573
73,734,888
Why can logical constness only be added to a std::span of const pointers?
Consider this code that attempts to create various std::span objects for a vector of raw pointers. #include <vector> #include <span> int main() { struct S {}; std::vector<S*> v; std::span<S*> span1{v}; std::span<S* const> span2{v}; std::span<const S* const> span3{v}; std::span<const S*> span4{v...
std::span<const S*> allows you to assign a const S* to an element. std::vector<S*> allows you to read an element of type S*. If std::span<const S*> were allowed to take a std::vector<S*>, then it would be possible to sneakily convert a const S* to a S*, by assigning the const S* to an element of the span and then read...
73,734,711
73,735,263
Isn't this code redundant taking into account C++ memory management?
I'm a C++ newbie, so I don't truly understand how C++ manages memory. Isn't this code redundant? void processData() { FILE* savedDataFile; char* savedData; try { savedDataFile = fopen("../savedData.dump", "r"); if (!savedDataFile) throw 0; savedData = (char*)malloc(0xf000...
Any FILE* pointer that is fopen()'d must be fclose()'d. Any dynamic memory that is malloc()'d must be free()'d. So yes, in general, you need those calls, BUT only when used correctly! Which this code is not doing. If fopen() fails, an int is thrown, and then the exception handler is exhibiting all kinds of bad/illegal...
73,735,234
73,736,741
I have written this code to convert an infix expression to a postfix expression using Stacks in CPP
#include<bits/stdc++.h> using namespace std; int prec(char c){ if(c=='^'){ return 3; }else if(c=='*' || c=='/'){ return 2; }else if(c=='+' || c=='-'){ return 1; } return -1; } string infixToPostfix(string ); int main(){ string s = "(a-b/c)*(a/k-l)"; cout<<infixTo...
Define two precedence tables, called outstack for operator when they are outside the stack and instack for operator when they are inside the stack. If any operator is left to right assosiative increase the precedence from outstack to instack. If it is right to left decrease the precedence. Op outstack pre instack p...
73,735,387
73,735,533
I am not able to print the output on the screen. I am using cppreference side (GCC 12.1 (c++20 )) compiler
I am not able to print the output on the screen.I am using cppreference side (GCC 12.1 (c++20 )) compiler, Is there any deadlock situation in below example. Is there any online compiler i can use for trying this type of examples #include <iostream> #include <semaphore> #include <thread> #include <vector> std::vector<...
There is no deadlock, but you have a race condition: In completeWork, prepareSignal.acquire does not block the execution (Based on c++ documentation: "When the counter is zero, acquire() blocks until the counter is incremented"). In this case, the counter is set to 2, and there is no other acquire. So the program may r...
73,735,733
73,735,970
std::from_chars overload for wchar_t?
Is there any reason why std::from_chars doesn't have an overload for wchar_t? Currently, there are only four overloads one of them being: constexpr std::from_chars_result from_chars( const char* first, const char* last, /*see below*/& value, int base = 10 ); So what is the ...
The from/to_chars series of functions are for elementary string conversions. These are the most elemental of numeric conversions. As such, they only support the most basic encoding: your system's native narrow character set (usually Unicode codepoints less than 128 encoded as UTF-8 or ASCII). If you have text in some o...
73,736,040
73,736,061
multiple definition of... + undefined reference to... the same function
my programm has various errors that i don't quite understand. in geraet.cpp i want to override the method schalten() from elektronik.cpp, but after compiling each component i cant link them (g++ -o main main.o elektronik.o geraet.o) with these errors: /usr/bin/ld: geraet.o: in function `schalten()': geraet.cpp:(.text+0...
When you define a function in cpp, you need to use the whole (prefixed) name, e.g.: #include "elektronik.h" bool Elektronik::schalten() { return false; } Same for Geraet. This is because, without prefix, the compiler will consider it to be a free function (in the given namespace).
73,736,064
73,745,367
Get a pixel color on directx11 from the screen
I need to do function like: RGBTRIPLE GetPixelColor(int x, int y) to get a color on a single pixel on directx 11 from the actual frame in my screen For the moment I have this code: //For each Call to Present() do the following: //Get Device ID3D11Device* device; HRESULT gd = pSwapChain->GetDevice(__uuidof(ID3D11Devic...
There are several ways to do that, first one, you read the entire texture back to memory and pick your pixel from there (Pseudo code) : create another ID3D11Texture2D same size/format as backbufferTex (with no bind flags, read cpu access and staging usage. Use CopyResource to copy your back buffer to the staging textu...
73,736,831
73,741,695
C++ spdlog use variables
I'm new to spdlog and following a tutorial which looks like this: Log.h #pragma once #include "spdlog/spdlog.h" #include "spdlog/fmt/ostr.h" namespace Engine{ class Log{ public: static void init(); inline static std::shared_ptr<spdlog::logger>& GetCoreLoger() { return s_CoreLogger; } i...
According to the spdlog's wiki pages, your formatting syntax is incorrect. For formatting a variable, a placeholder {} is required. Try this: int test_var = 12; INFO("The variable is: {}{}", test_var, "."); // ^^^^ adding these placeholders
73,736,886
73,737,080
How to setup/fill a vector of structures c++
I have a struct and some elements in it, I am trying to create a vector of structs and fill it up but tbh im pulling my hair out cause I have no idea what I am doing. Could someone please help me with how I should set this up? ''' #include <iostream> #include <string> #include <vector> using namespace std; //define s...
You have two mistakes, first one your animalS struct doesn't have a constructor, you should add constructor like this: animalS(const std::string &animalType, int animalCount, bool animalEndangered) : animalType(animalType) , animalCount(animalCount) , animalEndangered(animalEndangered) {} And use push_back() l...
73,736,899
73,737,056
Internally sorting a class that inherits from a vector of pointers to a user defined object (C++)
So I defined a class on C++ that inherits from a vector of pointers: class SuperBinList : public std::vector<SuperBin*>{ public: SuperBinList(); SuperBinList(const std::vector<SuperBin*>& superBinList); virtual ~SuperBinList(); SuperBinList& operator += (SuperBin* superBin); SuperBinList& operator += (const...
You have your SuperBinList::sortBySoverB() function defined as const, which means it is not allowed to modify SuperBinList, and this will have the type const SuperBinList *, rather than SuperBinList * Similarly, your lambda is define with const pointers const SuperBin* lhs, meaning you can only call const functions. Ch...
73,737,396
73,737,456
Making the user give a boolean input with while loop
I have just started learning C++ and trying to learn the syntax. #include <iostream> #include <limits> using namespace std; int main(){ bool answer; cout << "Did you enjoy testing this program? (1 for yes, 0 for no) "; cin >> answer; while (!(cin >> answer)) { cout << "Invalid value!\n"; ...
The cin >> answer; statement above the loop, and the cin >> answer; statement at the end of the loop body, both need to be removed. You are prompting the user to enter a value, then you read in that value and ignore it, and then you wait for the user to enter in another value, even though you didn't prompt the user to ...
73,737,420
73,738,528
How can I use boost accumulator quantile_probability inside a class member initialization?
Boost Accumulator has an unfortunate quirk in which the api interface behaves differently when used inside of a class. I am trying to use Boost Accumulator quantile_probability inside of a class but I can't figure out how to make it work. This problem is similar to this issue: Can boost accumulators be used as class me...
The open bracket in accumulator_t myAcc( gets parsed as a member function, in which case this is defining a function taking a variable of type ba::qunatile_probability. But that isn't a type, so it fails. You need to write your initializer with = or {, or write it in a constructor's initializer list struct Foo { //...
73,737,765
73,737,898
c++ - passing standard container as a template template parameter
So, I need to make a mixin class that would encapsulate children of some derived class. The derived class should inherit from the mixin while providing a container template as a template template argument for the mixin. The desired code is somewhat like that: /*template definition*/ template<template<typename T, typena...
You pass a type, std::vector<int>, instead of a template, std::vector. You need to accept the template template parameters too. template<typename T, typename A> does not make the template template use T and A. They are just for documentation and can be removed. Example: template <template <class, class> class C, clas...
73,738,257
73,738,862
Calling open() on a Unix domain socket failed with error "No such device or address"
I'm trying to communicate between NodeJS and C program using named pipes in linux. My server program has written in NodeJS: 'use strict'; const net = require('net'); const pipename = '/tmp/pipe1'; const fs = require('fs'); let server = net.createServer(function(socket){ console.log('A new connection'); ...
The /tmp/pipe1 is not a pipe file. It's a socket file. That's what the leading s means in srwxr-xr-x. And Bash's redirection like > does not support socket files. You need to use socket API to open the file. With strace (e.g. strace bash -c 'echo > /tmp/sockfile') we can see: ... openat(AT_FDCWD, "/tmp/sockfile", ...)...
73,738,617
73,906,883
GMP detect float exponent overflow when initializing
I am currently programming on 64-bit Fedora 36, and I realized that GMP floating point numbers have limitations on the exponent size: https://gmplib.org/manual/Floating_002dpoint-Functions The exponent of each float has fixed precision, one machine word on most systems. In the current implementation the exponent is a ...
This is not a bug. This is documented in the GMP manual: The 'mpf' functions and variables have no special notion of infinity or not-a-number, and applications must take care not to overflow the exponent or results will be unpredictable. Basically, overflow on mpf numbers is undefined behavior. If you want well-defin...
73,738,622
73,778,779
Error compiling Google Protocol Buffer Output (C++)
Update #2: Issue closed, but curious about all the error messages. I got it to compile after including #define PROTOBUF_USE_DLLS. After the build, the Error List still shows 398 errors and the output window lists a lot of warnings, but it still compiled. Why is that? I downloaded the Google Protocol Buffer source and...
The errors turned out to be Visual Studio Intellisense errors and not "actual" compile errors. For the one linking error, the issue was resolved by adding #define PROTOBUF_USE_DLLS to the protoc-generated C++ output.
73,738,740
73,738,885
destructor is called twice for variant-based implementation
I have a variadic variant_callable class object that I want to use for a runtime polymorphism. Inside it uses a visitor pattern with std::variant. However, I came by a rather strange behavior, that is object's destructor is called twice!. #include <utility> #include <variant> #include <tuple> namespace detail { te...
variadic_callable's constructor is being passed an object of type callable. This is a temporary object that cannot be the same object as the one stored in the std::variant (no matter how it is passed). The callable inside the std::variant must therefore be move-constructed from the passed temporary object. Both of thes...
73,738,976
73,739,041
How to keep good code practices in a specific case (c++)
So, basically, i have a struct, let's say struct someStruct {int x; int y;}; (only as a example), and a class. For my specific situation, x must be able to be changed from any scope, but y should only be changed from inside the class. I have no idea of what I'm supposed to do here. I have thought about making y a priva...
Make B private and declare Renderer as friend, e.g.: struct Triangle { friend class Renderer; // A, B, C, position, transform and material should be changed from any scope (don't bother with what they mean, it's not important for the purposes of this question) vec2 A; private: vec2 B; public...
73,739,507
73,739,755
How do you handle indivisible vector lengths with SIMD intrinsics, array not a multiple of vector width?
I am currently learning how to work with SIMD intrinsics. I know that an AVX 256-bit vector can contain four doubles, eight floats, or eight 32-bit integers. How do we use AVX to process arrays that aren't a multiple of these numbers. For example, how would you add two std::vectors of 53 integers each? Would we slice a...
Would we slice as many of the vector that would fit in the SIMD vector and just manually process the remainder? Is there a better way to do this? Pretty much this. A basic example that processes all number in batches of 8, and uses mask load/maskstore to handle the remainder. void add(int* const r, const int* const a...
73,740,325
73,740,707
How can I measure the speed difference of for loop?
I am curious about the items below in for loop. for(auto) vs for(auto &) Separating the for loop for(auto &) vs for(const auto &) for(int : list) vs for(auto : list) [list is integer vector] So, I wrote the below code for testing in the C++17 version. It looks like seems difference in CMake debug mode(without opt...
An empty loop can optimize away, so your compiler correctly does that. But benchmarking with optimization disabled is not meaningful. C++ requires optimization to get the performance we expect for production use (especially with template library functions), and optimization or not isn't a constant factor speedup; it ...
73,740,361
73,740,488
Getting Unexpected output in C++
I am trying to create a function which creates an array and return a pointer of the array: Here's my code: #include<iostream> using namespace std; int* example() { int arr[] = {1,2,3}; int *a = arr; return a; } int main() { int *a = example(); cout << *a << endl; cout << *(a+1) << endl; ...
The array arr is declared local to the function. As a result its lifetime ends when the function exits. We call this automatic lifetime. Returning a pointer to this memory invokes undefined behavior. The code might work the way you expect, or it might not. To work around this, you need a lifetime that is not automatic,...
73,740,441
73,740,504
How to get min and max value from a linked list using recursive function?
I am started learning data structure. Currently I am learning linked list. I have crated a linked list. I want to get the minimum value and the maximum value from the list using recursive function. I can do that using loop but I want to do that recursively. I have written functions for getting minimum and maximum value...
The obvious problem is that you call your function recursively, but ignore the return value. This means that only the first item in the list is considered. int getMin(node *currentNode) { int minValue = INT_MAX; if (currentNode != NULL) { minValue = minValue < currentNode->data ? minValue : currentNode->data; ...
73,740,530
73,740,594
Stroustrup reason for using auto when defining a variable
I am reading Bjarne Stroustrup "The C++ programming language" book, and it is mentioned that one of the reasons for using auto in a variable definition is: The definition is in a large scope where we want to make the type clearly visible to readers of our code. What is the meaning of large scope here? and anyone has ...
You took only part of the quote from the book. The entire quote is: We use auto where we don’t have a specific reason to mention the type explicitly. ‘‘Specific reasons’’ include: The definition is in a large scope where we want to make the type clearly visible to readers of our code. We want to be explicit about a v...
73,740,861
73,741,200
Dynamic allocation and pagination
I'm trying to monitor (with the system monitor) the total memory dynamically allocated by a snipped (for whatever reasons: I know, it sounds academic). Here's what I use (I know I'm not deallocating, and that the code is ugly). #include <iostream> #include <thread> #include <cstdint> using namespace std; int main() {...
Your code is not using the allocated memory. The compiler is going to notice that and will simply optimize the allocation away. If you want to observe the memory being allocated use it in such a way that it is not trivial to perform the same action without the allocation. What exactly that means will depend on how good...
73,743,062
73,744,017
how to provide a default value for a template conditional type?
All I am writing a trimStart fucntion with c++ template like the following: template<typename T> static T trimStart(T source, std::conditional<isWide<T>(), const wchar_t*, const char*>::type trimChars = " \t\n\r\v\f")) { .... } now I like to provide a default value " \t\n\r\v\f" or L" \t\n\r\v\f" according the ty...
I rearranged your code to this: #include <type_traits> #include <iostream> template <typename T> struct is_foo : std::false_type {}; struct foo{ int value;}; template <> struct is_foo<foo> : std::true_type {}; struct bar{}; template <typename T> void func(T t, std::conditional_t<is_foo<T>::value,int,double> x = ???...
73,743,356
73,749,166
wxStyledTextCtrl - Size of AutoComp
I was just wondering if it is possible to find the size (in pixels) of the autocompletion control shown by the wxStyledTextCtrl. My goal is to show a help window associated with the entry when a selection happens. Therefore, I need the location and also the width of the autocompletion control. It seems location can be ...
There is no way to get this information from the styled text control because the autocomp window is completely managed by Scintilla. And unfortunately, Scintilla doesn't make any methods available for getting this info. As a hack-around, the popup is currently implemented as a child window of the styled text control. ...
73,743,941
73,744,655
Non type template parameter of type std::string& compiles in gcc but not in clang
I am learning C++ using the books listed here. In particular, I learnt that we cannot use std::string as a non-type template parameter. Now, to further clear my concept of the subject I tried the following example which compiles in gcc and msvc but not in clang. Demo std::string nameOk[] = {"name1", "name2"}; template<...
Clang is complaining that your template argument is a subobject. (If you make the argument a complete string object, it works.) This behavior is based on an earlier restriction in the standard at [temp.arg.nontype], which read For a non-type template-parameter of reference or pointer type, the value of the constant ex...
73,744,258
73,746,967
asio, shared data, Active Object vs mutexes
I want to understand what is true-asio way to use shared data? reading the asio and the beast examples, the only example of using shared data is http_crawl.cpp. (perhaps I missed something) in that example the shared object is only used to collect statistics for sessions, that is the sessions do not read that object's ...
Is it implied that interaction with shared data in asio-style is an Active Object? i.e. should mutexes be avoided? Starting at the end, yes mutexes should be avoided. This is because all service handlers (initiations and completions) will be executed on the service thread(s) which means that blocking in a handler wil...
73,745,547
73,746,053
Cmake: How to statically link packages to shared library?
I want to create a .dll library with all its dependencies packed inside the .dll. However, there seems to be no easy way to achieve that with Cmake. My setup: cmake_minimum_required(VERSION 3.0.0) project(Main VERSION 0.1.0) add_library(Main SHARED Main.cpp) find_package(libzippp REQUIRED) target_link_libraries(Main...
Of course you can't pack one DLL into another. You have to make libzippp a static library in the first place. To do this, build libzippp with BUILD_SHARED_LIBS set to NO at the CMake command line. Then libzippp::libzippp will be a static library when you go to find_package it. This is easy enough to show steps for: $ g...
73,745,878
73,746,049
I am trying to reverse an array using loop in cpp ? but don't know what the problem is?
#include <iostream> using namespace std; int* reverse(int arr[],int n){ int rev[100]; int j =0; for(int i=n-1;i>=0;i--){ rev[j]=arr[i]; j++; } return rev; } int main() { int n; cin>>n; int arr[100]; for(int i=0;i<n;i++){ cin>>arr[i]; } ...
Your rev temporary resides in automatic storage. It means that the object will be gone after the function returns. While C++ allows you to decay rev to an int* and then return said pointer, it does not mean that this returns the object itself. You merely get a pointer to an already destroyed object. Not very useful. In...
73,746,134
73,755,783
Is std::format going to work with things like ICU UnicodeString?
Rather than a long preamble, here is my core question, up front. The paragraphs below explain in more detail. Is there a template parameter in std::format (or fmt) that will allow me to format into ICU UnicodeStrings?, or perhaps into something like char16_t[] or std::basic_string<char16_t>, while using a unicode libra...
{fmt} doesn't support ICU UnicodeString directly but you can easily write your own formatting function that does. For example: #include <fmt/xchar.h> #include <unistr.h> template <typename... T> auto format(fmt::wformat_string<T...> fmt, T&&... args) -> UnicodeString { auto s = fmt::format(fmt, std::forward<T>(args)...
73,746,195
73,770,353
Building a BSON filter from raw query string
Is it possible to create a collection filter from a raw query string? If so, how? I'm using the mongocxx driver and want to use some tested queries from the mongo shell instead of building them inconveniently with that BSONCXX streambuilder. But I can not find any examples. I tried to convert from_json(), but this thro...
Actually bsoncxx::from_json("{ \"val\": { \"$gt\": 0, \"$lt\": 9}}"); was not the issue. The transformation from std::string to bsoncxx::view was. Not 100% sure where the reason for the crash was, but this does the trick for me. Solution: std::string query( R"( { "val": { "$gt": 0, "$lt": 9}} )"); collection.find(bson...
73,746,392
73,746,635
C++: How to make program differentiate between multiplication and pointers, not accepting operations
So I'm writing a program for an assignment that multiplies two matrices using dynamic arrays only. I'm running into two problems. I can't figure out how to add specific values from two different arrays and storing that in a third array: bag = F[add] + F[add+1]; //line 73 and I also can't figure out how to multiply spe...
F[y] = (C[cnt1][cnt2]) * (D[cnt2][cnt1]); //line 68 C is int **C D is int **D F is int **F So, the expression on the right side is an int. F[y], though, is an int pointer. So, you either meant: *(F[y]) = ... or F[y][something] = ... There's no magic, you just need to carefully look at every type and every operation. W...
73,747,119
73,748,158
What is the usecase of calling hana::is_valid with a nullary function?
Boost.Hana offers boost::hana::is_valid to check whether a SFINAE-friendly expression is valid. You can use it like this struct Person { std::string name; }; auto has_name = hana::is_valid([](auto&& p) -> decltype((void)p.name) { }); Person joe{"Joe"}; static_assert(has_name(joe), ""); static_assert...
Use case is that of checking that f is actually nullary, e.g if constexpr (is_valid(f)()) { f(); // Treat f as a "no args function" } else if constexpr (is_valid(f, arg1)) { f(arg1); } what the documentation says is that unlike functions of non zero arity, the is_valid predicate can only be invoked in the form: is...
73,747,877
73,748,082
Is what I'm doing an Insertion sort, I think the logic is correct but unconventional?
This code is supposed to be an Insertion sort but is it implemented as such? I'm lost. The first loop goes through the array and checks if the next element is smaller than the current element. The nested loop inserts the next element(j) correctly in its place in the sorted portion of the array. #include <iostream> usi...
This for loop for (int j = i - 1; newI < array1[j]; j--) { if (j < 0) { break; } array1[j + 1] = array1[j]; array1[j] = newI; } can invoke undefined behavior when j is equal to -1 due to this expression in the condition of the for loop newI < array1[...
73,748,757
73,748,893
How to delete a specific value from a doubly linked list?
I was given a task with a DOUBLY linked list to delete a specific number from the list. My code is giving an Access Violation error. Even after multiple dry runs, I can't figure out what is wrong. The task basically is to create a search function which finds a specific number in the linked list, and a deletion function...
For starters, the search() function is being called twice within the delspval() function: if(search(val)==NULL){ and temp=search(val); that makes the delspval() function less efficient. This statement: temp->next->prev=temp->next; does not make sense. The delspval() function can be defined in the following way. I su...
73,748,978
73,749,110
Compiler disagreement on using std::vector in constexpr context
The following code compiles with gcc and MSVC, but not with clang. #include <array> #include <vector> consteval void foo(auto func) { std::array<int, func().size()> f; } int main() { foo([](){ return std::vector<int>{1,2,3,4,5};}); } Compiler Explorer If I understand the rules of dynamic memory allocation in...
It is just a bug in Clang. It seems to not consider the deallocations happening at the end of expressions as template arguments as part of the constant (full-)expression. When using a constexpr variable to store the size instead of a template argument, Clang accepts it as well. A simplified test case (not depending on ...
73,749,071
73,749,072
What is the advantage of Hana's type_c-and-declval dance when querying whether a SFINAE-friendly expression is valid?
On the one hand, the function boost::hana::is_valid is presented as follows Checks whether a SFINAE-friendly expression is valid. Given a SFINAE-friendly function, is_valid returns whether the function call is valid with the given arguments. Specifically, given a function f and arguments args..., is_valid(f, args...) ...
While writing the question, I've searched more an more (to put relevant links in it, mainly), and I eventually did find the answer in the documentation of Boost.Hana at Boost.Hana > User Manual > Introspection > Checking expression validity > Non-static members: the use of hana::type_c to wrap a type T in an object (no...
73,749,074
73,749,104
trouble figuring out for-each iterator interface in C++ with MSVC C++17
I've had trouble compiling iterator logic in MSVC. It results in a compilation error when trying to express an iteration using the short-hand for (type element: container) { ... } It could be duplicate but I am unaware what keywords to search for.. Using MSVC++ 2019, C++ 17 compilation mode /// iterator template <typen...
Your iter2 type does not satisfy the requirements of an input iterator, as it does not implement operator*, which a range-for loop uses to access the elements that are being iterated. You need to add this to iter2: T& operator*() { return start[index]; } And then consider removing operator T&(), as that is not an oper...
73,749,178
73,749,534
How do move-only iterator implement postfix ++ operator?
What is the right way to implement an iterator that iterates over a Recordset provided below in C++ style? class Recordset { public: Recordset(const Recordset&) = delete; Recordset& operator = (const Recordset&) = delete; Recordset(Recordset&& other) noexcept = default; Recordset& operator = (Record...
Single pass move-only input iterators (A c++20 std::input_iterator) are only required to be weakly incremental, where (void) ++i has the same effect as (void) i++. You can simply have void operator++(int) { ++*this; }. Older requirements for iterators (Cpp17InputIterator) requires iterators to be copyable, and require ...
73,749,515
73,751,194
How to copy a string to a unsigned char* on a struct?
a.h struct loader_struct { unsigned char* loader_x64; }; extern loader_struct* g; a.cpp #include "a.h" loader_struct g_startup; loader_struct* g = &g_startup; b.cpp #include "a.h" int _tmain(int argc, _TCHAR* argv[]) { std::string mdata = "abcdefg"; g->loader_x64 = new unsigned char[mdata.length()]; ...
You are getting "rubbish" because whatever code is reading from loader_x64 is expecting it to be null-terminated, but you are not actually null-terminating it, so the reader reaches past the end of the buffer, which is undefined behavior. You need to null-terminate the loader_x64 buffer, eg: #include "a.h" int _tmain(...
73,749,527
73,749,766
Initialization order of static inline member variables in class templates (C++17)
I am working on a code where I need a static member variable of some class to be initialized using a static variable of an instance of a class template. I know about the static initialization order fiasco and found several discussions on that issue but none of them really helped me with my problem. I don't even know wh...
Dynamic initialization of static data members of class template specializations (if they are not explicitly specialized) are completely unordered (indeterminately-sequenced) with any other dynamic initialization. It doesn't matter whether the member is inline or not, it doesn't matter whether the other dynamic initiali...
73,749,575
73,749,622
Why doesn't decltype(*this)::value_type compile?
Why doesn't decltype(*this) compile? It shows an error message: error: 'value_type' is not a member of 'const Foo<char>&' So what exactly is the reason that decltype( *this )::value_type does not compile in the below program: #include <iostream> #include <vector> #include <type_traits> template <typename charT> stru...
The result of applying unary operator* to a pointer is a reference (lvalue ref) to the pointed at value, not a copy of the pointed at value. So decltype(*this) (or decltype(*foo) for any pointer type) will always be a reference type. There's nothing special about this.
73,750,633
73,750,708
How do I define a function that takes a variadic class template?
I am trying to define a simple variant-based Result type alias, sort of like a poor man's rust-like Result type : namespace detail { template <typename SuccessType, typename... ErrorTypes> struct Result { using type = std::variant<SuccessType, ErrorTypes...>; }; template <typename... ErrorTypes> struct Result<void, ...
After expanding the Result_t alias in the function parameter, it looks like this: template <typename SuccessType, typename... ErrorTypes> bool Ok(const detail::Result<SuccessType, ErrorTypes...>::type& r) { return r.index() == 0; } The problematic part here is that the template parameters are left of the name resolu...
73,751,476
73,751,613
capture compiling error using python subprocess
Using Python to script running GoogleTest with subprocess. My code looks like import subprocess import logging logging.basicConfig(filename="gtest.log",level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s') output = subprocess.check_output("g++ test.cpp -lgtest -lgtest_main -lpthread -I <some header file...
Refer to the comment via @Miles Budnek: g++ prints errors to stderr, so you need to capture that as well as stdout. Add stderr=subprocess.STDOUT to your call to capture it as well.
73,751,891
73,751,909
Public class member not visible when CRTP derived type is a template class
The below code doesn't compile. I want Derived<T> to access m_vec member of Base. However, because Derived<T> is templated, it implemented CRTP via : public Base<Derived<T>> and m_vec is not visible. If I change Derived<T> to just Derived, m_vec becomes visible. Why is this/is there a workaround? #include <vector> tem...
Access the member using this->m_vec.clear(); That should compile.
73,752,011
73,752,467
How to remove button in IMGui and prevent settings window from closing?
I was using docking tree code of IMGui and I created a Application.cpp and Application.h in example_win32_directx9. I am using release and x64 to compile. I have set subsystem in system in Linker to Windows. Code of Application.cpp is: #include "Application.h" #include "imgui.h" namespace MyApp { void RenderUI()...
To fix it, bools need to be declared out of function. After editing it, the fixed Application.cpp with more functions was: #include "Application.h" #include "imgui.h" namespace MyApp { bool settings = false; bool p_open = true; bool Decimal_places = false; void RenderUI() { ImGui::Begin("...
73,752,168
73,753,282
Get USB detail info from PDEV_BROADCAST_DEVICEINTERFACE in Windows
case WM_DEVICECHANGE: { PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lparam; PDEV_BROADCAST_DEVICEINTERFACE lpdbv = (PDEV_BROADCAST_DEVICEINTERFACE)lpdb; std::string path; if (lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { path = std::string(lpdbv->dbcc_name); switch ...
The SetupAPI, specifically SetupDiGetClassDevs+SetupDiEnumDeviceInfo+SetupDiGetDeviceInstanceId+SetupDiGetDeviceRegistryProperty should get you started. More information and a sample can be found here...
73,752,176
73,765,914
"Undefined symbols for architecture arm64" building basic SFML project on M1 mac with g++-12
i've been having some trouble trying to compile a very basic SFML project on an M1 mac. the exact error i've been getting is as follows: Undefined symbols for architecture arm64: "__ZN2sf6StringC1EPKcRKSt6locale", referenced from: _main in cczblZnn.o ld: symbol(s) not found for architecture arm64 collect2: error: ld r...
fixed by scrubbing all references to SFML from my computer, installing it again with brew, and then using clang++ instead of compiling with g++ :)
73,752,190
73,752,556
how to update the elements of an array with the sum of previous two and next two elements?
how to update the elements of an array with the sum of previous two and next two elements ? given that for the first element the sum would be the sum of next two elements as there is no previous element and same is the case for last element. for example given an array {1,2,3} the array will be updated as {5,4,3} expla...
You need to create a temporary array to store the initial value of arr to prevent calculating the new value of arr[i] using new values (post-update) of arr[i - 1], arr[i - 2], etc. std::vector<int> initial_value(arr, arr + n); for (int i = 0; i < n; ++i) { int updated_value = 0; if (i - 2 >= 0) { updat...
73,752,533
73,752,699
Taking in a 2D vector of a string from a user but ends up getting segmentation fault
I am trying to input a 2d vector of string "t" times and make a grid of 2 * 2 size "t" times using C++ and the inputs can be integers 0 to 8 (inclusive) and ".", so i tried using a 2d vector of string but I am getting segmentation fault when accessing any element of a row > 0. I think it's because cin is buffered. Can ...
No, nothing to do with cin being buffered. The error is here temp.clear(); That line changes the size of temp to be zero, so on the next input cin >> temp[j]; you have a vector subscript error because temp has zero size. Just remove the line temp.clear(); and your code will work.
73,752,664
73,842,198
GLFW closing window automatically
I am trying to create a simple program using OpenGL I have set up some key callbacks which is triggered everytime I run the code The main loop is while (glfwWindowShouldClose(window) == 0) { renderGL(); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; and the key_callback function ha...
https://github.com/microsoft/wslg/issues/207 This is a known issue in WSL in which the buffer from the previous commands is called back to be used when the program runs again
73,752,693
73,752,802
Any way to prevent/limit user input
I am creating a simple number memorising game which can be played using command lines/console. Each round there will be one more digit of number you need to memorise. Then you have to enter it, if it's correct you get some points and the game continues. There is a problem where the use can input/type when the number y...
Since C++ cannot know, on which platform or terminal it is running, it cannot have native support for any potential terminal. Hence, you will not find such a functionality in pure C++. Your usage of function usleep suggests that you are maybe working on a Linux compatible platform. Here, a very often used solution is t...