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,469,108
73,469,261
What happens when we store a "char type" value in an "integer type" variable using std::cin?
int i; std::cin >> i; // i = 'a' What is the reaction of std::cin when we try to do this? As we know when the std::cin gets a value, it converts it into ASCII or something other and then stores it in a variable so what is the reaction of std::cin on this?
No it doesn't store the ASCII value of the character you are entering into i. Instead, the stream will put a fail flag for the input stream meaning the reading of integer resulted in a failure. Here is the code to demonstrate that. int i; cout << cin.fail(); // 0 as cin doesn't failed yet cin >> i; //...
73,469,846
73,486,624
Is it possible to let DCMTK's writeJson() write tag names?
I am using the DCMTK library in my program, which among others writes a JSON. With the DcmDataset::writeJson() function I can put the whole header in the JSON in one call, which is very handy, but the tags are listed by offset not name. This is the same as with the command-line program dcm2json, which writes a JSON fil...
The output format of dcm2json is defined by the DICOM standard (see PS3.18 Chapter F), so there is no way to add the Attribute Names/Keywords. However, you might want to try dcm2xml, which supports both a DCMTK-specific output format and the Native DICOM Model (see PS3.19 Chapter A.1). Both formats make use of the offi...
73,470,321
73,471,844
Passing virtual function pointer as argument of a Base Class function
First I have created a custom type as follows: typedef void* (*FUNCPTR)(void*); Then, I created a Base Class called P. class P { ... public: virtual void job() = 0; // Pure virtual function void start() { create((FUNCPTR) &P::job); } ... }; (create method signature accepts void *(*__star...
Now that it's been clarified that create is infact pthread_create, you can have class P { static void* do_job(void* self) { static_cast<P*>(self)->job(); return nullptr; } pthread_t thread; public: virtual void job() = 0; void start() ...
73,470,481
73,471,260
Working with MacOS UserDefaults using C++?
I am working on a C++ project that needs to save data to a persistent storage on the operating system. For MacOS, I want to save the data to UserDefaults - is there a C++ library to manipulate them? Similar to NSUserDefaults in Objective-C.
There are plain C functions in CoreFoundation which you can use directly, the CFPreference* family, but they might be rather awkward to use. See for example CFPreferencesSetAppValue and the CFPreferenceCopy* and CFPreferenceGet* functions. You're going to have to convert C++ from/to CoreFoundation data types. You proba...
73,470,947
73,471,654
Why does sending in argument as lambda function not work while sending it as normal function pointer works
I have been working on libcurl library and there I need to provide the API with a callback function of how it should handle the recieved data. I tried providing it with this callback function as a lambda and it gave me Access violation error, while when I give the same function as a function pointer after defining the ...
Edit Major props to @user17732522 for reminding me you can get the same effect without all the drama by simply using + as the prefix to your lambda. Way too late for me to be authoring reasonable answers. SryI totally spaced that. Original The curl_easy_setopt takes a variable argument stack, and peels them apart to th...
73,471,025
73,471,133
How to call proper assignment operator of custom class inside std::variant
I have the following class: class StackStringHolder { public: StackStringHolder& operator=(const std::string& str) { str_ = str; return *this; } StackStringHolder& operator=(std::string&& str) { str_ = std::move(str); return *this; } const std::string& get() c...
The Cause of the Problem: Your var can hold either an int or a StackStringHolder, so you cannot trivially assign it with a std::string. Solution: You can however add a converting constructor to your class StackStringHolder which accepts a std::string. Then it can be used to convert str to StackStringHolder and assign i...
73,471,450
73,471,786
Boost asio C++ 20 Coroutines: co_spawn a coroutine with a by-reference parameter unexpected result
In the following code, the parameter of the session coroutine is passed by reference. #include <boost/asio.hpp> #include <iostream> boost::asio::awaitable<void> session(const std::string& name) { std::cout << "Starting " << name << std::endl; auto executor = co_await boost::asio::this_coro::executor; } int ma...
You can think of the coroutine state as containing what would be on the function call stack (which is what makes the function resumable): cppreference When a coroutine begins execution, it performs the following: allocates the coroutine state object using operator new (see below) copies all function parameters to the...
73,471,717
73,474,251
Draw a rectangle with DX11
I need to draw a simple rectangle (not a filled box) with directx 11. I have found this code: const float x = 0.1; const float y = 0.1; const float height = 0.9; const float width = 0.9; VERTEX OurVertices[] = { { x, y, 0, col }, { x + width, y, 0, col }, { x, y + hei...
You have 6 vertices defined for a rectangle, which means you want to use TriangleList topology and not TriangleStrip topology.
73,472,347
73,472,437
Should I always use the new operator in C++ instead of the malloc function?
struct A { string st; }; int main() { A *a = (A *)malloc(sizeof(A)); a->st = "print"; cout << a->st; return 0; } When I use this way and it compiled successfully, but after that in runtime I got exception. So, I figure out one thing is A *a = new A; instead of A *a = (A *)malloc(sizeof(A));. Which way is better...
malloc alone is outright wrong. malloc allocates memory, it does not create objects. new allocates memory and creates an object by calling the constructor. The "better" way is to not use either of the two when there is no reason to use them. int main() { A a; a.st = "print"; cout << a.st; } A has only a singl...
73,472,756
73,472,948
std::array nested initializer
Why does this not compile #include <vector> #include <array> std::array<std::vector<const char*>, 2> s = { {"abc", "def"}, {"ghi"} }; but this does #include <vector> #include <array> std::array<std::vector<const char*>, 2> s = { std::vector{"abc", "def"}, {"ghi"} }; And if for whatever reason the std::vecto...
You need one extra set of { ... }: std::array<std::vector<const char*>, 2> s = { // #1 { // #2 {"abc", "def"}, // #3 {"ghi"} // #4 } }; An attempt at describing why: The inner initializer lists (#3 and ...
73,472,780
73,480,445
How to use string variables in attributes
In GCC and Clang, we can pass an integer variable into an attribute. constexpr auto SIZE = 16; int a [[gnu::vector_size(SIZE)]]; This is particularly useful when we write templates. template<size_t N> struct Vec { int inner [[gnu::vector_size(N)]]; }; However, if the attribute requires a string, I cannot find a ...
Standard attributes that take strings, like [[depecrated("reason")]], take a string literal, and not a variable or other expressions. This is like the message in a static_assert declaration. Looking at the gcc documentation for gcc-style __attribute__ specifiers https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html#...
73,472,985
73,473,108
Return statement not working in the linear search algorithm
This is a linear search algorithm and I am a newbie programmer....Why is the "return i" statement not returning i (printing it on console)?? Is it because the computer considers this as "end the program successfully" because the value of i > 0 (I mean is it acting like "return 0" statement??) how to solve this issue?? ...
Why is the "return i" statement not returning i (printing it on console)?? Thats a misunderstanding common among beginners. Returning something from a function and printing something to the console are two different things. Not every value you return from a function will be displayed on the console. If you use other ...
73,473,032
73,473,263
How to refer to the enclosing class member variables from inside of a nested class instance?
As a class member of some class A, I would like to maintain an std::set storing Bs. The set uses a custom comparison object which needs to read a non-static class member, m_t in the example code below, to perform its comparison. Example code: class B { ... }; class A { struct Comp { bool operator()(B b1, B...
Comp is just a C++ class, so you can complement it with any data as needed. E.g. a pointer to the enclosing class instance: struct A { struct Comp { A *host; bool operator()(B b1, B b2) const { std::cout << host->m_t << std::endl; // ...m_t is accessible here ...
73,473,132
73,473,197
308 Status code when making http request with httplib cpp
I am trying to make an HTTP request with httplib cpp to the following endpoint: http://api.publicapis.org/entries. I'm using the following code: httplib::Client cli("http://api.publicapis.org"); if (auto res = cli.Get("/entries")) { if (res->status == 200) { std::cout << res->body << std::endl; } } els...
Http 308 is code for permanent redirect, the page has moved... Check the Location header in the response and try with this url. The lib seems to have an option to follow redirects, try setting client.set_follow_location(true); https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
73,473,153
73,473,239
Array not Updating in a Function in my tic-tac-toe game
So I am making a tic-tac-toe game in c++. Here is my code so far: #include <iostream> #include <cmath> using namespace std; char gameboard[3][3]{{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}}; //Declares the Global Array for the Board char turn = 'X'; int column = 0; int row = 0; void PrintBoard() { //Display...
Your math is out and you have a typo (wrong variable) This is the correct code (I'm assuming TileNum has a values from 1 to 9) LocalRow = (TileNum - 1)/3; LocalColumn = (TileNum - 1)%3; Note that when you divide one integer by another you always get another integer, so floor is unnecessary.
73,473,180
73,514,153
1838. Frequency of the Most Frequent Element leetcode C++
I am trying LeetCode problem 1838. Frequency of the Most Frequent Element: The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum p...
The reason for the different output is that your xx index is only decreased one unit at each iteration of the i loop. But that loop is iterating for the number of unique elements, while xx is an index in the original vector. When there are many duplicates, that means xx is coming nowhere near the start of the vector an...
73,473,484
73,495,280
Failing under Correct VS Setup: Cannot open include file: 'imgui.h'
I beleive I am setting up my VS Config correctly but I still get errors when including a file as follows: The imgui file is under: The error is: Could you please help me?
If you want to link static library, I suggest you to read this issue carefully.
73,473,548
73,473,614
Template deduction of return type
I have a function that will retry a function for a certain number of times and return whether it was successful: template<typename Functor> bool Attempt(Functor functor) { bool success = false; size_t retries = MAX_RETRIES; do { success = functor(); } while (!success && retries-- > 0); ...
All the types you specify explicitly can be deduced: #include <optional> template <typename Functor> auto Attempt(Functor functor) { decltype(functor()) success{}; size_t Retries = 42; do { success = functor(); } while (!success && Retries-- > 0); return success; } std::optional<un...
73,473,556
73,473,641
'::' must be a class or namespace name in another class
I had defined a function in the header below class Camera { public: glm::mat4 GetViewMatrix() { return glm::lookAt(Position, Position + Front, Up); } } but when I use it in another class,it;s show. Error (active) E0276 name followed by '::' must be a class or namespace name void Camera::glm::mat4 GetVi...
There is no glm class in Camera class as shown. Change that function definition to glm::mat4 Camera::GetViewMatrix() instead.
73,474,859
73,475,861
How can cmake_minimum_required required version impact generated files?
I'm experiencing a strange behaviour where changing cmake_minimum_required affects files generated by CMake targetting Visual Studio 2019. According to the doc of cmake_minimum_required: If the running version of CMake is lower than the required version it will stop processing the project and report an error So it's...
So it's just supposed to interrupt project generation. That's not the case at all! cmake_minimum_required puts your project into a backwards compatibility mode consistent with the version specified. The "Policy Settings" section of that doc talks about this. There are a set of now over one hundred CMake policies that...
73,474,916
73,485,457
How to find and provide C++ library headers for clang?
I've built LLVM and Clang from sources using following instruction in order to try some of the latest C++ features. When I try to compile basic C++ program using this clang I get errors about missing basic headers: % /usr/local/bin/clang++ -std=c++20 main.cpp In file included from main.cpp:1: main.cpp:3:10: fatal error...
You should specify a path to the sdk for your target platform. You can retreive this by relying on xcrun: /usr/local/bin/clang++ -isysroot $(xcrun --show-sdk-path) -std=c++20 main.cpp In case you want to target other platforms (in the example bellow, for iphone) you have to specify both the target triple and the path ...
73,475,619
73,475,620
How to prevent CMake from explicitly linking system libraries?
I'll use CMake's example project as an example. So I have this: cmake_minimum_required(VERSION 3.10) # set the project name project(Tutorial) # add the executable add_executable(Tutorial tutorial.h) set_target_properties(Tutorial PROPERTIES LINKER_LANGUAGE CXX) After I generate the solution, when I open the solutio...
Posting this question and the answer because I couldn't find the solution on google, and it seems there wasn't one. Ok, so to fix the problem, all I need to do is: SET(CMAKE_CXX_STANDARD_LIBRARIES "") And that's it! Now CMake won't explicitly link all the libraries in the first screenshot in the question. But Even aft...
73,475,724
73,564,038
How can i run Microsoft Unit Testing Framework for C++ using github actions?
i'm trying to run my unit test which is using the Microsoft Unit Testing Framework for C++ using Github actions. I'v tried adding the DLL with the exe of the sln but it doesn't seem to work. build: runs-on: windows-latest steps: # using tmp v3 git branch - uses: actions/checkout@v3 # getting dependencies - name: get...
Went through the documentation and got it working. Microsoft unit test - https://learn.microsoft.com/en-us/visualstudio/test/vstest-console-options?view=vs-2019 GitHub actions vstestconsole set up - https://github.com/marketplace/actions/commit-status-updater runs-on: windows-latest steps: # using tmp v3 git branch -...
73,476,009
73,476,101
How to use cmath Bessel functions with Mac
So I am using Mac with the developer tools coming from XCode and according to other answers I should compile using something like: g++ --std=c++17 test.cpp -o test or using clang++ but I still I am having trouble making the script find the special functions. What else can I try? Minimum example #include <cmath> #incl...
https://en.cppreference.com/w/cpp/numeric/special_functions/cyl_bessel_j says: Notes Implementations that do not support C++17, but support ISO 29124:2010, provide this function if __STDCPP_MATH_SPEC_FUNCS__ is defined by the implementation to a value at least 201003L and if the user defines __STDCPP_WANT_MATH_SPEC_FU...
73,476,424
73,476,977
Makefile Compile Error and Visual Studio Code did not recognize include files
I use visual Studio Code and gcc-12.1.0, x86_64-w64-mingw32 and SDL2. I have folowing Makefile: all: g++ -I scr/include -L scr/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2 If I only have one main.cpp comiling and everything works. But now I added Header files and other C++ files. But I see already in Visual St...
g++ should be able to handle it, but for local includes you would usually use #include "" not #include <>. Otherwise, try to compile manually from the command line and see if the issue is related to your makefile / vs-code or if the include really can't be found.
73,476,947
73,496,338
How to get the "Dedicated GPU memory" number for every running process in Windows (The same numbers that are shown in the Windows Task Manager)
The Windows Task Manager, in the "Details" tab, shows the "Dedicated GPU memory" usage for every process. For example, I can currently see that chrome.exe uses 1.4 GB Dedicated GPU memory, dwm.exe uses 1.3 GB Dedicated GPU memory, and firefox.exe uses 0.78 GB Dedicated GPU memory. I want to get that exact same data fro...
Task manager and third party software are using performance counters to query the dedicated GPU memory information. For example you can execute these counters from powershell: Get-Counter -Counter "\GPU Engine(*)\*" Get-Counter -Counter "\GPU Engine(*)\Running Time" Get-Counter -Counter "\GPU Engine(*)\Utilization Perc...
73,477,191
73,477,205
Confused about having to bind VBO before editing VAO
I'm trying to draw a textured cube in OpengL. At first, I initialize VBO and VAO in the class constructor as follows. Block::Block(...) { glGenBuffers(1, &VBO); glGenVertexArrays(1, &VAO); //glBindBuffer(GL_ARRAY_BUFFER, VBO); glBindVertexArray(VAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, ...
You must bind the VBO before calling glVertexAttribPointer. When glVertexAttribPointer is called, the buffer currently bound to the GL_ARRAY_BUFFER target is associated with the specified attribute index and the ID of the buffer object is stored in the state vector of the currently bound VAO. Therefore, the VAO and the...
73,477,468
73,520,348
Why does the second wxSizer fail to center the button?
I created a global panel and called a method that creates a sizer and a button. The button clears the sizer (i.e., also the panel), and then deletes is. Then, another method is called, using the same logic, it creates another sizer and another button. This time they don't work. my code(windows, vs studio): #include "Ma...
You do need Layout(), as mentioned in the comments, as this is what actually repositions the windows -- SetSizer() just specifies the sizer to use for doing it, but doesn't do anything on its own immediately (it will when the window is resized the next time, as this results in a call to Layout()). However, even if it's...
73,477,497
73,478,006
How the code output is different when you compute it mentally? when the j = 2 the output should be 1, but the computer display 3
I was searching a method to print a pascal triangle, but when I tried to compute mentally it doesn't look right. the output of this is 1 3 3 1. but when you mentally calculate the iteration one by one the output is 1 3 1 0. is there something that I was missing? #include <iostream> using nam...
Your mental computation is bit wrong as I am sure you are not updating the value of "coef" mentally which is being changed to 3 rather than 1 which you seem to have missed after the 2nd iteration of the loop.
73,477,744
73,477,850
C++ convert std::string to byte array
Bear with me as I'm new to C++, pointers, etc.. I'm sending over raw image data to a microcontroller using Arduino via BLE. Currently, I'm using JS to send the raw data over as an ArrayBuffer. However (surprisingly), it looks like I can only receive the data on the Arduino side as a String and not raw Bytes. I verified...
Seems to be quite simple, std::strcpy() needs a pointer to writable (not const) memory, therefor the pointer cstr may not point to const char, leave out const and the following should work: char *cstr = new char [value.length()+1]; std::strcpy (cstr, value.c_str()); If you feel fancy, I believe you could use a const p...
73,477,843
73,509,805
How to create Anchor in front of camera in ARCore NDK API
I'm trying to create anchor in front of camera using ARCore C API. I extracted current pose of camera, and the documentation says that -Z pointing in the direction the camera is looking So I translated matrix of pose to -0.3 by Z axis. ArPose *pose = nullptr; ArPose_create(mArSession, nullptr, &pose); ...
First, you need to get view matrix of AR Camera and convert it to GLM matrix. float rawMatrix[16]; ArCamera_getViewMatrix(mArSession, arCamera, rawMatrix); glm::mat4 matrix = glm::make_mat4(rawMatrix); View matrix is commonly used to convert world coordinates to camera position (to apply perspective and camera transfo...
73,478,320
73,478,365
strange problem in a c++ program with pointers
I wrote this simple c++ program and I got some strange results that I don't understand (results are described in the line comments) int arr[3] {1, 2, 3}; int* p{ nullptr }; p = arr; std::cout << p[0] << " " << p[1] << " " << p[2]; // prints 1 2 3, OK p = arr; std::cout << *(p++) << " " << *(p++) << " " << *(p); // pr...
int* p{ nullptr }; std::cout << p[0] << " " << p[1] << " " << p[2]; This is Undefined Behavior, as you are dereferencing nullptr, p does not point at valid memory yet. p = arr; std::cout << p[0] << " " << p[1] << " " << p[2]; This is well-defined behavior. p points at valid memory, is always incremented before d...
73,478,447
73,479,791
Easiest way to deduce templates
As an example, I have the following function template: template <typename X, typename Y, typename Z> void f(X &x, Y &y, Z &z) { ... } I need to write a user interface in the form of void fxyz(std::string optionX, std::string optionY, std::string optionZ) Here, optionX, optionY, optionZ can be "x1" or "x2", "y1" or "y...
Map into variants, then visit them. std::variant<X1, X2> choose_X(std::string_view choice) { if(choice == "x1") return X1(); else if(choice == "x2") return X2(); } std::variant<Y1, Y2> choose_Y(std::string_view choice) { if(choice == "y1") return Y1(); else if(choice == "y2") return Y2(); } std::variant<Z1, Z2>...
73,478,489
73,478,512
QT creator for mac throwing error with some libraries
When loading a qt project in mac, I've got the following errors. In file included from ../../common/monitoring.cpp:1: ../../common/monitoring.h:3:10: fatal error: 'prometheus/exposer.h' file not found #include <prometheus/exposer.h> ^~~~~~~~~~~~~~~~~~~~~~ modules/ui/common/monitoring.h:3: error: 'prometheus/ex...
It should be INCLUDEPATH += "/opt/homebrew/Cellar/prometheus-cpp/1.0.1/include Since the subdirectory prometheus is set in #include <prometheus/exposer.h>.
73,478,612
73,478,829
thrust device_vector resize compilation error, don't understand why it requires .cu code
lets say I've got a main.cpp #include <thrust/device_vector.h> #include <cuda.h> #include <cuda_runtime_api.h> #include <iostream> int main(){ thrust::device_vector<float> test; //compiles fine! std::cout << test.size() << std::endl; // compiles fine! test.resize(6); //Error in thrust/system/detail/gener...
device_vector's name is self-explaining, this is a vector for device memory and is not created for using in system memory. std::vector should be used instead. This is the author's decision for the default settings. You are trying to use Thrust functionality in user mode code (C++ mode, CUDA is not enabled for .cpp code...
73,479,972
73,480,311
Why am I not reading the first member of the class when I point to the object with a pointer?
I'm experimenting with smart pointers and I wrote the code below: struct Buffer { char Data[128]; }; class SmartPtr { char * dataPtr; public: SmartPtr(Buffer& b) { dataPtr = b.Data; } ~SmartPtr() { cout << "desctructor called" << endl; } void operator=(Buffer & b)...
In the first code, you are taking the address of p (and thus the address of p.dataPtr), casting it to char*, and then printing it as-is. So, operator<< is misinterpreting the raw memory of p itself as-if it were a null-terminated string, which it is not, so you get garbage. In the second code, you are taking the addre...
73,480,039
73,480,689
When int age = -1, and I enter in an invalid input for age using cin (ie. asdf), why does the age return as 0 and not -1?
Using 64-bit Ubuntu 22.04.1 LTS | Using Eclipse IDE Version: 2022-06 (4.24.0) Build id: 20220609-1112 | Built using Linux GCC toolchain | Code alongside PDF of Stroustrup textbook Code: #include "std_lib_facilities.h" int main() { int age = -1; // program would still function if var was not assig...
C++98 had a bug, the book may have been written in late 2011, early 2012 and the author didn't use a C++11 compiler to test. cin >> first_name; This reads characters from input until non-whitespace is followed by white space. cin >> age; This reads digits into an integer, or 0 if the first character is not a digit. B...
73,480,081
73,480,130
Brace initialization when move constructor is deleted
This is probably not specific to C++20, but that's what I'm using right now. I have a simple struct struct foo { int bar; } which can be declared and initialized as const auto baz = foo{42}; Now, when I disable the move constructor (foo(foo&&) = delete;), the above initialization fails with error: no matching fu...
It is specific to C++20. Since C++20 a class is no longer aggregate if it there is any user-declared constructor at all, even if it is only defaulted or deleted. Aggregate initialization won't work anymore. This is a backwards-compatibility breaking change and you can't really get back the old behavior. You will have t...
73,480,289
73,480,390
Should you overload the "=" operator by reference or with a temporary variable?
Consider a class with just a single member for this example. class tester { public: int tester_value; tester(){} tester(int test_val) { tester_value = test_val; } tester(const tester & data) : tester_value(data.tester_value) { std::cout << "Copied!" << std::endl; } }...
Question 1: Why is it that using a temporary variable and memcpy() does not work properly to copy the data from one object to another? This is because of the Golden Rule Of Computer Programming: "Your computer always does exactly what you tell it to do, instead of what you want it to do". Tester A, B; // ... at some...
73,480,531
73,505,866
Win32: SendInput Alt+Click not working in some programs
I want to send Alt + Mouse Click to some programs. It works in most programs, it needs a small delay for some, but doesn't work at all in one of them. The mouse click is working, but the Alt key isn't. If I hold Alt manually and trigger a Mouse Click with SendInput(), it works. So I assume that the Alt key press is not...
It works in most programs, it needs a small delay for some, but doesn't work at all in one of them. "Most programs" check the Alt key state from inside the mouse message handler with correct synchronization. There are two correct ways: Look at the modifier flags in the message parameters (only applicable to Control...
73,480,895
73,480,912
pass truthy value of two non-boolean values to a function in a more terse way
My goal here is to pass the non-empty value of 2 given values (either a string or an array) to a function foo. In Javascript I'd be able to do: // values of variables a and b when calling foo // a = "hello" // b = [] foo( a || b ) // passes a, since b is empty and a is not (i.e // it contains at least 1 character) I...
You could use ?:, but you can’t define a foo that can use it as an argument. So try !a.empty() ? foo(a) : foo(b) You can’t make a foo that takes either type because C++ is strongly-typed, not dynamic like Javascript. And auto doesn’t change that — you aren’t naming the type, but there still is one. This also works fo...
73,482,101
73,482,205
Why does Visual Studio C++ take so long to compile
I use a pretty decent 3.4Ghz 4 core intel i5 cpu, and a Radeon Rx 560 Gpu, but for some reason it still takes at least 10-20 seconds to compile my code. Is there a way to speed it up? Or is this just how c++ works?
Sometimes, it doesn't matter what the specifications of your computer are. The size of some large scale Windows C++ projects can just take a lot longer because there is simply a lot more code, more functions to compile & link and or analyze. There are some things you can do to speed up the process by, using PCH (Pre-co...
73,482,589
73,484,556
How are string or vector type unsafe?
I am going through 'The C++ Programming Language, 4th Edition'. In 1.2.2 Type checking section, there is a sentence that says "Outside of low-level sections of code (hopefully isolated by type-safe interfaces), code that interfaces to code obeying different language conventions (e.g., an operating system call interf...
How are string or vector type unsafe? They aren't type-unsafe interfaces. As your quote states, their implementations may use type-unsafe code. To go into more detail, their implementations need to separate the allocation of storage, and the creation of the elements, which is inherently unsafe to do.
73,482,704
73,492,161
Type alias arguments in cppyy
I'm trying to use some C++ libraries in Python code. One issue I've had is I can't seem to call functions that take an aliased type as an argument. Here is a minimal example I've reproduced: import cppyy cppyy.cppdef( """ using namespace std; enum class TestEnum { Foo, Bar }; using TestDictClass = initia...
The problem is not with the alias, just that the converter code is not expecting an explicit std::initializer_list object, only the implicit conversions. This will work: res = TestClass([TestPair(TestEnum.Bar, 4), TestPair(TestEnum.Foo, 12)]) Edit: cppyy with repo master, the above now works as well.
73,484,142
73,484,248
Assertion failed I couldn't find the cause of the problem
for (size_t i = 1; i < count + 1; i++) { Mat img = vFrames[i - 1].Image1; Mat half1(mFinalImage, cv::Rect(-final_vector[i - 1].x + minx + abs(minx), -final_vector[i - 1].y - miny + abs(maxy), img.cols, img.rows)); img.copyTo(half1); } Mat half1(mFinalImage, cv::Rect(-final_vector[i - 1].x ...
The assertion error message explains it. One of the following statements in the constructor of Mat is false, however all should hold. 0 <= roi.x 0 <= roi.width roi.x + roi.width <= m.cols 0 <= roi.y 0 <= roi.height roi.y + roi.height <= m.rows Probably the region of interest is not within the matrix. Ensure that the d...
73,484,170
73,486,134
Template parameter deduction based on supplied lambda
I am exploring template parameter deduction in C++ and am currently facing the problem to deduce the parameter to a lambda and the return type of the method it's passed to as a parameter at the same time. I think it should be possible, since all the types are known at compile time, but I fail to find the solution. Some...
Function::operator() may be a template, in which case &Function::operator() will fail. Function::operator() may be overloaded, in which case &Function::operator() will also fail. A lambda with an auto parameter has a template operator(). struct function_traits doesn't know and doesn't care about Action<A>. All it has i...
73,484,508
73,488,068
Poco::Net::FTPClientSession uploading blank, 0-byte copy of the actual target file
I am currently writing a class which handles a variety of FTP requests and I'm using Poco's FTPClientSession class. I've managed to get most of the stuff I needed to work, however I'm facing an issue regarding uploading files to the server. int __fastcall upload(String sLocalPath, String sLocalFile, // String ...
Turns out, Poco::Net::FTPClientSession::beginUpload() doesn't read the file on its own. It returns a reference to an std::ostream, to which you need to load the contents of the file yourself (e.g. using std::ifstream): std::ifstream hFile(sLocalFilepath, std::ios::in); std::string line; std::ostream& os = m_Session.beg...
73,485,556
73,485,777
Template specialization for the base template type for future derived types
I have a class that works as wrapper for some primitives or custom types. I want to write explicit specialization for custom template type. My code that reproduces the problem: template < class T > struct A { void func() { std::cout << "base\n"; } }; template <> struct A<int> {}; template < class T, class CRTP >...
Not sure I fully understood what you want, but maybe something like this: template<typename T> concept DerivedFromBaseCrtp = requires(T& t) { []<typename U, typename CRTP>(BaseCrtp<U, CRTP>&){}(t); }; template < DerivedFromBaseCrtp T > struct A<T> { void func() { std::cout << "sometype\n"; } }; The concept ba...
73,485,942
73,492,697
c++20 default comparison operator and empty base class
c++20 default comparison operator is a very convenient feature. But I find it less useful if the class has an empty base class. The default operator<=> performs lexicographical comparison by successively comparing the base (left-to-right depth-first) and then non-static member (in declaration order) subobjects of T to...
I'd like to make a small modification based on @Barry's answer. We could have a generic mix-in class comparable<EmptyBase> that provides comparable operators for any empty base. If we want to use default comparison operators for a class derived from empty base class(es), we can simple derive such class from comparable<...
73,486,095
73,486,260
Why is there delay when I write on a file using c++?
I've tried to open a file, write something on it, read from the file and do the same process again but the output isn't what I expect, here's the code: file.open("ciao.txt", std::ios::out); file << "ciao"; file.close(); file.open("ciao.txt", std::ios::out | std::ios::in); std::string str; std::...
The problem is a combination of things. Here you write ciao to the file, no problem - except it doesn't have a newline (\n). file << "ciao"; Later, you read a line: std::getline(file, str); Had there been a \n in the file, EOF would not have been reached and the fstream would still be in good shape for accepting I/O....
73,486,374
73,488,654
Qt C++ Memento Design Pattern, I am trying to add a Undo/Redo function to my program, but why doesn't it work properly?
I am learning about the Memento Design Pattern and have constructed a simple Program for this purpose. I have constructed 2 classes, Container, which only holds a QString called Code The GUI is very simple, there is a QListWidget that displays a list of Container Items that have not been allocated to an Pallet Object, ...
Please notice: the problem lies in the fact you're using a list of pointers to store the pallets. It goes like this: pallet list has 2 items before modifying it you copy the list to the memento then you add a container to the last of the two items At this point you should notice that the list of pallets isn't really ...
73,486,578
73,486,908
convert time string to epoch in milliseconds using C++
I try to convert the following time string to epoch in milliseconds "2022-09-25T10:07:41.000Z" i tried the following code which outputs only epoch time in seconds (1661422061) how to get the epoch time in milliseconds. #include <iostream> #include <sstream> #include <locale> #include <iomanip> #include <string> int ma...
You can use the C++20 features std::chrono::parse / std::chrono::from_stream and set the timepoint to be in milliseconds. A modified example from my error report on MSVC on this subject which uses from_stream: #include <chrono> #include <iostream> #include <locale> #include <sstream> int main() { std::setlocale(LC...
73,486,864
73,487,212
how to loop through an array of string and turn them into ascii , while storing them in dynamic memory?
i am trying to make a program that turns each character of a string into an ascii character and store them into an array and then print them out . However it doesn't allow me to print anything out . I have tried assigning a string to the message input and it works perfectly but it doesn't work for user input.It just ...
string message_input{}; This defines a new std::string. The string is empty, by default. int l = message_input.length(); This obtains the string's length(). The string is empty, so l must be 0 at this point. std::getline(std::cin, message_input); This now reads some input, of unspecified length, from std::cin. messa...
73,487,780
73,488,061
Raycast check crashing UE5
I am trying to check what a multi line trace by channel is hitting by printing every hit object's name to the log, however the engine keeps crashing due to (I assume) a memory error. I've tried only printing the first object, which works, but since this a multi line trace I would like to check every object that is bein...
sizeof(hits) gives you the size of the C++ object in bytes, not the number of items in the container. You need to use for (int i = 0; i < hits.Num(); i++)
73,488,313
73,488,446
gRPC assertion failed when stopping async helloworld server
I'm trying to shutdown properly a gRPC server. I use the provided async helloworld from gRPC source. The file is here: https://github.com/grpc/grpc/blob/master/examples/cpp/helloworld/greeter_async_server.cc I have edited the main like the following: #include "greeter_async_server.cc" #include <thread> #include <iostre...
You're trying to delete an object (server) that's been created on the stack. That said, the example code does not showcase any way to cleanly stop the server once it's been started. It is even said in a comment above the Run() method: There is no shutdown handling in this code. This question provides good pointers ...
73,488,596
73,489,264
Is it possible to get/set values from a pointer vector<json>?
I am currently experimenting with C++, basically I am trying to find the most repeated values in a very huge array using vectors and json. However to make my code more efficient I've decided to use threading, however my knowledge of pointers and addresses doesn't seem to work on this one. Basically I am trying to do th...
I suggest not using the name read (it may conflict with other reads - especially since you do using namespace std; in the global scope - so don't do that). Also, pass by reference to the thread function. It's easier to deal with. You do that by packaging them in std::reference_wrappers (using std::ref). Example: #inclu...
73,489,183
73,489,463
Count Subarrays with Target Sum
Can anyone help me understand what this piece of code does? His logic, what is the output etc // currsum exceeds given sum by currsum // - sum. Find number of subarrays having // this sum and exclude those subarrays // from currsum by increasing count by // same amount. if (prevSum.find(currsum - sum) != prevSum.end()...
Those two lines you ask is the typical way to look if a certain key is in the map and get the value associated with that key. You have to check if there is a (key, value) pair in the map before accessing it with operator[], because if there is none then map[key] will insert a pair for that key with default value of the...
73,489,190
73,496,173
C++: std::memory_order in std::atomic_flag::test_and_set to do some work only once by a set of threads
Could you please help me to understand what std::memory_order should be used in std::atomic_flag::test_and_set to do some work only once by a set of threads and why? The work should be done by whatever thread gets to it first, and all other threads should just check as quickly as possible that someone is already going ...
Following up on some things in the comments: As has been discussed, there is a well-defined modification order M for done on any given run of the program. Every thread does one store to done, which means one entry in M. And by the nature of atomic read-modify-writes, the value returned by each thread's test_and_set i...
73,489,287
73,489,968
i'm getting an error in for loop and if statements:
#include <iostream> using namespace std; int main() { int i,t,km,sum=0; std::cin >> t; for( i=0;i<t;i++){ cin>>km; } for(i=0;i<t;i++){ if(km>300){ sum=km*10; cout<<sum; } else if(km<=300){ sum=300*10; cout<<sum; } else{ cout<<"wrong!"; ...
We'll start with a mini code review: #include <iostream> using namespace std; // Bad practice; avoid /* Generally poor formatting throughout */ int main() { int i,t,km,sum=0; // Prefer each variable declared on its own line; i is unnecessary std::cin >> t; for( i=0;i<t;i++){ // Overwrites `km` t times ...
73,489,422
73,489,825
How to get Maximum CPU frequency
I want to get the maximum frequency the cpu is designed for by the manufacturer. On Linux I can get the frequency each core is currently operating at by reading "/proc/cpuinfo" but I want max frequency (The rated frequency is written in the model name in "/proc/cpuinfo" but I don't know if this is the case for AMD proc...
Under linux, for a given CPU (e.g. N), look at the /sys/devices/system/cpu/cpuN/cpufreq directory. In that directory there are many interesting files: affected_cpus bios_limit cpuinfo_cur_freq cpuinfo_max_freq cpuinfo_min_freq cpuinfo_transition_latency freqdomain_cpus related_cpus scaling_available_frequencies scaling...
73,489,837
73,490,020
Why the base case with no template arguments for variadic tuple is not working?
As an exercise, I'm trying to define a variadic template for a Tuple but I found that the base case with no elements is not working. template <typename Head, typename... Tail> struct Tuple : Tuple<Tail...> { Tuple(const Head& head, const Tail&... tail) : Base{tail...}, m_head{head} {} private: using Base = Tup...
One correct incantation would be template <typename...> struct Tuple; template <> struct Tuple<> {}; template <typename Head, typename... Tail> struct Tuple<Head, Tail...> : Tuple<Tail...> { (the rest is identical to your code).
73,490,216
73,490,387
How to fix "expected primary-expression before 'continue'"?
I've started learning C++ and found myself in trouble with a simple problem. All that I need to do is to remove repeating spaces from stdin using a while loop, but I want to solve this problem with ternary if expressions. Here's my code: #include <iostream> using namespace std; int main() { bool space = false; ...
I assume that this obscure construction: c != ' ' ? space = false : !space ? space = true : continue; is meant to be this: if(space && c == ' ') continue; space = c == ' '; That is, if the previous character was a space and the current is too, continue, otherwise, set space to true if the current is a space and false...
73,490,555
73,494,463
Understand the bullet (5.4.1) in [dcl.init.ref] clause
Given the following example, struct S { operator const double&(); } const int& ref = S(); First per [dcl.init.ref]/5: A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows: Taking "cv1 T1" as const int and "cv2 T2" as S. Skipping all discarded bullets until we reach to [dcl....
If T1 or T2 is a class type and T1 is not reference-related to T2, user-defined conversions are considered using the rules for copy-initialization of an object of type "cv1 T1" by user-defined conversion As it says, you use the rules for copy-initialization of an object (not reference) of type cv1 T1. In other words,...
73,490,666
73,491,315
Is it possible to acquire the function pointer of a template member function with not all template arguments deduced?
Considering the code below, is it possible to acquire the function pointer of operator() for Test2 given that you have all its template arguments? For example, say I want a function pointer that points to operator()<float, double> where Args={float} and Type2=double. template<class Type1> struct Test1 { Type1 valu...
you may try declaring it like this bool (Test2<int>::*ptr2)(const double&) = &Test2<int>::template operator()<float>; or even auto ptr3 = static_cast<bool (Test2<int>::*)(const double&)>(&Test2<int>::template operator()<float>);
73,490,728
73,490,788
Can not be inherited from a template C++ class
I don't know what is the problem here... Maybe someone can help me, please. I want to inherit my new class MyDictionary from template abstract class dictionary. I have exactly this code: Dictionary.h #ifndef UNTITLED_CPP_DICTIONARY_H #define UNTITLED_CPP_DICTIONARY_H template<class Key, class Value> class dictionary {...
dictionary is a class template, and therefore when you inherit from it you have to specify the template arguments. In your case it seems like you would like to inherit dictionary with the same template arguments used for the derived class. Therefore change: class MyDictionary : public dictionary { To: //--------------...
73,490,976
73,491,115
Assigning an Array and a string to a function and compare them
Hello I just do not get it further. I would like to pass a variable string to a function and compare it with an array which i filled b4. The problem is that i dont know how I can pass all values of the candidates array to the function : I can just pass a single string to the function. In my Code that would be the 0. I ...
Take a look at the AnyOf function from the algorithm library. With it, you can apply the vote function to each array element, not only the first one. Pseudocode: if (std::all_of(candidates.begin(), candidates.end(), vote) { ... }
73,491,244
73,491,782
Is this reference-initialization or aggregate-initialization?
I have the following code snippet: struct A {}; struct B : A{}; B b{ A() }; Does the implicitly-declared copy constructor B::B(const B&) is used here so that the reference (const B&) is bound to B subobject of initialzier expression A()? and why no? If this is an aggregate initialization, this means that the ctor B::...
From C++17 onwards, B b{ A() }; is aggregate initialization. Prior C++17 Prior to C++17, the class-type B is not an aggregate. So B b{ A() }; cannot be aggregate initialization. In particular, B b{ A() }; is direct initialization: The effects of list-initialization of an object of type T are: Otherwise, the construct...
73,491,771
73,495,531
Why the tuple has a larger size than expected?
I had the following definition of a tuple class template and tests for its size. template <typename...> struct Tuple; template <> struct Tuple<> {}; template <typename Head, typename... Tail> struct Tuple<Head, Tail...> : Tuple<Tail...> { Tuple(const Head& head, const Tail&... tail) : Base{ tail... }, m_head{ h...
Empty base optimization only applies when you derived from an empty class. In your case, Tuple<> and Nil are empty classes, while Tuple<Nil> is not since it has non-static members (taking an address). You have already enjoyed EBO in your implementation. Tuple<int*> is derived from Tuple<>, which is empty, so sizeof(Tup...
73,491,957
73,492,719
How can i use neovim and coc.nvim for develop windows c++ apps on linux
I develop c++ apps on linux and i use neovim with coc.nvim and coc-clangd plugins. I want to develop an app for windows but i comfort with linux and neovim so i want to use them for it. But i get some include errors with some windows headers (etc. "windows.h"). I use linux only for writing the code and i'll compile the...
i'll compile the program on windows You can cross-compile it from Linux. It's only marginally more difficult than getting the code completion to work. Get the standard library headers (and libraries, if you want to cross-compile) from MinGW. Your package manager might have those, or you can get them from https://win...
73,492,380
73,492,477
How Do Vectors Pass By Value?
If I have created a vector object, an instance that has a size of 24 Bytes (on my machine) will be allocated. I have read that a vector object contains (roughly speaking) two elements: Pointer points to the first element of the data stored in the heap memory. The size of the data. I know that passing by value will no...
When we say that an object is copied in C++, we do not mean that the bytes of the storage that the object occupies are simply copied as if by memcpy which is what you are describing. Instead copying means invoking the copy constructor (or the copy assignment operator) of the class type to perform the copy operation in ...
73,492,392
73,492,441
Is this aggregate initialization or reference-initialization (revisted)?
This is a follow up question to Is this reference-initialization or aggregate-initialization? Consider the same example: struct A {}; struct B : A{}; A a{ B() }; Does this is an aggregate initialization or reference initialization? I mean by "reference-initialization" that the implicity-declared copy constructor A::A...
Does this is an aggregate initialization or reference initialization? A is an aggregate and A a{ B() } is list initialization according to the following rule(s): The effects of list-list-initialization of an object of type T are: If T is an aggregate class and the braced-init-list has a single element of the same o...
73,493,165
73,507,346
Quickest way to shift/rotate byte vector with SIMD
I have a avx2(256 bit) SIMD vector of bytes that is padded with zeros in front and in the back that looks like this: [0, 2, 3, ..., 4, 5, 0, 0, 0]. The amount of zeros in the front is not known compile-time. How would I efficiently shift/rotate the zeros such that it would look like this: [2, 3, 4, 5, ..., 0, 0, 0, 0]?...
AVX2 has no way to do a lane-crossing shuffle with granularity smaller than 4 bytes. In this case, you'd want AVX-512 VBMI vpermb (in Ice Lake). If you had that, perhaps vpcmpeqb / vpmovmskb / tzcnt on the mask, and use that as an offset to load a window of 32 bytes from a constant array of alignas(64) int8_t shuffle...
73,493,287
73,496,221
Qt How to stop shift-tab from changing widget focus?
I'm trying to set up a text edit that does the shift+tab remove indentation thing that code editors do; but i can't respond to shift+tab because it changes the widget focus. I tried overriding the event function in the main window and that didn't work; then i tried event filters on all widgets and that didn't work; the...
I was able to implement the desired behavior in Qt's included qtbase/examples/widgets/widgets/lineedits example program, by inserting the following code into main.cpp, just above int main(int, char **): class BackTabFilter : public QObject { public: BackTabFilter(QObject * parent) : QObject(parent) { qApp->...
73,493,802
73,493,870
The Interaction between std::array, std::vector, and std::copy
I am trying to copy a std::array into a std::vector using std::copy. According to the cppReference, the prototype of std::copy is: std::copy(InputIt first, InputIt last, OutputIt d_first) , where OutputIt d_first stands for the beginning of the destination range. By following the implementation, I have the following c...
vec.begin() is an output iterator and there is in principle no problem with using it in the way you are trying to. However vec.begin() is an iterator to the beginning of the range currently held by the vector. It is not an iterator that appends to the vector. Since your vector is initially empty, the valid range to whi...
73,494,170
73,494,326
Will there still be a memory leak if I don't store the returned ptr?
I was reading this question, and here the jsoncpp CharReaderBuilder::newCharReader() function returns a pointer to a dynamically created CharReader object, which can then be used to parse a JSON. I understand in that question the OP should have freed the returned pointer once it was used, since it was created on the he...
"The other way" is using smart pointers. Consider the following examples. #include <iostream> struct A { int b; A(int _b) :b(_b) { std::cout << "A created." << std::endl; } ~A() { std::cout << "A destroyed." << std::endl; } }; void c(A *a) { std::cout << a->b << std::endl; } int main() { c(ne...
73,494,420
73,494,870
`requires` expression is evaluated to false in a nested template, but code is still compiled
I am failing to understand how the requires keyword works inside a nested template. The code below can be compiled on the latest versions of MSVC and gcc (using /std:c++latest and -std=c++2a, respectively). Is the requires simply discarded in scenarios like this? Should I not use it this way? #include <type_traits> te...
I think the compilers are not implementing this correctly and you are correct that it should fail to compile. In [temp.names]/7 it says that a template-id formed from a template template parameter with constraints must satisfy these constraints if all template arguments are non-dependent. You are giving Wrapper only on...
73,494,686
73,527,958
How to get class pointer.instance from llvm instruction iterator?
I am writing llvm pass and my goal is to check if instruction is signed division instruction. I am doing something like that to get instructions in the function: for (inst_iterator I = inst_begin(&function), E = inst_end(&function); I != E; ++I) { errs() << *I << "\n"; }; Above gives me printout like that, example: ...
There are several ways to achieve this. Using Instruction::getOpcode (https://llvm.org/doxygen/classllvm_1_1Instruction.html#ab4e05d690df389b8b1477c90387b575f) as you suggested: for(auto I = inst_begin(F), E = inst_end(F); I != E; ++I) { Instruction &Inst = *I; if(Inst.getOpcode() == Instruction::SDiv) { errs()...
73,495,034
73,497,513
add a QListWidgetItem to a QListWidget using a std::shared_ptr to fix fortify issue
Fortify doesn't like QListWidget::addItem(new QListWidgetItem) and reports a false memory leak, even though QT manages the memory properly. I'm trying to figure out a work-around. I was told to use a std::shared_ptr, but I haven't figured out the syntax yet. Here's what I've got so far, but it reports an error about th...
This might do the trick, based on code you show in your question: class Class1{ ... std::unique_ptr<QListWidgetItem> item; // no need to use shared ptr std::unique_ptr<...whatever you need here...> ui; // change ui to unique_ptr and put it after the item! // remember to change construction of `ui` accor...
73,495,144
73,495,241
Overriding >> and polymorphism
So I am trying to do something, but I am not sure it can/should be done this way in c++. I have a file of objects I want to read in. Each object is of one of 3 types of classes which are part of a hierarchy In the file I have a discriminator to tell me which is which. Lets say the classes are: Checking, Savings and a...
C++ does not work this way, on a fundamental level. Quoting from your question, if you have a declaration: Account a; Then that's what a is. In C++, the types of all objects must be known at compile time. This is fundamental to C++, there are no exceptions or workarounds. The type of a cannot be changed at runtime, ba...
73,495,600
73,496,340
Return derived class object in the script whereas original function declaration returns parent class in C++
A function GetCarPrice() has a return type of a class Money where the function is declared, and this method is not declared within Money, meaning it's not a member function of this class. Later, I derive another class from Money, defined as Dollar, with some additional attributes and methods. Now, I want to return Doll...
Just create a Dollar instance and return the pointer of it in the GetCarPrice(). If there are some legacy code that creates a Money instance and you want to keep it, you should convert the object like this.(If the Money class has a copy constructor, it will be easy because you can call it at the constructor of the Doll...
73,495,642
73,495,657
Why the C++ compiler recognize the string type as char[]
I wrote a function template about google::protobuf::Map,code as follows: template <typename K, typename V> struct ContainImpl<google::protobuf::Map<K, V>, K> { static bool contains(const google::protobuf::Map<K, V>& container, const K& value) { return container.find(value) != container.end(); } }; template <typ...
Because a string literal in C++ is not a std::string. It is an array of const char of the appropriate size. If you want a string literal to become a std::string, you can use the user-defined string literal operator operator""s from the standard library since C++14: using namespace std::literals; //... Contains(*googl...
73,495,693
73,495,842
State of underlying resource when a shared_ptr is created from the raw pointer?
This link about shared pointers states that You can pass a shared_ptr to another function in the following ways: ... Pass the underlying pointer or a reference to the underlying object. This enables the callee to use the object, but doesn't enable it to share ownership or extend the lifetime. If the callee creates a s...
The paragraph is weirdly worded. If you remove this sentence: If the callee creates a shared_ptr from the raw pointer, the new shared_ptr is independent from the original, and doesn't control the underlying resource. It's fine. Indeed, talking about what would happen if the callee creates a new shared_ptr is somethin...
73,496,495
73,496,520
Why this Dijkstra algorithm is working without using min heap?
I implemented Dijkstra's algorithm using only a FIFO queue, still it passes all test cases in GFG. When will this code fail or if it works then why do we need to use a min heap? vector <int> dijkstra(int V, vector<vector<int>> adj[], int S) { // adj [] = {{{1, 9}}, {{0, 9}}} vector<int> dist(V, INT...
Using a FIFO instead of a min-heap will still give you the correct answer, but the time that your program will take to find that answer will be longer. To be noticeable, you would need to provide a large graph as input.
73,496,544
73,496,733
C++ function template initialization?
I'm not sure if this title reflects the question. Here's a template function. My question is what does s(...) in the code below mean since compiler doesn't know what class Something is and the compiler doesn't even complain. I don't quite understand what's going on. Thanks template <class Something> void foo(Something ...
what does s(...) in the code below mean It means that you're trying to call s while passing different arguments 0, {"--limit"}, "Limits the number of elements. For example, s might be of some class-type that has overloaded the call operator operator() that takes variable number of arguments. So by writing: s(0, {"--l...
73,498,019
73,498,944
C++ Array Sorting With Indices
I need to sort a float arr[256][16] array while retaining the original indices of the elements. So, for instance, if the indices of x = [7,12,4] are 0, 1, 2, I would like to sort this array as [4,7,12] and "remember" the indices as 2,0,1. Also, the container must be a standard array, even if its easier to use structure...
What you could do is, to sort the indices, based on the values in the array. And leave the array as is. And later access the elements through the index array. So, you compare the real float values, if one is less than the other, but then, exhange the index values in the index array. This could look like the below #incl...
73,498,110
73,498,588
c++: how to define a function using class name as the input parameters
In c++, typeid can accept the class name as the input. If I also want to implement a similar function, just like: void func(T class) { std::cout<< typeid(class).name() <<std::endl; } What should be the T? Update I am sorry for this unclearing question. And more details are provided in the following. I want to use ...
how to define a function using class name as the input parameters Functions do not take types as parameters. I know what template is, and what I want is not template. I hope the function can be used as func(A), where A is a class. typeid is not a function, it is a built-in operator. How it is implemented is beyond ...
73,498,376
73,498,403
What is the difference between single quotes and double quotes in these two functions?
What is the difference between single quotes and double quotes in these two functions? After I swap the two symbols, it can run normally. At the same time, I also want to know how to check this error through the content in the screenshot. The content is an overloaded function that matches the parameter list. How can I ...
Single-quote means for one-character. Can be used in type char Double-quotes means for a string. Can be used in type char[] or string, ...
73,499,804
73,500,041
Boost asio steady_timer work on different strand than intended
I am trying to use asio :: steady_timer in asio coroutine (using asio :: awaitable). steady_timer should work on a different strand (executor1) than spawned coroutine strand (executor), but asio handler tracking support shows that otherwise I clearly give the timer its strand it working on asio Coroutine strand, any th...
You pass the executor by reference. This is atypical. Executors are light-weight and cheaply copyable. In your case this happens to be ok, because the lifetime of executor1 exceeds the coroutine, and it isn't being modified on another thread, but in general, avoid reference arguments to coros (see e.g Boost asio C++ 20...
73,499,957
73,500,040
cast const pointers to void * in C++
I have the following code that does not compile with gcc 10.2.1 : struct Bar { unsigned char *m_a; unsigned char m_b[1]; }; int main() { Bar bar; const Bar &b = bar; void *p1 = b.m_a; // Ok void *p2 = b.m_b; // Error return 0; } The compiler error is : error: invalid conversion from ‘co...
Having a const struct adds const to all the members. Adding const to unsigned char * gives you unsigned char * const (i.e., the pointer cannot be changed to point to anything else, but you can change the value of what is pointed to). This can be cast to void *, since that is also a pointer to non-const. Adding const to...
73,499,965
73,500,249
Group last segment of a path using RegEx
I have a path where the first segments in this path are constant and will never change, the last segment is variable. Example: /my/awesome/path /my/awesome/path/ /my/awesome/path/1 /my/awesome/path/2 Is it possible using regex to determine the last segment and group it to a certain name? For example group it to name: ...
If you absolutely, 100% must use a regex, here's one possible solution which should work with most regex engines: ^/my/awesome/path/?(.*)$ The first capturing group will contain your id after the known prefix (with our without slash).
73,500,145
73,503,713
Pybind11 is slower than Pure Python
I created Python Bindings using pybind11. Everything worked perfectly, but when I did a speed check test the result was disappointing. Basically, I have a function in C++ that adds two numbers and I want to use that function from a Python script. I also included a for loop to ran 100 times to better view the difference...
Benchmarking is a very complicated thing, even can be called as a Systemic Engineering. Because there are many processes will interference our benchmarking job. For example: NIC interrupt responsing / keyboard or mouse input / OS scheduling... I have encountered my producing process being blocked by OS for up to 15 se...
73,500,302
73,500,920
WinAPI BCrypto RSA algorithm limits?
So here is a very simple code. Avoiding all the check and frees to keep it clean. // the key is an RSA key 1024 bits static const std::string PublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEfQ5ApaNvZN+xAZhbqaSV+ZAd" "N161lWDbQUQlKQdJgJtFQd22jyu0U7Nu88qQKV+JTKNJgnegQ9U7vsTchE8gqcjp" "jLgTqId6DZWxZ5w41o0...
RSA cannot encrypt data that is (when interpreted as a large integer) numerically greater or equal to the RSA modulus. Given that your key is 1024 bits and you're encrypting 128 bytes (1024 bits) the failing cases are most likely when the random data is numerically larger than your modulus. If you need to encrypt 128 b...
73,500,511
73,527,689
How to include existing C++ libraries per platform in MAUI project?
We have a C++ library that is built per platform i.e. .dll for Windows, .so for Android & .a for iOS. Tried the following to include the .so file in MAUI app for Android. (Other platforms are pending) - Platforms -> Android -> lib -> arm64-v8a folder Set .so file property : Build Action = AndroidNativeLibrary Used Jav...
So the correct location to put the .so files for Android is apparently <project root>\Resources\lib\<platform>\ So for arm64-v8, it's <project root>\Resources\lib\arm64-v8a\ (Also, anything copied into <project root>\Resources\Raw is directly copied into Android asset directory.)
73,500,600
73,500,863
In the Excel XLL SDK, why is xlfRegisterId failing when called from a user defined function?
I am following Malik's anwer to this question to try to get hold of the registration id of my user defined function. If I insert the code into my xlAutoOpen function like this extern "C" __declspec(dllexport) int xlAutoOpen(void) { XLOPER12 xDLL; Excel12f(xlGetName, &xDLL, 0); Excel12f(xlfRegister, 0, ...
Thanks to Steve Dalton's excellent book, I found the answer. The user defined functions needs to be registered with macro function permissions, by adding a # after QQQ in the above definition. So the code becomes extern "C" __declspec(dllexport) LPXLOPER12 exampleAddin(LPXLOPER12 x1, LPXLOPER12 x2) { XLOPER12 xDL...
73,500,832
73,500,908
Removing from the beginning of an std::vector in C++
I might be missing something very basic here but here is what I was wondering - We know removing an element from the beginning of an std::vector ( vector[0] ) in C++ is an O(n) operation because all the other elements have to be shifted one place backwards. But why isn't it implemented such that the pointer to the firs...
std::array and C-style arrays are fixed-length, and you can't change their length at all, so I think you're having a typo there and mean std::vector instead. "Why was it done that way?" is a bit of a historical question. Perspectively, if your system library allowed for giving back unused memory to the operating system...
73,501,241
73,503,731
Why this two different implementations of Tuple have a different size?
I have two different implementations of a Tuple class template. One with specialization for any number of arguments and one using variadic templates. When using an empty class for some of the tuple elements the two implementations have different sizes. Why does the second one using a variadic template have a bigger siz...
Tuple1<int*> is Tuple1<int*, Nil> and have a specialization wich unique member T1 x; with empty base class Tuple1<Nil, Nil>. On the other side, Tuple2 treat Nil as any other (empty) types. With cppinsights, you might see instantiation: template<> struct Tuple2<Nil> : public Tuple2<> { inline Tuple2(const Nil& head); ...
73,501,401
73,701,342
Cmake package not found
I've installed Drogon using vcpkg, and in my IDE I have following error: Package 'Drogon' not found. After installing, regenerate the CMake cache. I am using Visual Studio 2022 vcpkg_rf.txt: install drogon CMakeLists.txt: # CMakeList.txt : Top-level CMake project file, do global configuration # and include sub-project...
Considering the given information: Visual Studio 2022 -> Means CMake will default to x64 -> vcpkg will use VCPKG_TARGET_TRIPLET=x64-windows vcpkg_rf.txt: install drogon -> Means you use a response file to install drogon. Without specifying the triplet this is x86-windows As such your triplet used by CMake and vcpkg...
73,503,035
73,503,864
How to limit parameter less template method to types of the own template class?
I have a template class that represents a special integer type. A minimal implementation of this class could look like this: template<typename T> struct Int { static_assert(std::is_integral_v<T>, "Requires integral type."); using NT = T; T v; explicit constexpr Int(T v) noexcept : v{v} {} templ...
First a type trait from Igor Tandetnik (my own was uglier): template<typename T> struct Int; // forward declaration template <typename T> struct is_Int : std::false_type {}; template <typename T> struct is_Int<Int<T>> : std::true_type {}; template <typename T> inline constexpr bool is_Int_v = is_Int<T>::value; Then y...
73,503,316
73,504,519
Is there a way to create an array of functions inside a loop in C++
I'm using ROOT Cern to solve a multi-variable non-linear system of equations. For some problems I have 4 functions and 4 variables. However, for others I need 20 functions with 20 variables. I'm using a class called "WrappedParamFunction" to wrap the functions and then I add the wrapped functions to the "GSLMultiRootFi...
Making your i a template parameter and generating the functions recursively at compile time can also do the trick: using FunctionPrototype = double(*)(const double *, const double *); template<int i> double func(const double * x, const double * par) { return -par[i]+x[i]*par[i+1]; } template<int i> void generate_re...
73,504,265
73,504,380
What happens when I access a pointer when it's stored in a vector which is on the stack?
std::vector<object*> objects; Object* o = new Object(); objects.push_back(o); I want to access objects[0]. So, when I access it, is there a pointer to the stack, then the heap? Or, how does this work?
There's a few things to unpack here. First off, let's say you have a vector<object*> as you state, and that it is declared with automatic storage duration. void f() { // declared with automatic storage duration "on the stack" std::vector<object*> my_objects; } A vector by it's nature stores a contiguous block ...