question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
62,242,451
62,242,655
Multiple argument with std::forward in C++
I have a struct which has 5 member, I initialize all argument with std::forward : #include <iostream> #include <string> #include <utility> struct OutputFilesName { template<typename T> OutputFilesName( T&& result_subdir_name, T&& result_TSIM_minus, T&& result_TSIM_plus, T&& result_minus_total_dat, ...
Problem is that your constructor uses common type T for all arguments. Now for first argument char[2] is deduced for second char[3] what is in conflict. If you pass all stings with same length it compiles. So for each argument you need different template parameter (demo). Anyway consider drooping use of explicit const...
62,242,472
62,242,528
How to decrement several variables in C++in a single line statement?
Edit: I replaced the phrase 'in one line' by 'in a single line statement' since this is what I was looking for Let's say we have the following variables at hand: int a = 5; int b = 9; Is there a way to compress this ... a--; b--; ... into in a single line statement?? The question is not about decrementing multiple va...
You probably mean "in a single statement", not just "in a single line". Then you can use the comma-operator: (a--,b--);
62,243,162
62,243,579
How to access SetThreadDescription() in Windows 2016 Server, Version 1607
If I just call SetThreadDescription() from WinAPI, it works on Windows 10, Version 2004. However, on Windows 2016 Server, 1607 it produces the following message box: The procedure entry point SetThreadDescription could not be located in the dynamic link library and the path to my executable program follows in the mes...
Apparently, despite MSDN says "DLL: Kernel32.dll", the function is actually in KernelBase.DLL, so I've fixed the problem after changing to: HMODULE hKernelBase = GetModuleHandleA("KernelBase.dll");
62,243,173
62,244,159
Some test cases aren't passing
#include <iostream> #include <vector> int i=0; //points at the current stack that we are working with int box=0; //no. of boxes held by the crane int64_t H; //max. height of the stacks given in the que. int main() { int n, value; //storing no. of stacks and creating an additional variable value to store operati...
With the method you're trying to define an array with a user-input length is unfortunately invalid in C++. But fortunately, there are basically two methods use to allocate arrays dynamically. Method 1: Using Vectors Vector is an important part of C++. It has a lot of features (e.g. its size don't need to be defined sta...
62,243,284
62,244,100
Detect consecutive objects with a common attribute in 2-D array
I have a 2-D array of gems, all the gems have been given random color. Now i want to detect if three or more consecutive gems in a row or column has the same color. If so i want to do some action with those gems. Gem gems[10][10]; for(int i=0;i<10;++i){ for(int j=0;j<10;++j){ gems[i][j].setColor(GetRandIn...
Here's how I'd go about it. You need to do two scans. First, you need to scan for runs in one direction, then the other. It's much simpler than trying to loop through once. I first check for horizontal runs, exiting as soon as one longer than 2 is found. Same with the vertical ones. Your function has a bool signature, ...
62,243,373
62,250,340
Too High CPU Footprint of OpenCV Text Overlay on FHD Video Stream
I want to display a FHD live-stream (25 fps) and overlay some (changing) text. For this I essentially use the code below. Basically it is Load frame (cv::putText skipped here) Display frame if it's a multiple of delay but the code is super super slow compared to e.g. mpv and consumes way to much cpu-time (cv::useOpti...
I now found out about valgrind (repository) and gprof2dot (pip3 install --user gprof2dot): valgrind --tool=callgrind /path/to/my/binary # Produced file callgrind.out.157532 gprof2dot --format=callgrind --output=out.dot callgrind.out.157532 dot -Tpdf out.dot -o graph.pdf That produced a wonderful graph saying that o...
62,243,436
62,243,512
How can I manage inheritance in this case?
I'm trying to create a table in C++ that can contain various data types. Therefore I've created a virtual template class "Column" and derived from it "IntColumn", "FloatColumn", ecc. Then I wanted to create a std::vector to fill it with all the columns. The problem is that if I try to create a vector of Column type I s...
I don't know what your column type should represent, so there are two approaches I'll give you: Describe a column. In that case, you have an array of column descriptors that describe a table and all you need is a "polymorphic container". Using that keyword should get you further. Contain values of a column. In that ca...
62,243,527
62,350,923
How to compile and share two c++ libraries on an android build using CMake
I have custom C++ classes which I want to run on my android app. I am successfully binded my C++ files using CMakeLists. But as my classes uses opencv, I am getting an issue which is obvious fatal error: 'opencv2/core.hpp' file not found Then I tried to add opencv library on my android app, downloaded the open cv andr...
the error you get is telling you that it cannot find opencv include file: #include <opencv2/core.hpp> you need to locate the opencv2 folder, and pass it to cmake as an additional include directory: https://cmake.org/cmake/help/v3.0/command/include_directories.html example: Adding OpenCV to Native C code through CMake ...
62,243,557
62,243,877
Define all pure virtual functions in abstract base class as a varaidaic template
Can a single variadic function handle all base class pure virtual functions? In the case belowSay would override SayGreeting and SayGreetingLocation. class Brain { private: virtual void SayGreeting(std::string greeting) = 0; virtual void SayGreetingLocation(std::string greeting, std::string location) = 0; } cl...
Not directly. Member function templates cannot be virtual and to override a method in the base class the method needs to have the same name and signature. But you can do this: #include <iostream> #include <string> class Brain { private: virtual void SayGreeting(const std::string& greeting) = 0; virtual vo...
62,243,853
62,243,910
Why is the debugger throwing "read access violation. this was nullptr" exception?
First time posting here, so sorry if this is a beginner's problem. I am trying to create a Snake class for a simple game I'm making but the debugger keeps throwing weird exceptions. Every time I debug the program, it takes me into a 'vector' file, points me to a certain line and says: "read access violation.'this' was...
This is because your code has undefined behavior (UB). It can work by coincidence, it can fail without any symptom, or the weirdest things can happen. The debugger takes in general extra care, adding a lot of controls. And it fortunately spotted the use of a null pointer. In fact, this line does not what you thi...
62,244,087
62,245,073
Where is the syntax with class as a parameter in main needed?
This question states that main can be implementation defined with some restrictions. So, I wrote the following C++ code to try out the following signature of main: main.h class MyClass { private: int i; public: MyClass(); inline int geti() { return i; } inline void seti(int i) { t...
The command g++ -o main main.c++ -O3 compiles successfully with warnings This is not successful compilation. You should always use -Werror. If you fail to do so and then decide to ignore the warning and proceed with running the program, it's your own responsibility. You better know full well what you are doing. See t...
62,244,355
62,244,588
Can C++ templates help in defining one-liner 'property' members?
Background: I would like to create a settings class in C++ that mimics .NET's Properties.Settings.Default. For people that don't know what is it, basically it's a singleton class in which you can store application settings. My attempt: The singleton class: so far so good, thanks to C++ Singleton design pattern The prop...
I wouldn't use "Material" and others as template parameter, I mean they are just strings and it doesn't seem necessary to have different types for them. Also I don't know "good old macros", I only know bad old macros ;). You can write a Property: template <typename T> struct Property { std::string category; ...
62,244,617
62,244,740
Storing a variadic template class into std::vector
template<typename...Args> class something { //... }; class storage { template<typename...Args> void build_something_class_obj() { //... } private: std::vector<???> m_container; }; How can I store classes like that? Args may vary so I can't make storage template class
something is a template not a type, but you can only have objects of one type in a vector. Different instantiations of something are completely unrelated, unless you use a base class: struct something_base {}; template<typename...Args> class something : something_base { //... }; And now you can have a std::vect...
62,244,947
62,245,029
Inheritance, overriding, and virtual functions to avoid repeated code
I have three classes, A, B, and C. B and C are derived from A. Both B and C need to implement a method F. The code in B.F() is a subset of C.F(). Is it a good way declare A.F() as a virtual function and define B.F() and C.F()? There would be the same code in 2 methods, which I would like to avoid. What are the other ...
I guess it's not the best thing to do. If you can avoid code rewriting - sure, do it. It would be better to define F() in A, as you've said, with the common code for both B and C, and then override it in C.F(), using A::F() call in overriden function. I mean, with this you can firstly execute parent method A.F(), and ...
62,244,980
62,245,066
Proving assigments in constructor's body are inefficient
I read in http://www.cs.technion.ac.il/users/yechiel/c++-faq/init-lists.html that using initializer lists is more efficient than doing assigment in the body of the constructor, because for example in Fred::Fred() { x_ = whatever; } 1) the expression whatever causes a separate, temporary object to be created, and this...
How can assigment cause the creation of some temporary object inside the constructor? That means that the Construtor would call itself: an infinite recursive call No. The text talks about calling the constructor of the member. With an int it doesn't matter too much, but consider: struct foo { foo() { /* ...
62,245,040
62,248,293
grpc can't find protobuf library
I went over the grpc installation and finished building and installation. Now when I try to: find_package(gRPC CONFIG REQUIRED) I get CMake Error at CMakeLists.txt:15 (find_package): Found package configuration file: /usr/lib64/cmake/grpc/gRPCConfig.cmake but it set gRPC_FOUND to FALSE so package "gRPC" is co...
The problem is actually with the project you use via find_package() and with its package file (/usr/lib64/cmake/grpc/gRPCConfig.cmake in your case). The error message The following imported targets are referenced, but are missing: means, that the package file references IMPORTED targets but they are never defined. The...
62,245,290
62,245,367
How do the ">" and "<" operators work for string comparisons?
In the C++ textbook I'm reading (Programming, Principles and Practice using C++ by Bjarne Stroustrup), there are numerous instances of code snippets in which strings are compared as follows: if (str1 > str2) and then some code. Could someone please explain to me how "bigger than" and "less than" operators work in conj...
The strings are compared lexicographically . The string in which an character is lexicographically greater than the corresponding character in other string will be considered as the greater string. This is known as lexicographical comparison. The lexicographic or lexicographical order (also known as lexical order, ...
62,245,343
62,246,501
WriteProcessMemory not working for some reason
This is all the source code for a program i'm trying to make, and I can't get WriteProcessMemory to work at all. It returns the correct messages, saying that everything went successfully, but nothing actually changes in the game. Does anyone know of a fix? #include <iostream> #include <Windows.h> using namespace std; ...
You're passing a null pointer to WriteProcessMemory for the third (lpBuffer) parameter. You have to pass the address of the actual value, not the value itself. If you want to write an integer value, try this: DWORD val = 0; // or 999? WriteProcessMemory( pHandle, static_cast<LPVOID>(playerAddr + hlthOffs), &val...
62,245,586
62,245,696
Read all vector elements as one integer in C++
I have this deque and this vector: std::deque<uint8_t> Time(3); std::vector<uint8_t> deque_buffer(3); I do some push_backs: Time.push_back(1); Time.push_back(2); Time.push_back(3); I copy the data to the vector for(int i=0; i<3; i++) { deque_buffer.at(i) = Time.at(i); } I want to read all the vector data and sto...
Here is what you can do: (sample code on how to "merge" vector elements). #include <iostream> #include <vector> using namespace std; int main() { vector<unsigned char> vec = {1,2,3}; int res = 0; for (const auto &val:vec) { res = (res << 8 ) | val; } printf ("0x%x\n",res); prin...
62,245,622
62,245,685
constexpr constructor must initialize direct base class (Visual Studio)
I have someone else's code that I shouldn't alter: struct Parent { int thing1, thing2; }; and want to make my inherited class usable with constexpr: struct Child: public Parent { constexpr Child() {} //error constexpr Child(int t1, int t2) { thing1 = t1; thing2 = t2; } ...
Until c++20, your Parent class is not constexpr constructible, since there are no default initializers for the data members. I believe it's a gcc bug that allows it to compile. You can make Parent constexpr constructible like this: struct Parent { int thing1{}, thing2{}; }; // provide default values for members Note...
62,245,683
62,247,619
Qt : how to action_triggered then use QMouseEvent?
I'd like to do something like this, even though I understand this is not how it works. I'm not really good with QMouseEvent, void MainWindow::on_addState_triggered(QMouseEvent* event) { qDebug() << event->pos(); if (event->buttons() == Qt::LeftButton) { newBoard.drawState(event->x(),event->y()); ...
Alright, the way I imagine I can do it is a little bit ugly but it "works". Maybe there is a cleaner way to do the following : void MainWindow::on_addState_triggered() { drawAddState=true; } void MainWindow::mousePressEvent(QMouseEvent *event) { if(drawAddState==true) { ...
62,245,753
62,245,834
Specialization of a template function for a specific type
Consider this function template returning the maximum of two type values: template<typename T> T max(T a, T b) { return a ? a > b : b; } Is it possible to define a separate behavior for a user defined type the same way as we could do with classes? something which might look like this? template<> Entity max<Entity>...
Your code has some problems. I have fixed them in the below example code: struct Entity { bool operator >(const Entity & other) { return x > other.x; } int x = 0; }; template<typename T> T max(T a, T b) { return a > b ? a : b; } template<> Entity max(Entity a, Entity b) { std::cout << "this is...
62,246,116
62,246,533
C++ : Static instances of class
I'm trying to create objects of this class, but storage duration should be static: The program must create exactly storage_count (not more, not less) objects of type anywhere, one after another, starting from index argument value 0, and progressing up to and including storage_count - 1. class anywhere { public: any...
I'll first say that, indeed, you might be presenting us with an "XY problem", and what you actually need is something else than a runtime-determined number of "static" instances of a class. Regardless: It seems you want to implement something between the Singleton Pattern (single instance) to the Multiton pattern (mult...
62,246,641
62,246,768
How to save a change to an array in c++
I have to make a program that reads the number of seats and stores it in a two dimensional array. The empty seats is hashtag and if the user buys a seat it becomes *. The odd rows have 15 seats and even have 20. When I purchase a seat, it puts the * on the seat but when I buy another seat it removes it and puts * on t...
In Show_Chart, you are doing: ab[i][j] = EMPTY; for every i and j. This means the old values are erased every time you call this function. Remove that line to avoid overwriting saved seats. To initialize all the seats before asking for any user input, you can do this in main before entering the while loop: for (int i ...
62,246,778
62,246,910
Leetcode 27. Remove Element: Execution time for the same submission differs drastically
Leetcode problem: Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what yo...
LeetCode doesn't claim to offer a hermetic and consistent environment for running your programs. You can imagine that they probably have hundreds or thousands of machines on which they run submissions. Some of them they probably bought five years ago, some are brand new, some are temporarily running more submissions th...
62,247,599
62,247,731
How do we use nested if else with #define preprocessor
#define len(a) if (a == 8) 1 \ else if (a == 3) 0 \ else -1 this code is just an example how do we use nested if else. I don't want to use ternary operator as in that case i can't use else if statement.
inline __attribute__((always_inline)) int len(const int a) { switch(a) { case 8: return 1; case 3: return 0; } return -1; }
62,248,160
62,266,133
How do I prevent libserial to eat up characters like 0x0A, 0x0D, or 0x0F coming from my serial device?
When communicating with a serial-over-USB device (a GNS FM9 receiver for getting road traffic alerts) by using libserial's SerialStream object, I found out that not all characters coming from the device are in fact being read. This is what I always get served: 3F 00 56 08 37 3F When using the same device with the RDS ...
OK, I opened an issue with the maintainers of libserial and got the answer that the C++ std::iostream (NOT even LibSerial::SerialStream!) kicks out whitespace characters by default. CR, LF, and FF are regarded as such. They proposed me this solution: SerialStream tmc_receiver_handler ("/dev/ttyUSB0", ios::in | ios::out...
62,248,186
62,248,216
Change member identifier of a type during runtime in C++
Is it possible to change the name/identifier of a member of a user defined type during runtime, so that something like the following would be possible. file.json: "{name: "Peter", nums: [10, 13, 1]}" JSONDocument d("file.json"); // Parses JSON File d.name.key = "other_key"; d.other_key = "Alfred"; d.writeToFile("file.j...
No, you cannot create members at runtime in C++.
62,248,220
62,249,291
How to know if a string is inside of a another by skips none or some letters ,
I'm trying to write a program to check if string is inside of another in any way? I don't mean the contain method. Something like string "AgBgC" contains the string "ABC" or for another one like "browndcodw" contains "brown" and "cow". However, "browndcodw" DO NOT contain "woc", since they are not in order. I first usi...
The algorithm is failry simple. Go through all characters of the input string. Check, if it does match with the first character of the search string. Increment the index in the search string. Next compare to the second character and so on and so on. If all characters from search string have been match, then the result ...
62,248,481
62,263,735
How to use type-level functions to create static types, dynamically?
In TypeScript, there are type-level functions that allow creating new types based on given literal types/specifications (see Mapped Types, Conditional Types, etc.). For instance, here is such a function, let say provided by a lib author: type FromSpec<S> = { [K in keyof S]: S[K] extends "foo" ? ExampleType : never ...
Given Scala is one of the tagged languages, here is a solution in Dotty (aka. Scala 3). Take this with a grain of salt, since Dotty is still under development. Tested with Dotty version 0.24.0-RC1, here is a Scastie that proves this actually compiles. Scala doesn't have the same sort of built-in type machinery as TypeS...
62,248,750
62,261,959
boost::locale::normalize() returns empty strings with ICU backend
Reduced problem code: #include <iostream> #include <string> #include <vector> #include <boost/locale.hpp> std::string fold_case_nfkc(std::string_view str) { return boost::locale::normalize(boost::locale::fold_case(std::string(str)), boost::locale::norm_nfkc); } std::string normalize_nfkc(std::string_view str) { ...
It could be your terminal emulation playing tricks. On my Linux box, I get similar output when running from inside Vim, but running it through e.g. od or xxd shows that the bytes are there, and when redirecting to a file, it shows up correctly in an editor. Note though that on my c++20 compiler, the char8_t const* str...
62,249,255
62,249,293
string is appending from previous statements
I am going through C++ language code. and found an interesting thing. See the code below - void CharsAndStrings() { char s[] = "vaishnav"; char s1[4] = {'s','h','i','v'}; char s2[4] = {static_cast<char>('zz'),'y','x','v'}; // warning - Multi-character character constant printf("\n"); printf("%s\n",...
For this declaration: char s1[4] = {'s','h','i','v'}; calling: printf("%s\n", s1); invokes undefined behavior (UB), since printf requires the argument used by %s to be null-terminated. UB means anything can happen. In your case, it appears the compiler placed the 3 arrays in the order s2, s1, and s, so printing out o...
62,249,256
62,249,437
Is it possible to use std::make_unique in a class constructor and `this` pointer?
I am trying to use unique_ptr instead of raw pointers for components that are assigned to an actor class. #include <iostream> #include <memory> #include <utility> #include <algorithm> #include <vector> class Component; class Actor { public: void AddComponent(std::unique_ptr<Component> component) { ...
There are at least three issues here. There are various syntax errors (missing declaration of Component before the definition of Actor, typos, ... I'll ignore them now they are mentionned. The if you have any pointer, you can build a unique_ptr from it which will handle the lifetime of the object. That's not made with...
62,249,444
62,265,393
How to implement bubble sort in C++?
I have tried to implement bubble sort on singly linked list (by changing pointers). I am wondering what's wrong with this solution. It seems to be clear and should work, but I am beginner in C++, so I guess that I did somewhere mistake which I cannot spot. Here is code: #include <iostream> using namespace std; struct...
In practice, you don't swap the nodes, only the pointers to the next nodes. In particular, you don't modify the pointers that were pointing to the nodes that you try to swap. For example, if a -> b -> c -> d and you want to swap b and c, then a should point to c now, not to b. Moreover, cshould point to b, etc. There...
62,249,479
62,249,509
Does c++ move semantics save resources in every situation?
I know that C++ move semantics is supposed to save processor power and memory since Move::Move(Shallow&& source) noexcept // Move constructor { data = source.data; // Assume data is an array of size = size and all initiated to a user specific value size = source.size; source.size =0; source.d...
Is there any benifet using move constructor if we assume that data is just a simple integer or even a very large uninitialized array No. This move constructor seems pretty much the same as just calling copy constructor with a shallow copying. It is. "Moving" only works to transfer ownership of resources, and you ca...
62,249,520
62,249,521
What is the difference between chrono::month and chrono::months
What is the difference between the C++20 chrono types/values month{7} and months{7}? Isn't it confusing to have two such similar names?
Yes, it can be confusing to have both month and months when first encountering this library. However there are consistent naming conventions in this library to help reduce that confusion. And the benefit is having a clear separation of distinct semantics while retaining short intuitive names. months All "predefined" ...
62,249,776
62,249,976
C++: operator precedence from a Stroustrup example
Stroustrup C++ 4th Ed Page 197 has the following examples, which result in an incrementing stream of characters printed until null and not "abc". Questions: how is the ++*p being evaluated? ++ and * are the same precedence and evaluation right-to-left, therefore it's my understanding *p is evaluated first, leading to...
Yes, you are right about the precedence and the associativity. This expression: ++*p; is parsed as ++(*p); i.e. first the indirection of p is done, and then the value returned is incremented. This means that in the while loop: while (*p) cout << ++*p; the pointer p is never actually incremented. This results in...
62,249,985
62,250,254
C++ Linear search algorithm, determining the number of elements in array
This code is from the Geeks for Geeks Algorithms section and i do not understand this part int n = sizeof(arr) / sizeof(arr[0]); In the main function, specifially why the division with sizeof(arr[0]) which would lead to half the number of actual elements in the array. Hope someone can explain me this. // C++ code to...
Let's consider the declared array int arr[] = { 2, 3, 4, 10, 40 }; As the size of the array is not specified then the number of elements in the array is equal to the number of initializers. It is not difficult to count the number of elements. It is equal to 5. So the array consists from 5 elements of the type int. Th...
62,250,263
62,250,346
C++ Closing Socket to initiate new connection
I am new to socket programming in C++. I've made a simple port scanner that scan one port and it worked as expected. Now I'm trying to scan multiple ports So I create a socket and started iterating over an array of ports, BUT all ports appears as closed. My Question is: Do i have to close socket in order to scan anoth...
So apparently i must close the socket between each connection, Thanks to Some programmer dude So I changed my code now I create/close socket inside the for loop. Example below: for (int i = 0; i < 7; i++) { // Creating the socket // ------------------- int sock_fd = socket(AF_IN...
62,250,321
62,251,201
How do I both store unicode characters and output them to a file?
This is my input function: template <typename T> T getUserInput(std::string prompt = "") { T input; std::cout << prompt; if constexpr (std::is_same_v<T, std::string>) { std::getline(std::cin, input); } else { std::cin >> input; std::cin.ignore(std::numeric_limits<std:...
If you are using Windows you can use _setmode: #include <fcntl.h> #include <io.h> #include <iostream> #include <string> #include <fstream> template <typename T> T getUserInput(std::wstring prompt = "") { T input; std::wcout << prompt; if constexpr (std::is_same_v<T, std::wstring>) { std::getli...
62,250,579
62,251,087
Calling override of virtual function is causing a segmentation fault
I am trying to override a function but end up with a segmentation fault. I followed some Tutorials and now I'am not able to find the origin of the segmentation fault. I use 1 header and 1 cpp file. Update The Reason is that I want to Make multiple Command like print and instatiate different commands and call the Execut...
The problem is not related to your virtual functions, or to the override. It is simply that you are using the address of an object that no longer exists. In the following code block: Command* command; if(1){ // if is updated Print print; // and reason for seg fault ...
62,250,781
62,250,855
Not waiting when open a txt file with notepad C++
When I open a .txt file with Notepad in C++, my program does not continue until I close Notepad. How can I have my code continue instead of waiting like this? Code: string a; string topicName; a = "C:\\Hello\\Hi\\Hi.txt"; topicName = "notepad \"" + a + "\""; system(topicName.c_str());
Use popen instead of system. #include <iostream> int main() { popen("notepad.exe", "r"); std::cout << "I'm still running!" << std::endl; } I compiled this with g++ on Windows 10 64-bit and it works.
62,250,829
62,252,782
Invalid memory address passed when calling custom DLL function in Microsoft Access SQL
I would like to call a custom function Simil(LPCWSTR a, LPCWSTR b) for computing the Ratcliff/Obershelp string matching algorithm in Microsoft Access SQL (2019). The function resides in Simil.dll. The following is the dllmain.cpp file that defines the entry point and which I compile using the Nuwen MinGW Distro. #ifdef...
I found a workaround. I used a User Defined Function (UDF) in VBA that I was able to call from the SQL context. This function needs to reside in a module for it to be available in SQL. Function fnSimilWrapper(a, b) fnSimilWrapper = fnSimil(a, b) End Function
62,250,834
62,252,260
Namespace refactoring in C++
I am refactoring namespaces of small part of a large project. So I have refactored following 2 files which had Oldname as the namespace to x::y::z. file1.hpp namespace x::y::z { Class abc { public: void funcA(type1 arg1, type2 arg2) } file1.cpp #include "file1.hpp" namespace x::y::z { void abc::funcA(type...
From cppreference.com (emphasis added): Out-of-namespace definitions and redeclarations are only allowed after the point of declaration, only at namespace scope, and only in namespaces that enclose the original namespace (including the global namespace) and they must use qualified-id syntax Given this rule, the defin...
62,250,841
62,250,873
struct members gets cleared when accessed
First off, I'd like to apologize if my explanation is bad, English isn't my first language. I'll be happy to try and explain better if you didn't understand what I wrote here. I'm trying to solve this problem. I have an array of struct (Workshop) which is a member of another struct (Available_Workshops). My issue is th...
In this function, you are returning a pointer that stores the address of a local variable: Available_Workshops* initialize(int s[], int d[], int n) { Available_Workshops aw; Available_Workshops *u; // ... u = &aw; return u; }; Dereferencing the pointer returned by this function invokes undefined be...
62,250,963
62,251,069
MSVC __debugbreak() when used with openGL error callback produces no callstack
I'm using openGL's more recent glDebugMessageCallback convention to help with my openGL error handling. What I want to be able to do is have a way to see what function causes the openGL error. I figured the only way with the callback method would be to insert a breakpoint into my callback function so that when an error...
You have to enable synchronous debug output: glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); If the Debug Output is produced asynchronously, then the debug callback function may be called from a thread other than that in which the commands are execute. See Logging and glEnable.
62,250,967
62,251,129
comparison between nullptr and boolean
While I was experimenting with null pointers, I tried to write a code to check whether a pointer was null or not: #include <iostream> using namespace std ; int main(){ int *p = 0; if(!p == true){ cout<<"nullptr\n"; } else{ cout<< "no\n"; } return 0; } which worked fine without a...
This has to do with the difference between implicit and explicit conversions, and the special status of the bool type with respect to explicit conversions. Generally, while you can convert between integers and pointers (either direction), you can only do it explicitly with a cast. No cast means no conversion and you g...
62,250,969
62,294,958
concurrent program using simple two phase locking
Problem: I want to compute concurrently some equations using the so-called two-phase locking concept. My approach: Create an array that will update in real time values of each variables. I am a bit stuck in the way I should create threads , apply mutex/semaphore on the algorithm to do it concurrent. Input (of course, I...
1. Building a dependency graph between the assignments I take it your goal is to compute as much assignments in parallel as possible while obtaining the same result as if you were sequentially computing the assignments one after another. To identify what can be done in parallel, I would suggest building a dependency gr...
62,251,112
62,251,142
Getting Error Message in Eclipse: "error: no match for 'operator='"
I've a Problem with C++ in Eclipse and i'm a newby. I get the following Error Message: ..\src\Aufgabe5.cpp:16:23: error: no match for 'operator=' (operand types are 'Stammbaum' and 'Stammbaum*') I think the problem is the initializition. But i don't how to fix this. Main Class: #include <iostream> #include "S...
Replace Stammbaum baum = new Stammbaum(); with Stammbaum baum; baum is just a regular variable. There is no need to use new. Also (common beginner mistake), don't do this Stammbaum baum(); because that makes baum a function prototype.
62,251,151
62,251,217
std::decay and removing const qualifiers
I'm trying to understand the workings of std::decay a little better. Per cppreference it's supposed to remove const and volatile classification from the type as part of other transformations it does. However, below function displays "False", "True" vs. "True", "True" as one might expect. Can someone please clarify why ...
std::decay_t would remove the const from the pointer, had it been const, not the type it's pointing at. That is, a char* const would decay into a char*.
62,251,262
62,259,086
noexcept swap and move for classes with mutexes
In general it is a good practice to declare a swap and move noexcept as that allows to provide some exception guarantee. At the same time writing a thread-safe class often implies adding a mutex protecting the internal resources from races. If I want to implement a swap function for such a class the straightforward sol...
On POSIX systems it is common for std::mutex to be a thin wrapper around pthread_mutex_t, for which lock and unlock function can fail when: There is an attempt to acquire already owned lock The mutex object is not initialized or has been destroyed already Both of the above are UB in C++ and are not even guaranteed to...
62,251,386
62,256,400
converting getrusage from linux to windows
I'm converting a linux C++ code to Windows and I'm struggling with a replacement for this getrusage method. 1. timeval CPUStopwatch::now_timeval() const { 2. rusage ru; 3. getrusage(RUSAGE_SELF, &ru); 4. return ru.ru_utime; 5. } How can I parse this line (3) to a working windows line? I've i...
In PostgreSQL source code you can find : /* * This code works on: * solaris_i386 * solaris_sparc * hpux 9.* * win32 * which currently is all the supported platforms that don't have a * native version of getrusage(). So, if configure decides to compile * this file at all, we just use this v...
62,251,450
62,251,814
C++: struct initialization in presence of constructor
I have question on C++ behavior when initializing structures using a list. For example, the following code behaves the same in C and C++. The list initializes x: struct X { int x; }; int main(int argc, char *argv[]) { struct X xx = {0}; return 0; } Now, if I add a constructor, I find out through tes...
The following syntax: X xx = {0}; is just a form of copy-list initialization. This has the effect of invoking the constructor of X, as you observed. The name of this initialization comes from the fact that this looks like a list is being copied, but just the regular constructor is invoked. Note that this will only co...
62,251,497
62,252,164
Holding or passing around non-addressable-functions since C++20
C++20 added the rule of addressable function 16.5.4.2.1 [namespace.std]/6: -- emphasis is mine -- Let F denote a standard library function ([global.functions]), a standard library static member function, or an instantiation of a standard library function template. Unless F is designated an addressable function, ...
This rule comes to us from P0551. The wording here is "unspecified (possibly ill-formed)" - not undefined behavior, not ill-formed NDR, nothing like that. Now, the library is largely designed, specified, and implemented, around direct use of APIs. The library specifies what x.foo(y, z) means and the implementation has...
62,251,525
62,252,031
Segfault with custom new/delete and Qt in C++
So I wanted to play around with custom new/delete a bit and followed this answer. I have a MWE that works nicely, but once I include a Qt header (even without using it), all I get is a segmentation fault. The segfault occurs before entering main() and I don't know whats going on. Here is the code: /* main.cpp */ #inclu...
It's a bad idea to access cout from inside a global operator new, since cout may not be initialized yet. libQt5Core has many static initializers that run before main(), and some of them allocate memory using operator new. Indeed it seems QMutex is initialized before cout, and so it crashes on cout <<. $ gdb ./a.out (gd...
62,252,076
62,252,088
C++: array<> too many initializers
The following code is returning the compilation error below. I'm stuck understanding how there are too many initializers. This code works using vector<X>. Does anyone know why the error is being reported and how to resolve? Thanks #include <iostream> #include <array> using namespace std; struct X { int x, y; }...
Try array<X,2> a0 = {{{0,1}, {2,3}}}; Note the extra set of braces. It seems a bit odd but it's this way because the only member of array is the actual array: template <class T, size_t N> class array { T val[N]; // ... }; The constructors are all implicitly defined so that array ends up being a trivially con...
62,252,553
62,252,593
C++ pointer array to specific location in char array
I had a problem with a Project. It is generating C++ code to edit a file but there is one thing I'am stuck with. The file is stored inside an char array and I want to have a pointer array to a specific position inside the char array but I only get a pointer to one character of the array. What I want is something like t...
Your immediate problem can be solved like this: #include <cstring> // std::memcpy char array[] = "Hello, how are you?"; char* ptr = &array[7]; std::memcpy(ptr, "who", 3); // copy 3 chars from the character literal "who" to ptr std::cout << array << std::endl;
62,252,616
62,252,650
No instance of constructor "Hourly::Hourly" matches argument list and Error code C2664 on the same line
I am quite lost on how to solve my question. I have read many posts and it's just not clicking on how they apply to my problem and as I look over my code I can't seem to see what is broken. Main: Hourly hourly("John", "Smith", "12345", 123456789, 42.0, 45.5); //error's occur on john and I'll add the hourly class as ...
The issue appears to be the phone number, which you're passing to the constructor as: 123456789 Your constructor expects a string, but without quotes, this is an integer. Pass it as follows and you shouldn't have an issue: "123456789"
62,252,706
62,252,862
Printing original array and changed array
I'm doing an exercise where I have to print the original array and add more elements to the array and print those too. So the output should be Original array: [10, 20, 30] After append values to the end of the array: [10 20 30 40 50 60 70 80 90] The second part is printing but for some reason, the original array eleme...
If you want to use a for loop to print elements of an array, you have two options. You can use a traditional for loop with a loop counter like i. This is usually preferred if you want to iterate over a partial range. You usually compare the loop counter with the last index. On the other hand, if you are going to iterat...
62,253,017
62,253,108
Rference to non-static member function must be called
The following piece of code aims to sort a 2D vector on the basis of the first column, but it returns an error : Line 8: Char 43: fatal error: reference to non-static member function must be called sort(people.begin(),people.end(), sortfunc); ^~~~~~~~ 1 error g...
As suggested by @SevastianHoffmann , lambda function does the job. class Solution { public: } vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(people.begin(),people.end(), [](const vector<int>& v1, const vector<int>& v2){ return v1[0]<v2[0]; }); return peopl...
62,253,409
62,253,661
Is using std::memcpy on a whole union guaranteed to preserve the active union member?
In C++, it's well-defined to read from an union member which was most recently written, aka the active union member. My question is whether std::memcpying a whole union object, as opposed to copying a particular union member, to an uninitialized memory area will preserve the active union member. union A { int x; ...
The assignments you have are okay because the assignment to non-class member a.y "begins its lifetime". However, your std::memcpy does not do that, so any accesses to members of a2 are invalid. So, you are relying on the consequences of undefined behaviour. Technically. In practice most toolchains are rather lax about ...
62,253,841
62,253,875
(C++) Total number of elements in a multidimensional vector
I've learned that checking the sizes of one-dimensional vectors is an easy task, because one can just write #include <iostream> #include <vector> int main(){ vector <int> v = {1, 2, 3, 4}; cout << v.size() << endl; cout << sizeof(v)/sizeof(int) << endl; } The output is, as expected, 4. However, when I try...
In your 2nd example, v is a vector of vector<int>s, so v.size() reports 3 sub-vectors instead of the number of integers. std::vector::size() does not recurse, you have to do this yourself: std::size_t sum = 0; for (auto &&i : v) { sum += i.size(); } // return sum;
62,253,972
62,254,015
Is it safe to reference a value in unordered_map
For example: #include <unordered_map> class A{}; std::unordered_map<unsigned int, A> map {{0,{}},{1, {}},{2, {}}}; int main() { A& a1 = map[1]; // some insert and remove operations ( key 1 never removed) // .... } Is it safe to still use a1 to reference the value which key is "1", after a lot of insert operati...
Yes, it is safe. From the standard: 22.2.7 Unordered associative containers [unord.req] The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. The erase members shall invalidate only iterators and references to the eras...
62,254,385
62,254,398
Why is the calculation in the subtotal of this program incorrect?
I am trying to create a C++ program that calculates sales tax for a customer and displays a receipt. For example, if you entered 10 as the first sale amount and the tax rate is 0.0825 it should display the total tax as $0.83. Why does my subtotal and total due at the end of the receipt display $10.82 when it should be ...
setprecision(2) doesn't mean "round to 2 decimal digits," it means "display 2 decimal digits." The actual value is 10.825 but you're only displaying the first two decimal digits. If you want to round away from the midpoint, you need to use one of the rounding functions on the result. Since you want to round to the sec...
62,254,389
62,254,586
Inconsistant outputs on printing values
In this program I am cloning a graph in c++. This is the question that i am coding. This is my program and following it the issue and problem area. #include <vector> #include <unordered_map> #include <queue> #include <iostream> using namespace std; #define neighbours neighbors // Definition for a Node. class Node { pu...
umap[value] = newNode; exhibits undefined behavior, by way of accessing an uninitialized variable value. In practice, value contains some garbage that happens to sit on the stack. Changes to seemingly unrelated parts of the program affect the contents of the stack, and thereby the initial value of value, and ultimately...
62,254,777
62,254,925
Why am i getting a SIGABRT error in this code
I have writen this code in CodeChef but it constantly gives me runtime error called (SIGABRT). I have been trying to resolve this issue yet there is no result. I have reduced memory to my fullest. I need help. There are N students standing in a row and numbered 1 through N from left to right. You are given a string S w...
I fully aggree with @Sam Varshavchik However, I tried you're code with following input: try $ ./test input 2 input ha output 0 input lo output 0 => no crash try $ ./test input 2 input ha output 0 input lo output 0 => no crash try $ ./test input 2 input a terminate called after throwing an instance of 'std::out_of_r...
62,254,786
62,255,796
is there a standard way to calculate number of days between two asctime() values
like number of days between Mon Jun 08 09:21:39 2020 and Mon Jun 18 07:11:29 2020 is 10. otherwise, I am thinking of creating a function to calculate difference by using Jan=31, Feb=28, ... and so on but that would be lengthy. Is there a direct/better way to do the same.
Here is some code that shows one way to do it, by first converting the ASCII strings into struct tm's, then converting the struct tm's into time_t's, and then calculating the difference (in seconds) between the two time_t's and finally converting that into days: #include <stdio.h> #include <stdlib.h> #include <time.h> ...
62,254,915
62,256,419
Generate tag file only for C++ files(.h, .cpp, .cxx, .c)
I am working in a code base of C/C++ files on Linux. I want to jump to definition of a function when pressing Ctrl [ inside vim . For this I am generating a tag file by running ctags --language-force="c++" -R * but it is scanning .xml, .js, and other non C++ files. As a effect, the ctags command is taking more time to...
Try --languages option instead of --language-force option: ctags --languages="c++,c" -R *
62,255,094
62,272,039
OnComponentBeginOverlap.AddDynamic says no instance of the function template matches the argument list?
In a cpp file, my use of: BoxComp->OnComponentBeginOverlap.AddDynamic(this, &AAICharacter::OnBoxOverlap); BoxComp->OnComponentEndOverlap.AddDynamic(this, &AAICharacter::OnBoxEndOverlap); got the following error: cannot convert argument 2 from 'void (_cdecl AAICharacter::*)(AActor*,UPrimitiveComponent*,int32,bool,const...
The error is fairly self-explanatory. cannot convert argument 2 from 'void (_cdecl AAICharacter::*)(AActor*,UPrimitiveComponent*,int32,bool,const FHitResult &)' to 'void (_cdecl AAICharacter::*)(UPrimitiveComponent*, AActor*,UPrimitiveComponent*,int32,bool,const FHitResult &) The second argument in the indicated line...
62,255,234
62,255,777
I want to play only one mp3 file in loop Qt
I have only one mp3 file paying in background. I want that mp3 file to played till I close the application. What I am facing is that the mp3 file is played for only once and then stops. I want it to be played again. Find sample code below Code: QMediaPlayer *music = new QMediaPlayer(); music->setMedia(QUrl("qrc:/sounds...
Simply do it by connecting signals and slots as follows: connect(music,&QMediaPlayer::mediaStatusChanged,music,&QMediaPlayer::play);
62,255,274
62,255,463
Could somebody tell the reasons why use such code in the definition of a member function: `Base::fool(T1 *pub, T2 *info){ (void)pub; (void)info;}`
The related procedure code is provided below.I often see such kind of code in open source projects which can run both on Linux and Windows. Somebody told me that it is to avoid compiling warning. Is it really the case? class Base { public: virtual void on_publication_matched(Publisher* pub, PublicationMatchedStatus...
Let have a look at the first two examples. They define a function that simply does nothing. The difference lies in the void cast (void)pub; (void)info; which is typically used to avoid the unused-variable warnings by the compiler. It does a cast to void. The expression is discarded afterwards, so effectively e.g. (voi...
62,255,734
62,255,850
Why is my virtual function not assigning values?
I am trying to use a virtual function to calculate area of rectangle and triangle like this:- #include<iostream> using namespace std; class Shape{ public: int width; int height; void get(){ cin>>width; cin>>height; } virtual void area(){ cout<<"Calculates area"; } }; class ...
The problem is that the width and height are assigned to the shapeObj variable Shape shapeObj; shapeObj.get(); but you are using the trObj and rectObj variables to calculate the area. Triangle trObj; Rectangle rectObj; ptr=&trObj; ptr->area(); ptr=&rectObj; ptr->area(); Try this instead int main() { Triangle trOb...
62,255,803
62,255,995
namespace noob questions: two cpp files sharing the same namespace have the same variable
namespace noob questions I have two files in the same binary. // class1.cpp namespace A { const std::string k1 = "abc"; } // class2.cpp namespace A { const std::string k1 = "bcd"; } They are not declared in header file. Won't they collide? I tried to compile and it can compile. I should put them to unnamed namespa...
It is because const implies internal linkage. You will get the expected error about duplicate symbols if you defined A::k1 as non const.
62,256,209
62,257,803
Using timer with zmq
I am working on a project where I have to use zmq_poll. But I did not completely understand what it does. So I also tried to implement it: zmq_pollitem_t timer_open(void){ zmq_pollitem_t items[1]; if( items[0].socket == nullptr ){ printf("error socket %s: %s\n", zmq_strerror(zmq_errno())); r...
zmq_poll works like select, but it allows some additional stuff. For instance you can select between regular synchronous file descriptors, and also special async sockets. In your case you can use the timer fd as you have tried to do, but you need to make a few small changes. First you have to consider how you will invo...
62,256,913
62,259,463
How to read unicode from oracle database c++
I am trying to select string written in Arabic letters from oracle database using C++ The problem is i read Chinese characters instead I am using their globalization guide Environment* env = Environment::createEnvironment(" US7ASCII","OCCIUTF16"); Connection* con=env->createConnection("","",""); Statement* stmt= con->c...
Try with this code modification: Environment* env = Environment::createEnvironment("AR8MSWIN1256","OCCIUTF16");
62,257,202
62,257,258
How to debug C++ program in VSCode with file added
I work fine with debugging without adding a file, however, I do not know how to deal with it with file added. The commands are as follows: g++ -g --std=c++11 lab1.cpp -o lab1 ./lab1 ./tests/extracredit-test-0.txt The following are my task.json and launch.json. I wonder how to modify it to support debugging with the f...
How to debug C++ program in VSCode with file added You are using GCC. Consider upgrading to GCC 10. Then compile with g++ -Wall -Wextra -g (all warnings and DWARF debug information) and use the GDB debugger. You could be interested by the static analysis facilities introduced in GCC 10, and/or by tools such as Frama-...
62,257,799
62,258,039
Is this allowed at runtime? How do you extract the top N elements of a stack-like thing?
I'm trying to do something like this - copy the top N elements of the stack to an array. I want to use it to define the invokevirtual, invokespecial, invokestatic, invokeinterface, and invokedynamic instructions for a Java Ahead-Of-Time Compiler. The stack is a linked list and __pop() unwinds and returns the top of the...
Will my implementation crash at runtime? Maybe. You exhibit Undefined Behaviour at least in: jvalue* __extract(int count){ jvalue extracted [count]; for (int i = 0; i < count; i++){ extracted[count - i - 1] = __pop(); } return extracted; } Your function returns a pointer to a local variable w...
62,258,154
62,437,725
Leetcode 1366: Heap Buffer Overflow
Here's my code for Leetcode 1366, and it doesn't work for some test cases such as ["XYZ","XZY"] I'm pretty sure about the algorithm, i.e. using a vector of pairs of characters and vectors as a map. There's something wrong with the code, in my opinion, not the algorithm. class Solution { public: string rankTeams(vec...
There is a bug in this question's "Online Judge", which I guess LeetCode should fix it. Apart from that, the following solution is an accepted one and is much simpler: class Solution { public: string rankTeams(vector<string> &votes) { vector<vector<int>> count_map(26, vector<int>(27)); for (char &c...
62,258,218
62,259,098
compile time indexer for enum classes
how would you create a kind of compile time indexer that given a group of enum classes is able to correctly create a unique identifier. Template<class... Args> struct Indexer { template<class T> Indexer(T value) { value_ = someconstexprfunction<T>(value, interDistance_); } int enumInternalIndexCode() { /* ... *...
#include <type_traits> #include <cstddef> template <typename T, typename... Ts> struct Index; template <typename T, typename... Ts> struct Index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {}; template <typename T, typename U, typename... Ts> struct Index<T, U, Ts...> : std::integral_constant<std::...
62,258,324
63,343,888
Retrieving data from af::array via host() results in wrong data
When trying to retrieve data from an af::array (arrayfire) from the device via host(), my output data on the host is wrong (i.e. wrong values). For testing that, I wrote a small code sample (based on https://stackoverflow.com/a/29212923/2546099): int main(void) { size_t vector_size = 16; af::array in_test_arr...
The datatypes between arrayfire and C are in conflict. For float use: af::array in_test_array = af::constant(1., vector_size), out_test_array = af::constant(0., vector_size); float *local_data_ptr = new float[vector_size](); For double use: af::array in_test_array = af::constant(1., vector_size, f64), ...
62,258,657
62,260,271
Write a dynamic array
I want to write a program that can use a dynamic array. A size is to be passed via the constructor and as soon as this size is reached, a new array is generated in which the previous values are copied into it. For this, I overloaded the [] operator. The program seems to work at first glance. But after I tried to impl...
first , this code didn't call the overloaded [] operator function , its just using default operator [] of type T array , and it never allocate any memory , you can output at allocate memory position dArray.dynamischesArray[i]=i; cout << dArray.dynamischesArray[i] << "\n"; and there it some error logic in the overloa...
62,258,744
62,259,338
QTreeView doesn't work outside the main function
I'm trying to generate a simple QTreeView inside another widget (QMainWindow). The following code works as expected and displays the tree-view, int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow w; w.show(); QString rootPath = "C:/"; QFileSystemModel model; model.setRootPath("");...
QFileSystemModel model; and QTreeView tree; Are local stack variables, meaning they will be gone once you exit the create_tree function. You can solve your issue by creating them on the heap by using new, which will keep them alive. Be careful, that you need to think about how you destroy these created objects. The Q...
62,258,749
62,261,699
Different constructor calls depending on compiler
Running the code supplied in this question: Why move return an rvalue reference parameter need to wrap it with std::move()? #include <string> #include <iostream> #include <utility> template<typename T> class TD; class Widget { public: explicit Widget(const std::string& name) : name(name) { std::cout << "W...
MSVC has implemented P1825R0 - More implicit moves As can be seen in the Microsoft C++ language conformance table section of the Visual Studio C++ documentation, this is Visual Studio implementing P1825R0: Merged wording for P0527R1 and P1155R3 (more implicit moves), as of Visual Studio 2019 version 16.4, compiler M...
62,259,044
62,259,219
Get current time in C++\{C}
How can I get the current time, in C++, without C libraries? C has <ctime>. I am trying to avoid C libraries, for no good reason.
You can use std::chrono::system_clock::now() from chrono library. It returns a time point representing the current point in time.
62,259,109
62,264,096
Avoiding preprocessor for mutual exclusive function call in C++20
Please consider the following little function. It provides compiler abstraction for breaking the debugger programmatically: inline constexpr void BreakDebug() { #ifdef __GNUC__ __builtin_trap(); #elif defined _MSC_VER __debugbreak(); #endif } I would like to rewrite the function and replace the pr...
Apparently, those builtin functions can also be turned into dependent name. I checked this here. So the usual trick that consists in making potentially ill-formed code dependent works: enum compiler_t{ gnu, msvc }; inline constexpr compiler_t compiler = #ifdef __GNUC__ compiler_t:: gnu; #else compiler...
62,259,278
62,259,323
Can you initialise in the class and in the constructor and is that correct?
Considering the code below: #include <iostream> class tester { public: tester(){} explicit tester(double val) : m_a(val) // I assume this now overwrites the "default" initialise value? {} double m_a {1.123}; // Default constructor value? }; int main() { tester t1; tester t2(2.456); ...
Yes, for default member initializer, Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor. If a member has a default member initializer and also appears in the member initia...
62,259,804
62,261,226
instead of so many if statements I want a logic where I can do it with one statement or optimized way
I have a vector of structures vector<S> sData which my structure contains 5 elements (name, age, techs, projects, language) The user can input name and it should output the structures that equal to that name and for the other elements too. My problem is that the user can input two of them only and it should only check...
I'd suggest a little code refactor. Let's consider adding a helper structure SearchS which holds all params you are looking for (and comparison operator): struct S { QString name; int age = -1; QString techs; QString projects; QString rate; }; struct SearchS { std::optional<QString> name; std::optional<i...
62,260,370
62,262,272
Doubleton class - transition from single to double
Below I managed to create a singleton class that allows the instantiation of an object. How can I modify the code as simple as possible to get a "Doubleton", to have two objects? #include<iostream> using namespace std; class Singleton { public: static Singleton& instance() { return uniqueInstance; ...
"Templetize" it: #include<iostream> using namespace std; template<int N> class Singleton { public: static Singleton& instance() { return uniqueInstance; } int getValue() const { return data; } void setValue(int value) { data = value; } private: static Singleton uniqueInstance; int data; Singleton...
62,261,064
62,262,574
Console like application in CPP
I have been assigned with a coding homework in CPP where I'm supposed to create a Matrix calculator. This would be an ok-ish task considering all I need to do is matrix calculations, use polymorphism, consider memory consumption, and some more criteria. What I'm struggling with is that is should be a console like envi...
For your first question, look at libreadline or libeditline. If you do not want to lift a finger, run your program under the rlwrap wrapper. For your second question, look at Simple library or implementation for a mathematical expression evaluator . Look for one that allows you to define and use variables.
62,261,159
62,261,241
This piece of code executes fine once and gives segmentation fault the other time
I have gems objects gems[10][10], which have an attribute color. I want to get three or more consecutive gems in a column having same color, and change thier color. The code below works just fine once while gives segmentation fault the other time. What cause the segmentation fault in random runs. bool findMatch(){...
while(gems[a][i].getColor()==gems[j][i].getColor() && a<10){ When a reaches the value of 10, here. gems[10] gets evaluated before the a<10 comparison. Since this exceeds the size of the array, this results in undefined behavior.
62,261,576
62,280,535
How to create Python extension from existing C++ packages include .dll, .h files using Pybind11?
I am trying to convert a C/C++ API package into a Python extension. I have gone through this visual studio tutorial succefully. This is a simple tutorial and maybe not very practical for a real convertion. Here is my task. I have the include folder, a folder of *.dll and *.lib files, and some demo cpp files. questio...
1) The dlls will need to be packaged with the python extension (see below) and most likely installed in the same folder. 2) No you need to wrap them individually. This is less effort than it sounds, and even if some sort of batching was available you'd still need to specify them all. 3) This question is about packag...
62,262,208
62,301,129
Windows (COM) API behaving differently w/o specific library
It seems that the Windows API behaves differently depending on whether or not I link in a specific library. Unfortunately, it's a pretty big library which makes it hard to track the issue down and I don't have a real clue where to start. I can reproduce this behaviour for several APIs. For example, I'm using the COM-ba...
It turned out that loading the OpenBLAS library caused the problem. It's even reproducible with a minimal example: // code in the original post --> works LoadLibraryA("libopenblas.dll"); // not reproducible with LoadLibraryExA("libopenblas", NULL, DONT_RESOLVE_DLL_REFERENCES); // to avoid calling DllMain // code in t...
62,262,308
62,262,799
Const map and its size
I have a std::map which cannot change at runtime. Thus, I have marked it const I cannot mark it constexpr, since has a non-literal type. Can I deduce the size of this map at compile time? #include <map> #include<string> int main (){ const std::map <int, std::string> my_map { { 42, "foo" }, { 3, "bar"...
Unfortunately, you can't use std::map and std::string in constexpt context. If it's possible, consider switching to array and string_view: int main() { constexpr std::array my_map{ std::pair<int, std::string_view>{ 42, "foo" }, std::pair<int, std::string_view>{ 3, "bar" } }; constexpr auto items = my_...
62,262,690
62,262,792
QT5 Signals does not activate the functions inside SLOT
Good morning everyone and thank you for your time. I have created a rubik's cube program and I would like to connect it with a serial link controller.Everything works fine and independently but when I connect my thread (serial connection) to the rest of the program it doesn't work. I have created a signal that calls a ...
serial *lecture and Cube c are two different objects. Did you mean to the following? QObject::connect(lecture, &Cube::MySignal, &c, &Cube::rotationFComplete);
62,262,882
62,263,319
How can I get every object of a list and call the getName method to print it's name
I have a problem with printing the name of each object that a list contains by calling the getter method for the name. I have the class Student. That class contains a list of Course type objects and a method called printData(), that inside has an iterator to loop through the list to get each Course type object and call...
1) Student::printData() is const, so courses.begin() is a list::const_iterator which can't be assigned to a non-const iterator 2) Course::getCourseName() is not const, so you can't call it from const context. Please take a look at this code: class Course { public: Course(const string& n) : nameOfCourse(n) {} const...
62,262,946
62,263,252
set::find finds an element that does not exist
I have the following Edgeclass: class Edge { public: int src, dest; bool operator== (const Edge &edge) const { return ((src == edge.src) && (dest == edge.dest)) || ((src == edge.dest) && (dest == edge.src)); } bool operator<(const Edge& edge) const { return !(((src == edge.src) && (dest == edge.dest)) || ((sr...
You currently don't have a valid Compare for std::set, so your program has undefined behaviour. Here is one that is compatible with your == bool operator<(const Edge& edge) const { return std::minmax(src, dest) < std::minmax(edge.src, edge.dest); } This can also be used to simplify your == bool operator==(const Ed...
62,262,968
62,263,156
Generically taking linear combinations of indexibles/callables
I'm trying to globally scale and add together callable/indexible objects (vectors in the abstract mathematical sense of the word). That is to say, I'm trying to take linear combinations of objects that define operator[] or operator(). For example, I want to be able to do this: LinearCombination<std::function<double(dou...
This function: template<typename T> auto zero(rank<2>) -> decltype(static_cast<T>(0)); wins overload resolution against: template<typename T> auto zero(rank<0>)->std::enable_if_t< std::is_assignable<std::function<double(double,double)>, T>::value , std::function<double(double,double)>>; This is because rank<2...
62,263,598
62,263,685
What's the equivalent feature of SparseMatrix in GLM?
Eigen has Eigen::SparseMatrix, what's the equivalent feature in GLM? I've looked through its documentation, and googled, couldn't find it. But it's hard to believe glm doesn't have sparse matrix.
But it's hard to believe glm doesn't have sparse matrix. Why is that so hard to believe? Sparse matrices are outside of GLM's job description. GLM is intended to mimic the OpenGL shading language's vector/matrix facilities. Obviously it adds its own stuff, but that's the core of the system. Sparse matrices aren't par...
62,263,799
62,318,715
How to declare a 2D vector consist 2D vectors?
This is confusing me in c++ (17) I want to declare a 2 dimension vector with any size which each member is again a 2D vector itself. I want to make empty vectors with known size. In fact I want its size to be set at declaration. For a better picture , imagine a classic sodoku puzzle with 9 houses in 3x3 grid which each...
It turns out that the problem is to define a vector of cell_t declaration. board_t test(3,std::vector<cell_t>(3,std::vector<int>(3))) // @a^^^^^^^ @b^^^^^^^^^^^^^^^ @a we have a vector of cell_t but @b we describe a 'vector of int' that's the problem. we should go by cell_t(3,std::ve...
62,264,083
62,265,387
ActiveDirectory/C++: How to translate Guid to User Name?
Question in the title. I have the Guid of a user, and want to get the user name from Active Directory. I have been googling and looking at an example from Microsoft, but can't get it working. And every google hit I get is showing how to do it in C#, while I need it in C++. Any ideas? Preferably I'd like to just get the...
That link you included is about performing a search. But if you have the GUID, you don't need to search. You can bind directly to the object using the GUID using an LDAP path in this format: LDAP://servername/<GUID=XXXXX> You can exclude the servername if the computer you are running this on is joined to the same or t...