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
61,706,835
61,706,908
C++ passing by reference random output
If anyone is seeing this in the future, the answers below are great and explain in depth why I got this error. So, now I understand why I get the random output with this code. Because I did not use a return statement in the function's body. This is my code: int getNewValue(int &); int main() { int number = 5; ...
Is this because a cout function requires a return value and a void function has no return value? Yes. The issue is you are mixing up 2 ways of getting information from a function. Passing an argument by reference: void getNewValue(int &num) { num *= 3; } In this case the usage would be: getNewValue(number); cou...
61,706,947
61,707,291
How to use folders in visual studio c++?
My Problem is that in the sln view, there are no folders, severely hindering organization, and in folder view, when I add c++ files they become misc files and are not added to the solution. So my question is; how would I use folders, or if it isn't possible, what should I use instead? I am using Visual Studio 2019.
If you want to add project folders and/or files: The quickest way that I know of is to add the folder to your project file directory using Windows Explorer find the folder in Solution Explorer (make sure Show All Files is checked) right click on the folder and select Include In Project You may have to do the folder a...
61,707,195
61,790,725
Error building opencv with mingw, qt, windows
I tried to build opencv library with mingw for Qt 5.13.0. I have generated makefiles using the options for cmake: "C:\Program Files (x86)\CMake\bin\cmake.exe" ../sources -G "MinGW Makefiles" -DWITH_QT=ON -DWITH_QT_OPENGL=ON -DBUILD_EXAMLES=ON -DQT_QTCORE_LIBRARY_DEBUG="Qt5Cored.dll" -DQT_QTCORE_LIBRARY_RELEASE="Qt5Core...
Solution: You need to open "modules/core/CMakeFiles/opencv_core.dir/flag.make" and replace "RC_DEFINES=..." with "RC_DEFINES = -DCVAPI_EXPORTS -D_USE_MATH_DEFINES -D_WIN32_WINNT=0x0601 -D__OPENCV_BUILD=1 -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS"
61,707,289
61,707,364
C++ Class Methods Definition Syntax
In C++, it is sometimes considered good practice to declare your classes in a header file and define all the methods in a cpp file. I understand this, but a consequence of this seems to be that instead of having all of the class methods tabbed-in inside curly braces, they are just out in the open in the cpp file. Is th...
You could do this: == h.h == namespace H_DEFS { class H { public: int A(); int B(); }; } using namespace H_DEFS; == h.cpp file == #include "h.h" namespace H_DEFS { int H::A() { return 4;}; int H::B() { return 5;}; } == main.cpp == #include "h.h" int main() { return H().A() + H().B()...
61,707,777
61,708,146
Sliding window using deque (runtime error)
In the following program, I am trying to find the maximum in window size of k in an array of length n. For reference, the question is from LeetCode. For example, if the array is [2 5 3 1 2] and window size is 3, then I have windows as [2 5 3], [5 3 1], [3 1 2] and corresponding maximums are 5, 5, 3. I am using std::deq...
Observe this part of your code: while (1) { int elem = d.back(); // get element d.pop_back(); // pop element if (elem == nums[i-k]) { // compare element break; // and break on success } // What happens on failure??? } ...
61,707,970
61,715,671
How to improve GEMM performance on data-mapped (Eigen::Map) matrices sharing memory with an std::vector?
When multiplying two data-mapped matrices (Eigen::Map) I notice a significant performance difference depending on how the memory was allocated. When using memory coming from a custom allocation, it's almost twice as fast compared to using (also aligned) memory coming from an std::vector with data allocated also by Eige...
As pointed out in the comments by PeterT and chtz, the manually allocated version does not initialize the memory (in contrast to std::vector), accessing it is undefined behavior, and thus the MMU likely does something smart, i.e., not actually accessing the memory. When also initializing the memory in the second part, ...
61,708,267
61,708,383
Jump bypasses variable initialization in switch statement
I need an std:: vector<char> or an std:: string in my switch case for some purpose. So, I wrote the following dummy code to see if it works: #include <iostream> #include <string> int main() { int choice = 0; do { std:: cout << "Enter Choice" << std::endl; std:: cin >> choice; switch(ch...
char str[6]; is default-initialized. In case of C arrays of simple values with automatic storage duration ("allocated on stack") it means "no initialization at all", so I guess it's not an error. If you, however, initialize the array like char str[6] = {}, it will yield an error. I suggest you put extra curly braces so...
61,708,409
61,715,193
SFML game not compiling on Windows
I've been working on a game using SFML for a while now and it's been going great working on it on my Linux and Mac machines. Recently, I tried compiling the game on Windows and ran into many issues. I'm using g++ and a makefile. g++ -std=c++17 -g -O2 -Wall -Wno-reorder -LSFML-2.5.1/lib -ISFML-2.5.1/include -o dungy Ani...
Apparently, I had to use the debug libraries, which I don't have to use on any other platform. The makefile I now use has the following flags: LDFLAGS = -lsfml-graphics-d -lsfml-audio-d -lsfml-window-d -lsfml-system-d Before, I had these LDFLAGS without the -d on the end. Not sure why this is different on Windows than ...
61,708,512
61,724,721
Mocking standard library functions using gmock
Following is the function which I want to unit test: void sampleFunc() { FILE *file = fopen(path, "rb"); if (!file) { std::cout << "File couldn't be opened!" << std::endl; } const int bufSize = 32768; unsigned char *buffer = (unsigned char*) malloc(bufSi...
What you might do to test your function: class IFileManager { public: virtual ~IFileManager() = default; // You could even improve interface by returning RAII object virtual FILE* fopen(const char* path, const char* mode) = 0; virtual void fclose(FILE*) = 0; // ... }; class FileManager : public IF...
61,708,606
61,708,647
Why does my template lead to duplicated symbols?
My program has 30 duplicate symbols errors for the methods length() and table() from the struct below. This struct can be instantiated in four ways. Each of them is identical but for the table each instantiation refers to and, potentially, the length of that table. This needs to be known at compile time in order that I...
Fully specialized template functions in a header file should be declared inline template <> inline const int WaveTable<SQR>::length() { return kSquareTableLength; } ^^^^^^ etc. etc.
61,708,771
61,710,777
How to use functor which returns two value with standard library functions?
I want to solve the following problem: I have a system of equations ax+by=c dx+ey=f I have read in a tutorial that we can use a functor like the following bool isIdd(int i){ return ((i%2)==1) } and than we can use this functor with the find_if function. I want to ask if it is possible two return two values f...
is possible to return two values from a functor (for example a tuple) yes ,it is ,but you need also proper operator bool() As I understood, you want something like this: #include <utility> #include <algorithm> #include <iterator> #include <functional> struct Pair{ bool b; uint32_t data; operator bool...
61,708,993
61,709,090
How to get rid of these compiler warnings?
When I run my code with the below implementation of the Constructor of LRUCache class, I get 12 compiler warnings as follows: The same set of first six warnings is repeated again. struct Node{ Node* next; Node* prev; int value; int key; Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),valu...
The problem here is initialization order in your Node struct. In C++ members are initialized in the order they are declared, regardless the order they are listed in the constructor initializer list. Thus they are initialized in the order next, prev, value, key. Listing them differently in the constructor can be mislead...
61,709,086
61,713,359
CMake target with sibling folders
My project structure is the following: root -CMakeLists.txt ----exec -----CMakeLists.txt -----src ------a.cpp ------a.h ----lib -----CMakeLists.txt -----src ------b.cpp -----inc ------b.h Exec target depends on lib target. My main CMakeLists.txt is just the following: cmake_minimum_required(VERSION 2.8) cmake_policy(S...
As commented, you can simply link the BASIC CMake library target. Because it was created earlier in the same CMake invocation, CMake already know of its existence and will link it properly. In addition, (if you can upgrade your CMake to at least 2.8.11) you can apply the lib/inc include directory directly to your BAS...
61,709,113
61,714,018
Reverse an array in groups of given size in C++
I am trying to solve a problem which is a Basic level Array problem. I implemented my logic and passed the sample test cases given on that page and also tried some custom inputs and it did worked as intended. But when I submit my code it gives a Segmentation Fault, but unfortunately it didn't tell on which particular t...
So the fault here is reverse(A + i, A + i + K); because if K > N then A + i + K in reverse() will access out of bound memory therefore it causes SIGSEGV. The solution is to use reverse(A + i, min(A + N, A + i + K)); which will handle both the general case and special case when K > N
61,709,127
61,709,264
array elements not printing when trying to print in the main function
I want to find the factors of a product by using arrays to check whether they equal it or not the values do not print here is the code #include <iostream> using namespace std; int main() { int arr[5] = { 1,3,5,7,2 }; int arr1[5] = { 0,6,5,4,9 }; int X; cout << "Please enter X:"; cin >> X; for (int i = 0, j = 0;...
Use this nested loops for (int i = 0; i < 5 ;++i) { for(int j=0 ;j<5;++j){ if (arr[i]*arr1[j]==X) { cout << arr[i] << " "; cout << arr1[j] << " "; } } }
61,709,163
61,713,089
When passing a std::map to a thread I am getting inconsistent behavior
In the linked code, I am trying to pass an std::map to the thread as a reference (using std::ref). However, sometimes when the map is accessed my the thread it is empty.
std::vector invalidates pointers or references when elements are added. I ended up using a std::vector of std::unique_pointers to store the map. Use a std::deque or pass by value. As commented by Igor Tandetnik. Also refer this answer
61,709,202
61,709,643
How to call the destructor of a child of an abstract class?
I have a purely abstract class: class Abstract{ void func1(arg1, arg2) = 0; } And its implementation with a destructor: class Concrete : public Abstract{ void func1(arg1,arg2) { /*implementation code..*/ }; ~Concrete() {/*code for the destructor..*/} In main.cpp I create an unique pointer for it: int main(){ s...
As per your implementation you have not defined your Abstract Class Destructor as virtual. So simple fix will be to make the destructor of the Abstract Class as virtual. So the Declaration of the Abstract Class will look like below: class Abstract{ public: void func1(arg1, arg2) = 0; virtual ~Abstrac...
61,709,482
61,710,147
Find the best number of thread with Intel OpenMP : only 1 thread has better results than many threads
Using multiples times the following type of loops in my code : #pragma omp parallel for schedule(dynamic, num_threads) for(int i=0; i<F_matrix_A.size(); i++){ for(int j=0; j<F_matrix_A.size(); j++){ F_previous_T[i][j] = F_previous[j][i]; } } #pragma omp parallel for schedule(dynamic, num_threads) for(i...
The line schedule(dynamic, num_threads) is likely to cause scalability issues. Indeed, with a matrix of size 1700 and 64 threads, the chunk size of the dynamic schedule policy is 64. Thus, the number of chunks is floor(1700/64) = 26 which is far too small to feed the 64 threads! Even with 32 threads, the work balancing...
61,709,859
61,710,009
How to deduce the type of lambda's return value.?
As per the documatation(What is a lambda expression in C++11?), The return type of the lambda could be deduced in this code. I could not get the idea how it could be done? void func4(std::vector<double>& v) { std::transform(v.begin(), v.end(), v.begin(), [](double d) { return d < 0.0...
Sloppy speaking, the ternary operator has some built-in conversion to a common type. You can read on cppreference how the type of the result is determined. The details are rather involved, so i'll put it in plain English: The result of d < 0.00001 ? 0 : d; is double. In the no-conditional version one branch returns an ...
61,709,891
61,713,210
How to create a vector of std::ofstream s and write the stream to different text files
I am just trying to write some numbers to a few different files using an std::vector of std::ofstreams. My program is compiling and running and the files are getting generated but there is no text in my files. #include <iostream> #include <fstream> #include <vector> int main() { auto num_components = 3; std::...
auto num_components = 3; std::vector<std::ofstream> files_to_be_written; files_to_be_written.resize(num_components); Since you call std::vector::resize() here, this creates three new empty std::ofstream elements in the vector. Then you append three more std::ofstream objects to the back of the vector with std::vecto...
61,710,326
61,710,551
Suppose you have an array of N elements. You need to find for how many i, Ai + A(i+1) is a square number. Is this question trivial? If so how?
I just wanted to know if the above question is trivial or not. More importantly, how can you recognize if an algorithm is trivial?
It depends what do you mean by trivial. If you talk about complexity, it is O(n*M(N)) where M(N) is the complexity of the underlying multiplication algorithm with N maximum of the array's values and n is the length of the array. If you talk about implementation, it is one loop with one check that the sum of the neighb...
61,710,355
61,714,431
Clang-format: space before unary operator
I would like to configure clang-format to put a space before unary operators (to increase readability): Instead of: i++; I would like: i ++; Is it possible? (I can't find anything about this in the documentation.) If not, could one submit a feature request for clang-format?
Unfortunately, No. There is no option for formatting unary operator (i++ -> i ++) in clang-format neither it's written in its official and most trusted documentation and other sites. Secondly, the basic convention has always been i++ rather than i ++ (for most programmers) in programming languages. So, it doesn't seems...
61,710,518
61,710,755
C++ function pointer's address invariance
I know that function pointers` addresses do not change among various compilation units. struct Interface { void sum(int, int); }; For instnce, &Interface::sum will yield the same value among different units (Am I wrong?). At what extent does this hold? Will the address be the same when compiled on a different mach...
First of all, I would like to emphasize that the fact that sum is a method is unrelated to the answer. Second, the address will be the same across all compilation units because it's the most efficient - otherwise, you have to duplicate sum in the executable. If it's in only once place, every caller can just call there....
61,711,005
61,712,172
Why erasing element from vector while iterating causes Segmentation fault (core dumped)?
The following generates the problem I am having in a larger scale program. #include <iostream> #include <vector> using namespace std; int main() { vector<int> vec{1, 2, 3, 4, 5}; for (unsigned i = vec.size() - 1; i >= 0; --i) { if (vec[i] > 2) vec.erase(vec.begin() + i); else cout << vec[i] <...
As the comment says, i is unsigned, therefore i >= 0 is always true. When i becomes less than 0 it actually becomes a large positive number, and then indexing into the vector with i invokes undefined behavior. The proper way to erase elements from a vector is to use the erase-remove-if idiom: vec.erase(std::remove_if(v...
61,711,088
61,714,836
Creating a custom allocator for CHeapPtr (for use with Sqlite)
I wanted to create some smart pointers for sqlite3 using CHeapPtr. CHeapPtr uses the CCRTAllocator class by default, so I figured I'd just create some custom allocator classes that inherit from CCRTAllocator but override its Free method, so that they use the proper clean-up functions: class CSqlite3Allocator : public ...
You don't need to inherit from CCRTAllocator, allocator is expected to be just a new class. You can use ATL's COM heap allocator as an example: class CComAllocator { public: static void* Reallocate(void* p, size_t nBytes) throw() { return ::CoTaskMemRealloc(p, ULONG(nBytes)); } static void* All...
61,711,224
61,711,631
-Wformat-truncation error writing 2-3 bytes into region of 2-6 bytes
I have an issue with the following fuction: std::string TimeToTimestampStr(time_t t) { tm aTm; ACE_OS::localtime_r(&t, &aTm); // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) // HH hour (2 digits 00-23) // MM minutes (2 digi...
in tm the fields are int so there are signed, for the compiler all the numbers you compute can be negative, but you sized your array supposing there are all positive because you know what localtime_r does, but for the compiler 26 bytes are necessary because the worst case is like -9999--13--31_-23--59--59 Of course hav...
61,711,437
61,711,616
while loop w/ 2 conditions does not work c++
I'm working on a minigame in C++ lately. The goal is to write a little game where you have to guesse a number. If you do so you'll get a point (I call it hit there) and if you don't you'll get a "miss". Logically speaking I don't want the game to go for ever. So I was trying to use a while loop to define at which score...
if you want the game will end after 3 hits or 15 misses you should use the && operator and not the || operator it is because the || operator will return true when at least one of the conditions true, the && operator will return true when both of the true
61,712,020
61,712,334
Matrix multiplying method gives out additional column filled with zeros
I wrote a method that multiplies matrices. It works fine, but gives additional column of zeros. The result of multiplying is correct. Here is the code of method: Matrix Matrix::multiplyMatrix(Matrix second) { vector<vector<double> > sum(vec.size(), vector<double> (vec[0].size())); if (vec[0].size()!=seco...
Your matrix named "out" has the wrong dimensions, also, int the first line of your code, the sum has wrong dimensions too. the first line should change to: vector<vector<double> > sum(vec.size(), vector<double> (second.vec[0].size())); the definition of out should change to: Matrix out(vec.size(), second.vec[0].size()...
61,712,324
61,712,384
about Initialized Captures of the C++14 lambdas
Why the value x is updated to 6, and y is initialized to 7? Could anybody give me some clues? int x = 4; auto y = [&r = x, x = x+1]()->int { r += 2; return x+2; }(); // Updates ::x to 6, and initializes y to 7.
In the capture group: [&r = x, x = x+1] r is a reference to x, so any changes to r are reflected in x. On the other hand, the left hand side x in the capture group, is a copy of x+1, where the right hand side x comes from outside the lambda. Since the confusion is coming about from the fact that lambda capture syntax...
61,712,383
61,712,463
Smart pointers: no suitable constructor exists to convert from derived_object* to std::shared_ptr<abstract_base_object>
I have just started learning about smart pointers and I'm having some trouble implementing them. I'm writing code for a board game that has an abstract base class for pieces and for example one derived class for a piece: class pieces { public: virtual ~pieces() {}; }; class piece1:public pieces { private: std...
Implicitly converting a raw pointer to a smart pointer would result in many potential problems, e.g. that raw pointer that points to memory that is already owned/managed by a smart pointer, that has automatic storage duration, or that is manually managed, would be passed to a smart pointer for managing, and that would ...
61,712,556
61,721,718
Connect with an already created named pipe with boost
I'm looking in to using third party libraries for IPC communication using named pipes on Windows. I've been using the Win32 API for this for the last few years. I was interested in replacing my implementation with a tried and true open source library. I noticed that boost::process has an implementation of an async_pipe...
OK, so I was going about it the wrong way. After reading this issue on Github Link I realized I needed to use a stream_handle instead. Note, the pipe must be opened in OVERLAPPED mode for this to work. Creating the stream_handle static boost::asio::windows::stream_handle OpenPipe( io_context& context ) { constexpr ...
61,713,109
61,713,236
No known conversion from 'A' to 'A &&' for 1st argument
I am new to r-values and l-values in C++. I was playing with it. I am not sure why the following code works: class A { public: A() { std::cout<<"Constructor called"<<std::endl; } A(const A& a) { std::cout<<"Copy Constructor called"<<std::endl; } }; template<typename T> void printA(T...
In this function template: template<typename T> void printA(T&& b) { std::cout<<"Print method called"<<std::endl; } T&& is a forwarding reference. This means it can bind to l-values, or r-values: A a; printA(a); // ok, l-value printA(A{}); // ok, r-value However, this is a regular function that takes exactly an r...
61,713,364
61,713,438
How can I check if these structs has the specific type called "Foo"?
#include <iostream> /**** I am confused to apply sfinae method here ******/ template <typename T> struct hasTypeFoo { //.. static constexpr bool value = true; }; ///////////////////////////////////////////////// struct A { using Foo = int; }; struct B { }; int main() { constexpr bool b1 = hasTypeF...
Use std::void_t: template<typename T, typename = void> struct hasTypeFoo : std::false_type { }; template<typename T> struct hasTypeFoo<T, std::void_t<typename T::Foo>> : std::true_type { }; A very good explanation of how std::void_t works, can be found in this question. It is used here to silently reject the speciali...
61,713,422
61,715,041
JNI on Android: Callback from native with Integer parameter works, with String or Void it doesn't. Why?
I have a callback class for doing callbacks from native C++ code to Kotlin (not sure if Kotlin/Java makes a difference here, if so, is there any documentation on that?). I have a working callback with an integer parameter, that I call from different native threads without a problem. Now I want to add a second one that ...
You're missing a semi-colon in the method signature that you pass to GetMethodID. It should be: id = g_env->GetMethodID(target, "stringCallback", "(Ljava/lang/String;)V"); Note the semi-colon after Ljava/lang/String. See the part about Type Signatures in Oracle's JNI documentation. Regarding your other variations: A ...
61,713,700
61,714,409
Can I create Union of classes
I have two classes for communication that will never exist at the same time but both will be in use. Example: class CommA { public: void SendA(); ... private: ProtocolA a; ... } class CommB { public: void SendB(); ... private: ProtocolB b; ... } Is it possible to hold them in Union to ...
The std::variant was already raised by others in comments and answers. I'll explain why it is the recommended approach. There is an important thing to know about unions: only one member of a union can be active at any time. If you create an AB object, it's either a or b, and if you access the wrong one, it's UB. H...
61,714,343
61,714,395
how to use std::find through ONLY first elements of the vector pair OR a custom vector triplet?
I have a vector<triplet> where triplet is a custom datatype, which is defined as follows:- struct triplet{ int in, g, o; //where in denotes index of a triplet element in the vector<triplet> } So I have a elements in my vector<triplet> as follows vector<triplet> v= ({0,4,0},{1,2,0},{2,5,0},{3,4,0}); I have a few q...
Use a lambda function. int value_to_find = ...; find_if(v.begin(), v.end(), [=](const triplet& t){ return t.in == value_to_find; }); Any time you need a one-off function for some purpose a lambda function is the obvious choice.
61,714,364
61,714,448
trying to insert object at certain index in list (c++)
I'm trying to insert an object in a list of objects at a certain index, but my iterator doesn't seem to want to be added to an int. here is my code : list<Node> nodes; . . . // filling list . . . void DiffLine::addNodeAt(int i, Node node) { std::list<Node>::iterator it; it = nodes.begin() + i; nodes.insert(it, node);...
std::list is not random-access so its iterators are not randomly advanceable on purpose. There's std::advance() in the header <iterator> if you really want to advance it, just be ready to wait for a linear time. And consider using std::vector.
61,714,426
61,714,533
Why memory_order_release support until C++20?
https://en.cppreference.com/w/cpp/atomic/memory_order From cppreference, memory_order_release can use until C++20? Can anyone explain why C++ Standard will delete this and which one memory_order we should use after that.
This is just a misunderstanding with the formatting of cppreference. It's not that one line that is "until C++20", it's the whole block. memory_order_release isn't removed in C++20. It's just that memory_order itself was respecified from being a weak enum: typedef enum memory_order { memory_order_relaxed, memo...
61,714,634
61,714,816
What is -lutil means in g++ complie option?
What is the purpose of -lutil option in g++ compile options? I Google this, but doesn't find good explains. Better explain with an short example.
-lutil is a use of the -l<library> link option. To will instruct the linker to search for, and possibility link against, a library named libutil. libutil is part of glibc and contains some BSD derived functions: openpty/forkpty/login_tty logwtmp login/logout These functions are not part of any C, C++, or POSIX standa...
61,714,730
61,716,619
getting the structure name with boost fusion
Using boost::fusion is possible to iterate an adapted structure and get the name of each member of that structure. Is there a way to retrieve also the name of the structure some way? What I woulld like to do is the following: given the current scenario namespace inner { struct test_struct { int a; int b; } } BOOS...
That's not a feature. You can see it by inspecting the output of the preprocessor. You can see the struct_member_name extension, but no such literals for the struct name: namespace boost { namespace fusion { namespace traits { template <> struct tag_of<inner::test_struct> { typedef struct_tag ty...
61,715,594
61,716,193
reverse iterating and comparing two consecutive elements of std::vector (c++)
I'm iterating through a list of points that define a circle (closed shape). For each point I'm checking the distance between this one and the next and deciding to subdivide if the distance is bigger than 4. for (vector<Node>::reverse_iterator i = nodes.rbegin(); i != nodes.rend(); ++i) // going through list in reverse ...
Check i + 1. If it's rend(), then get v2 from rbegin(). You said your structure is a "list", but your use of += tells me you have random access iterators, so I wrote the below assuming you had a random access iterator (such as if nodes was a std::vector). If that's not the case (eg if nodes is actually a std::list) thi...
61,715,648
61,717,227
How to restrict the parameter type of a callable to be passed to a function?
#include <functional> template <typename M> M g(std::function<M(int)> f) { return f(0); } int main() { g([](int x){return x + 1;}); return 0; } I want to express something like "the (only) argument passed to function g should be a callable object that has int as type of the parameter". G++ 9.3.0 says pr...
First, write a simple meta-function that gives the type of the argument of a unary function pointer: template<class Ret, class Arg> auto arg(Ret(*)(Arg)) -> Arg; Then, in the body of g, you can static_assert that the passed in callable (when decayed to a function pointer), has a single parameter of type int: template ...
61,715,918
61,716,451
Using C++ templates to switch algorithms
I have a C++ class that has a pointQuery function. Currently, when I have to switch between linear and binary search, I comment the other part of the code. I saw this post, and tried to refactor my code. My code goes something as: namespace searchStrategy{ struct linearSearch{}; struct binarySearch{}; } te...
(partial) specialization might be a solution, but member/function cannot be partial specialized, you might then partial specialize the whole class. As alternatives, In C++17, you might use if constexpr: bool pointQuery(const T* f) const { if constexpr (std::is_same_v<LookupStrategy, searchStrategy::linearSearch>) ...
61,716,109
61,716,553
c++ destructuring function return value
Sorry if this question has been asked before. I am pretty newbie to this; So, I have the following code; template<typename K, typename V> class test_class { std::map<K, V> my_map; void add_kv_to_std_map ( K const& key, V const& val ) { // And basically, i have the following syntax; auto [it, ...
I don't really need ins variable. Is it possible to just retrieve it in there? No. You can use a variable name that conveys the meaning that it is ignored. Personally, I prefer underscore (note that underscore is a reserved identifier in global namespace, so don't use it there). You can use the [[maybe_unused]] attri...
61,716,456
61,716,536
Accessing specific parameter from parameter pack inside function scope, how?
Given, template<typename T, typename ...Args> void foo(T t, Args ...args){/*foo scope*/} When foo("bar",27,true); is called, how to access true, within the scope of foo? Can a parameter simply be extracted like auto param3=args<2>;? I'm trying to get both the parameter type and the value it contains.
std::tie creates a tuple of lvalue references. Paired with std::get<I> will give you access to the arguments as if they were referred by name. #include <tuple> template <typename T, typename... Ts> void foo(T t, Ts... ts) { auto args = std::tie(t, ts...); auto param3 = std::get<2>(args); } DEMO Note: Usually,...
61,716,473
61,716,497
Why are my or operators not working as intended?
My if statements are getting hit no matter the input. I can't wrap my head around why. Here is the code: void Novice::selection() { char selection, shift; cout << "Please select a section to run: A - Home Row, B - Bottom Row, C - Top Row, D - Pointer Fingers, E - Right Pinky;" << endl; cin >> selection; ...
This is not how logical operators work in c++. To compare against multiple values, you need to do: if (selection == 'A' || selection == 'B' || selection == 'C') { // ... } Note that your first if is incorrect, even if you use the fix above. If you check whether a value is not equal to several other values, this wi...
61,716,649
61,716,911
printf/scanf usage and difference from <iostream> and cout/cin diffferences, when to use which?
not a question about a particular code, but in C++ the operators scanf/printf using <stdio.h> seem the same to me as cout or cin in the header <iostream> so can anyone just explain what the difference between the operators, why and when do we use either one? humbly apologize if this has been asked before, but T...
Regular competitive programmers face common challenge when input is large and the task of reading such an input from stdin might prove to be a bottleneck. Such problem is accompanied with “Warning: large I/O data”. cin/cout is faster than scanf/printf, key differnce among these. Why is scanf faster than cin? On a hig...
61,716,709
61,717,501
RELEASE DEBUG in CMake
I was trying to set up two different type of code for my project.When I try to run the following code nothing is printed.I am using cmake and mingw. #include <iostream> int main(int, char**) { #if DEBUG std::cout<<"Hello from debug"<<std::endl; #endif #if RELEASE std::cout<< "Hello from release"<<std::endl; #endif }
I recommend using NDEBUG, since it's standardized. It's defined for non-debug -- while normally used with assert, I've used it for other things too. #include <iostream> int main() { #ifndef NDEBUG std::cout << "Hello from debug" << std::endl; #else std::cout << "Hello from release" << std::endl; #endif }
61,716,924
61,716,997
Friend function how can i change their members globally
how can i change the members of a friend function globally, not just inside its block? i have a simple example below: Expected Output(int): 45 35 35 #include<iostream> using namespace std; class dog { private: int HealthPoints; int Damage; public: dog(int HealthPoints, int Damage){ ...
You don't want global variables. What you're currently doing is passing Attacker and Attacked by value - e.g. copying them. You make changes in doAttack to these copies. The originals are never modified. Pass them by reference instead. I have changed the name of your function to be more friendly as well. Feel free to c...
61,717,309
61,717,417
How can I limit memory usage for a C++ code via command line using gcc?
How can I limit memory usage for a C++ code via command line using gcc? For context, I'm implementing a code judge so I need to run every script students submit, I was able to do the same for Java with the following command: java -Xmx<memoryLimit> Main So far no luck with gcc, any ideas? Thank you.
There is not much that the compiler can do in regard to limit the memory use of a program. Programs are generally not run within a "C++ virtual machine" that would be analogous to the JVM, so there is no comparable command line options for an executable. Typically however, operating systems do support specifying resour...
61,717,435
61,717,497
Why I can't use operator+ with reverse_iterator?
I have this code: #include <map> #include <set> #include <vector> #include <algorithm> #include <cctype> #include <string> ... void f() { std::set<std::pair<int, std::string>> orderByRating; /*...*/ for (auto revIter = orderByRating.rbegin(); revIter != orderByRating.rend(); revIter++) { int subsetS...
operator+ can only be used on random access iterators. std::set::iterator is a bidirectional iterator, and so is a reverse iterator obtained from it, because a reverse iterator has the same iterator category. To advance a bidirectional iterator by n elements, you can use std::next: auto curIter = std::next(revIter, sub...
61,717,459
61,717,586
Split an std::tuple on an arbitrary index
I have an std::tuple and I want to split it at an arbitrary compile-time parameter N. I have seen solutions floating around for getting the head and the tail of an std::tuple like here , here or here , but these cannot solve my problem since for me this constant (like 1) that is being passed as a template argument is a...
You're near. Your error is to pass N as argument from tail() to tail_impl(). You should pass it as template parameter template < std::size_t N, typename... Ts> auto tail( std::tuple<Ts...> t) { // ..............VVV return tail_impl<N>( std::make_index_sequence<sizeof...(Ts) - N>() , t); } and tail_impl() become...
61,717,475
61,717,496
Can you have a function be a const and also return a const C++
For example if the member function of a class is: const QStringList& getList() const Returning a whole list is potentially an expensive operation but I also don't want the function to be able to change the private member variables of the class. I'm curious on this one.
Can you have a function be a const and also return a const C++ Yes. A member function can simultaneously be const, and return a reference to const. In fact, this is quite typical when returning references to member variables.
61,717,758
61,717,856
Detaching thread from it self
I got some problems with multythreading, while i was creating small Direct2d library. Is there any way to detach thread from it self? For exaple: std::thread a([](){ std<<cout "thread started" << std::endl; //here i need to destroy(detach) this thread });
No, there is no standard or safe way to detach a thread from within the thread. You must either join or detach a thread object before it goes out of scope. Based on your use case, the use of std::async may be a more suitable alternative, as it does not require any manual joining or detaching of a thread: #include<futur...
61,717,803
61,717,965
C++, Passing an object as a parameter in anothers object constructor
I have 3 classes in 3 files. Fecha.h Horario.h Recordatorio.h I want to be able to create a new Recordatorio class that has an Fecha and Horario class inside. This is the function i have in main: Recordatorio recordatorio(Fecha(5, 10), Horario(9, 0), "Clase Algo2"); Note: Fecha(5,10) and Horario(9,10) works just fin...
Recordatorio::Recordatorio(Fecha fecha, Horario horario, string mensaje) : fecha_(fecha), horario_(horario), mensaje_(mensaje) { } This will now use the default copy constructor for your classes rather than constructing an empty object then assigning it.
61,717,851
61,718,030
Initializing a c++ 11 style singleton
Say I have a singleton class App of which I obtain the instance of via: App& App::get() { static App instance; return instance; } From my research, when a singleton is required, this is apparently the best way to obtain it's instance. Suppose however that I need to pass a value once during the initial instanti...
Well, you could have a static pointer which points to a local static instance in init: // App.hpp #include <cassert> class App { public: static void init(bool const b) noexcept { static App ap{b}; _inst = &ap; } static App& get() noexcept { assert(_inst); return *_inst; ...
61,717,936
61,718,084
Undefined reference when using rust library in C++
I'm trying to use a Rust code in C. I used no mangle for Rust and extern "C" for C++ code that is going to be defined in Rust. However I keep getting undefined references whem trying to link my Rust library into my C++ code interface.rs use std::os::raw::{c_int}; type OnDataCallback = unsafe extern "C" fn(data: *mut u8...
Linker searches for symbols from left to right. Specify the library with symbols after the source file that needs them. g++ -o rust_c -L. interface.cpp -linterface Then add rust dependencies - -pthread and dlsym -ldl.
61,718,035
61,718,156
Why does this C++ method execute the last defined object's body instead of failing due to pointing to a dead object?
Consider the following C++ code: #include <iostream> using namespace std; class Hello { public: Hello(const char* name) : name(name) {} void body() { cout << name; cout << " body\n"; } const char* name; }; Hello* first; void create() { Hello wellington("Wellington"); ...
The surprising part: despite "first" pointing to a "dead" object, the body method is correctly executed.. Why is this surprising to you? Accessing through an invalid pointer has undefined behaviour. The behaviour is not guaranteed to be something other than "correctly executed" (for whatever is your expectation of "c...
61,718,203
61,718,380
glfw get monitor width/height
I am new to OpenGL, glfw in particular, and was wondering if it is possible to retrieve the preferred monitor's width/height (in C/C++)? e.g. something like: unsigned int width = glfwGetMonitorWidth(), height = glfwGetMonitorHeight();
If you need the monitor size in pixels - you must be looking for glfwGetVideoMode If you need the physical monitor size (in millimeters) - there is glfwGetMonitorPhysicalSize
61,718,234
61,718,630
is there an option that derive class can be inherited to base class in c++ OOP?
i have a point class which is inherited from the rectangle class(it is the assignment) can the rectangle class be inherited from the point class? 1.class Rectangle: public Point 2.class Point: public Rectangle
No. Inheritance cannot by cyclic. From object oriented design point of view, if all instances of class A are instances of the class B (in the object oriented sence), and if all instances of class B are instances of class A, then A and B should not be distinct classes - i.e. they should be the same class.
61,718,495
61,718,789
MPI address not mapped - MPI_Gather function
I have the following c code, have a large vector and is scattered through the different processor and then gather again, I have a custom MPI type that has been previously tested on another program: pixel *src = (pixel*) malloc(sizeof(pixel) * MAX_PIXELS); const int ROOT = 0; int pid, n_processors; pixel *receive_buffer...
I think you did not mean to pass the address of the receive_buffer point into the function, did you? You want MPI_Gather(receive_buffer, send_count, mpi_pixel_type, src, send_count, mpi_pixel_type, ROOT, MPI_COMM_WORLD);
61,718,576
61,718,742
Understanding compiler choice in resolving function overloading
I am compiling on a platform where int= 32 bits (gcc arm none eabi, cortex M3, GCC version 9) with the dialect set to C++17. I have a overloaded a method with both template versions and plain versions of the same method. The normal overloads are in a private base class but have been exposed through a using clause. c...
The reason you are getting an ambiguous overload error, is because an unsigned int could be implicitly converted to any of the overload argument types for MemoryStream::write. Since there is no direct overload for unsigned int, the compiler does not know which overload to select: template<typename T> typename std::enab...
61,718,860
61,718,919
Give container ownership of its children, but have children store a reference to their parent using smart pointers
I would like to have all the children of a Node in a tree to be owned by their parent, and have each child store a reference to its parent. That way, when a parent Node is destroyed, all of its children are automatically destroyed. I also expect that if the root Node of the tree is destroyed, the entire tree is safely ...
Your addChild member function should not be const for this to work. fixed exmple
61,718,925
61,719,010
Proper use of c++ namespace
I'm new to c++ and have a project with a handful of classes broken out into separate header and source files. It would be very convenient for a few of these classes to have access to shared utility methods for validating keyboard input. This is because I don't want the class methods to be clogged up with long, identica...
Yes, you can define functions in a namespace, and yes you can then use those functions in different parts of your program, and yes that is how you call them. No, there is no style or compiler problem with using namespaces.
61,718,942
61,718,958
How to overload + to sum 2 objects that are matrix in c++?
i have this class class Matrix { int size; std::unique_ptr<std::unique_ptr<int[]>[]> val; public: Matrix(int size1) { size=size1; val=std::make_unique< std::unique_ptr<int[]>[] >(size); ... } ... move constructor,move assignment operator Matrix& operator+(Matrix &m...
Return by value, as you should for operator+ most of the time: // vvv--Removed & vvvvv-----vvvvv--Const is more appropriate here Matrix operator+(Matrix const &m) const { ... } This will require a copy constructor, make sure to add that. Also note that you should probably collect your for-loop logic into an oper...
61,719,509
61,725,183
Flatten and restore a complex vector into a double vector and back
I have a vector containing complex values (either defined as std::vector<std::complex<double>> or arma::cx_vec) and would like to convert them into vectors containing double-values of twice the size. Afterwards I would like to convert them back again. Currently I use two loops (here from going from double-vectors to co...
std::complex<double> is explicitly called out as something that can be treated as a double[2] Array-oriented access For any object z of type complex<T>, reinterpret_cast<T(&)[2]>(z)[0] is the real part of z and reinterpret_cast<T(&)[2]>(z)[1] is the imaginary part of z. For any pointer to an element of an array of...
61,719,790
62,501,352
glfw how to destroy window in mainloop
I am trying to develop a program using glfw where the window closes in the main loop. However, I get this weird run time error: X Error of failed request: GLXBadDrawable Major opcode of failed request: 152 (GLX) Minor opcode of failed request: 11 (X_GLXSwapBuffers) Serial number of failed request: 158 Curre...
Yes, you can call glfwDestroyWindow in the main loop. Here's how I did it. #include <GLFW/glfw3.h> int main() { GLFWwindow* window; if(!glfwInit()) return -1; window = glfwCreateWindow(400, 400, "My Window", NULL, NULL); if(!window) { glfwTerminate(); return -1; }...
61,719,919
61,720,041
How to print out a vector which holds objects?
This question stems from a larger code I am working on but hopefully I can break it down to simplify: Say I have two classes, one which holds 2 integer variables, and another which contains a vector that holds the first class class TwoInts { int num1; int num2; } class NumHold { std::vector<TwoInts> numV...
Treat out how you would treat std::cout, then return it at the end of the function: std::ostream& operator<<(std::ostream& out, const NumHold &myNumHold){ //one possible output format for(const auto& twoInt : myNumHold.numVector){ out << twoInt.num1 << ", " << twoInt.num2 << '\n'; //pretend out is std::...
61,719,944
61,720,019
std::string constructor with lvalue throws with clang
I am making use of Matei David's handy C++ wrapper for zlib, but I get an error when compiling on macOs (clang-1100.0.33. include/strict_fstream.hpp:39:37: error: cannot initialize a parameter of type 'const char *' with an lvalue of type 'int' The problem is here: /// Overload of error-reporting function, to enable ...
If you use int strerror_r(int errnum, char *buf, size_t buflen);, then there is no appropriate string constructor and the program is ill formed. If you use char *strerror_r(int errnum, char *buf, size_t buflen);, then the program is well-formed. The standard C/POSIX library implementation influences which function you ...
61,720,009
61,720,469
How to write fast modules like numpy for python?
How can we write a massive - fast module for python? I mean how they write a module like numpy that executes heavy pieces of code in python (which is very slow) so fast? Are they using the C/Python API for that matter? Or it's something else?
Extension can be written in C/C++ with connectors to other python objects and functions. The official python documentation has a C/C++ API reference
61,720,368
61,721,878
Polymorphism - Pointing to Classes program fails to compile
This example is from C++ in easy steps 5th ed (Mike McGrath) - Ch 8 Polymorphism, "Pointing to Classes". I was wondering if anyone ran into this before or know why this fails to compile. I followed the example from the book and for some reason my program fails to compile and throws an exception related to casting. I e...
Try changing this line ptrA -> Identify((int) &ptrA); to this ptrA -> Identify((long) &ptrA); On most platforms pointers and longs are the same size, but ints and pointers often are not the same size on 64bit platforms. If you convert (Base*) to (long) no precision is lost, then by assigning the (long) to an (int), it ...
61,720,409
61,720,511
C++ encapsulation, how is it useful
The following slide refers to C++ language and it says that "encapsulation is about ensuring the user uses our ADT in a safe way" But, If he have access to my .h files he can edit it for example and change what was declared inside my class from private to public. for example: my_file.h: class Complex { private: ...
With C++ you can shoot into your foot in a lot of ways. You can also use #define private public and you won't need to change anything in the code to access the private interface... the point here is not how encapsulation can be broken, instead is about what you achieve using that. When you have to choose between cla...
61,720,415
61,720,527
How do I read a stringstream into a char *[40] / char ** array?
I am working on creating a UNIX shell for a lab assignment. Part of this involves storing a history of the past 10 commands, including the arguments passed. I'm storing each command as a C++ string, but the parts of the program that actually matter, and that I had no input in designing (such as execve) use char * and c...
This line: chars[i] = (char *)test_2.c_str(); leaves chars[i] 'dangling' when you go back round the loop or fall off the end. This is because test_2.c_str() is only valid while test_2 is in scope. You'd do better to do something like this: #include <sstream> #include <iostream> #include <string> #include <vector> #in...
61,720,424
61,720,465
C++ can't access public members
I'm a new C++ learner. Given the following code in C++, why I can't access this.init() in a function even though it's public? class Complex { private: double re, im; public: void init(double x, double y); void add(Complex c); double abs(double x)const; static int Num; Complex(double x,double y=...
Your abs function is marked const: double Complex::abs(double x) const; and so when is called, the caller object is guarantee not to change, and so if you try to change the value of Num compiler won't let you do it, because you are violating the constness of the objects
61,720,768
61,720,895
Why casting in C++ prints an unexpected result?
I know basics of casting in C++—or I thought I knew. Yesterday, I was trying to convert an 8-element uint_8 type array to a 2-element uint_32 type array. I cast my values to 32bit format and while trying to display them into 32bit format, the computer gives me their address not their values.. You can see where I became...
Many of your print statements cause undefined behaviour or don't make sense. std::cout << "Address of info " << &info << std::endl; //Output 0x7ffdd25cabe0 as expected. This line prints the address of your array. As you see, you get some pointer value out. std::cout << "Expected value of info " << (uint8_t*)info<< st...
61,721,259
61,721,364
C++ different declarations of an object
I have started learning C++ and totally confused of the difference between: Array a(20); Array* ptr = Array(20); I read that if the first was written inside a block it will be freed after the end of it automatically, but the second one will leak memory. But why is that? what each-one stands for? Plus, how should I de...
Array a(20); This declares a variable of type Array. It is initialised with the expression 20, which resolves to the constructor Array(int). The storage class of the object depends on the context. If it is within a block scope, then the object has automatic storage. Objects with automatic storage are destroyed autom...
61,721,261
61,721,798
Element wise inversion in Eigen Matrix
Is there a function/s for doing elementwise inversion of an Eigen Matrix #include <eigen3/Eigen/Dense> const auto mat = Eigen::MatrixXd::Constant(3, 3, 5); std::cout << mat; 5 5 5 5 5 5 5 5 5 And my expected result is this: 1/5 1/5 1/5 1/5 1/5 1/5 1/5 1/5 1/5 Is there any other way to do this apart from using a for...
Solved this issue. Just putting here in case anyone else comes across this issue mat.cwiseInverse() Link to all co-efficient wise functions for eigen
61,721,337
61,721,418
Qt segmentation fault on setlayout
I'm trying to creat a Settings panel which inherits from QWidget. However, when it shows, it receive SIGSEV from my system because of Segmentation fault. Here is my code: //settings.h #ifndef SETTINGS_H #define SETTINGS_H #include <QWidget> class QRadioButton; class QGroupBox; class QPushButton; class QEventLoop; class...
I'm not 100% sure why calling setLayout() causes a crash, but I do know that there is a better way to construct your GUI that doesn't require calls to setLayout(). Instead of calling setLayout(), when you create a QVBoxLayout or QHBoxLayout object, pass in a pointer to the QWidget you want it to manage, as an argument...
61,721,563
61,781,336
Passing a Delegate to a callback function in unmanaged code using c#
I have to register a callback function written in unmanaged code from c#. I have written the following codes: //Declaration for c++ code [DllImport("sdk.dll")] public static extern void sdkSetDequeueCallback(DequeueCallback cbfunc); //call back delegate [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegat...
You need to insure your 'Deque' reference is alive and not overwritten as long as the callback is being used in C++. You are responsible for holding delegate C# object alive as long as the corresponding C++ callback is used. Better yet, just use Scapix Language Bridge, it generates C++ to C# bindings (including callbac...
61,721,791
61,722,067
MSBuild fails to build Visual Studio Project due to missing property files (potentially IDE related)
I'm trying to get Jenkins running in a docker windows container and I've got most everything set up but I continue to run into a compilation error: 22:21:06 C:\JENKINS_HOME\workspace\iCEWav\src\engine\IceLibrary\IceLibrary.vcxproj(27,3): error MSB4019: The imported project "C:\Program Files (x86)\Microsoft Visual Studi...
Well that didn't take too long. According to documentation, MSBuild is actually not apart of the recommended or required workload for VCTools. The MSBuild that was already on the Docker container came from the base image provided by Micosoft and lacked the VC tools (mcr.microsoft.com/dotnet/framework/sdk:4.7.2-windowss...
61,721,802
61,726,705
returning multiple values from recursive function c++
i have a recursive search function that returns the index of my vector where the search key was found However sometimes my vector can have two different positions that have the same key but my function only returns the first one. here is my function: int IdeaBank::twoSearchAND(int first, int last, string word_1, strin...
You might collect results into a container such as std::vector. To avoid extra copies to concatenate vectors if used as return value, I use it as output parameter in the recursive method. void IdeaBank::twoSearchAND(int first, int last, const std::string& word_1, const std::string& word_2, ...
61,721,835
61,722,188
Understanding when shared_ptr reference counts are incremented when passing into a function
I have the following Container class template <typename T> class Container { private: std::vector<std::shared_ptr<T>> items_; public: void addItem(std::shared_ptr<T> item) { std::cout << "useCount addItem pre: " << item.use_count() << std::endl; items_.push_back(std::move(item)); std...
std::move moves the item out of that variable into another one. As one author put it, it "has explicit license to pillage [the variable]." For most std objects, that puts the original object into an unspecified state. However, it appears std:shared_ptr is an exception in that it leaves the object in an empty state. Wha...
61,721,976
61,722,133
Which static library should I link when using wingdi.h?
Recently I've tried FLTK. After I compiled the source code, I want to create a tiny application using FLTK. However, after I tried to complie it, g++ said: C:\Program Files (x86)\FLTK\lib/libfltk.a(Fl_Window_shape.cxx.obj):Fl_Window_shape.cxx:(.text+0x298): undefined reference to '__imp_ExtCreateRegion' C:\Program F...
Most functions declared in wingdi.h require linking to gdi32.lib. For example, ExtCreateRegion is documented here, and among the details at the bottom of that page are: Header:     wingdi.h  (include Windows.h) Library:     Gdi32.lib DLL:         Gdi32.dll which static library should I link? gdi32.lib is not a stat...
61,722,072
61,722,414
What does this operator do in c++?
What does : do in C++? is there any difference with ? : is it an operator? for example in code below: // Extracting the coefficients and exponents as numbers int expon[21] = { 0 }; int coeff[21] = { 0 }; for (int i = 0; i < monoms; ++i) { int monomSize = monomStr[i].size(); for (int...
The ?: syntax is called the ternary operator, or also sometimes called the conditional operator. The : syntax is called a range-based loop. As for the differences between the two, the conditional operator is sort of a shorthand for if statements. The range-based loop is (as you might guess) a shorthand of sorts for a l...
61,722,324
61,722,638
C++ How to implement A* with new nodes calculated on the fly?
I am trying to use A* for a search problem where I begin in a certain state of a matrix (e.g. all zeros), and each step I can perform one of several transformations on the matrix and I want to arrive in another state of the matrix (e.g. all ones). The search nodes also store some other auxiliary objects. As a result, ...
So I could have two Nodes with the exact same state and different addresses. If that's all that your problem was, the answer would simply be a matter of using a unordered_set<Node> instead of just newing Nodes, and make sure that your Node class has a proper hash function associated with it. This will take care of de...
61,722,547
61,725,212
Why QT QSqlTableModel does not sort Chinese correctly?
I save data with sqlite,and one of the columns is Chinese text.I use QSqlTableModel+QTableView.But When I excute "Model->setSort(0, Qt::AscendingOrder)" and the data of column 0 is Chinese,it doesn't sort correctly.I know this may be a coding problem, but I don't know how to modify SQLite's coding,
Not a coding problem. QSortFilterProxyModel can be used. Below is the sample code: #include <QApplication> #include <QSortFilterProxyModel> #include <QTableView> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQueryModel> int main(int argc, char* argv[]) { QApplication a(argc, argv); QSqlDatabase db = QSqlDatab...
61,722,723
61,723,162
How can I escape the switch and while(1) loop?
Thanks for stopping by to see this. This was made from Visual c++. I wanted to make a random problem with a random number and arithmetic operations. It's supposed to give me a new problem until I get the right answer and when I get the right answer, It's supposed to be stopped and closed. But, even if I get the right a...
I thought the *1 break around the bottom would let me escape but It didn't work. I'll appreciate it in advance. It will break the loop. But it will break the loop for both incorrect and correct answers (which isn't what you want). I think you get confused by another bug which is in the switch-case statement. For each...
61,722,802
61,725,455
How do only a task of nested loop run on thread on OpenMP
I'm trying to make a program that multiplies two arrays in parallel so that each thread multiplies a row by a column. The problem is that if I put the omp for in the outside for, the thread will execute the entire internal for instead of just executing the task, and if I put the omp for in the inside for, the for from ...
One of the options is to use collapse clause: https://stackoverflow.com/a/13357158/2485717 You may also rewrite your for loop to avoid being nested: for (int i = 0; i < n * n; ++i) { int line = i % n; int column = i / n; multiply_line_per_column(line, column); } As pointed out by @Hristo Iliev in the com...
61,723,200
61,723,517
Returning a weak_ptr member variable
I have the following TreeNode class which can store a reference to its parent node as well as a vector of pointers to all its children. TreeNode class TreeNode : public std::enable_shared_from_this<TreeNode> { private: int val_; std::weak_ptr<TreeNode> parent_; std::vector<std::shared_ptr<TreeNode>> childre...
There's no way around calling lock on a weak_ptr, the whole point of weak_ptr is that it doesn't count towards reference counting of the object that it is pointing to, while still allowing to use the control block to check if the object is valid or not, and then get a shared_ptr. For me it looks like parent_ shouldn't ...
61,723,579
61,723,647
Time limit exceeded even after doing an upper_bound on the array
Language used : C++14. I am given 2 sorted arrays A and B. Now, for each element in A i have to find a greater element in B if it is possible and note that once i have found an element in B for a particular element in A, i can only search ahead of that index in B . I am doing something like this: int j=0; for(i=0;i < A...
First of all make sure that the first iterator in your upper_bound is <= second iterator as it may happen that for some number the last element in array B is greater than it, so now if you do j = index + 1, it will be equal to B.end(), now searching for any greater element would always return some integer greater than ...
61,724,430
61,725,063
Checking whether a String is a Lapindrome or not
The question is to check whether a given string is a lapindrome or not(CodeChef). According to the question, Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. I have tried solving the problem using C++ with the code below ...
Replace the lapindrome function to this one: bool isLapindrome(std::string str) { int val1[MAX] = {0}; int val2[MAX] = {0}; int n = str.length(); if (n == 1) return true; for (int i = 0, j = n - 1; i < j; i++, j--) { val1[str[i] - 'a']++; val2[str[j] - 'a']++; } ...
61,724,567
61,724,894
const correctness for custom reference wrapper
I'm using boost::variant to implement type erasure when sending data across network. When the data arrives to the client or server, I'm inspecting its structure to retrieve the underlying information and reporting errors when the structure does not match the one agreed upon in the API. For this purpose, I created a lig...
Returning const object is mostly useless, as auto /*view_t*/ my_view = cview(some_value); // legal So you lose your constness. Modifying const value is undefined behavior, your view can be used in a way leading to UB. But as long you don't modify const object, you are "fine". Splitting into 2 classes is safer, as it c...
61,724,809
61,802,310
Creating a new registry key using the NtCreateKey() NTAPI function [NtOpenKey() function returns a NTSTATUS error value of -1073741772]
I am written the following code to create a new key in the registry but an NTSTATUS error value of -1073741772 is returned by the NtOpenKey() function when attempting to fetch the handle of the base key to create a new key. typedef NTSTATUS(*LPCREATEKEY) (PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, ULONG, PUNICODE_STRING...
This is how a new key is created in the registry using the NTAPI functions. #include <winternl.h> typedef NTSTATUS(*LPCREATEKEY) (PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, ULONG, PUNICODE_STRING, ULONG, PULONG); HINSTANCE dll = nullptr; LPCREATEKEY ntCreateKey = nullptr; HANDLE createdKey = nullptr; UNICODE_STRING ne...
61,725,198
61,725,437
Is it safe to use LPCTSTR in a structure with the WM_COPYDATA message?
I have this structure: typedef struct tagCOPY_PACKET { TCHAR szFile[_MAX_PATH]; GUID guidSignature; } S_COPY_PACKET; I prepare to send data with WM_COPYDATA like this: CString strFile = GetFileToOpenFromFileExplorerPath(); S_COPY_PACKET sCopyDataPacket; _tcscpy_s(sCopyDataPacket.szFile, _MAX_PATH, strFile); ...
The documentation of WM_COPYDATA says: The data being passed must not contain pointers or other references to objects not accessible to the application receiving the data. Therefore, when CMeetingScheduleAssistantDlg lives in a different executable, you cannot pass an LPCTSTR value. If it is in the same executable, c...
61,725,240
61,725,780
C++ code that cannot access private members of a class using derived class
I've currently got code below in which i am trying to initialize the data members x, y and z to 0 when an object of type Solid is being instantiated. The lines 25, 26 and 27 contain errors, how would I rewrite these lines to access the x and y members and set them to 0? edit 1: I've written out my code below. edit 2: T...
You can't access private members of a base class, and the point of this exercise is that you don't need to - not that you should come up with a way of doing it. Your default constructor should only set its own member - Shapes default constructor takes care of its own members: Solid() { z = 0; } or (the preferred metho...
61,725,632
61,726,286
Circular inclusion with function inside namespace
I'm starting to learn C++ and recently encountered a problem with circular dependency of two headers. I've already tried forward declaring the Class and namespace, also played around with it in a seperate project but didn't find any solution. Whatever I do the function doesn't get access to the class private members. H...
You need to change A.h to include a forward declaration of getDataChunk() in namespace Byte: #pragma once #include "B.h" class Player; namespace Byte { void getDataChunk(Player& p); } class Player { private: int m_number; public: friend void Byte::getDataChunk(Player& p); }; Please note also that includ...
61,725,661
61,725,697
How can you use C++ in IntelliJ IDEA?
The question is in the title. So far I've only used IntelliJ for Java. Do I need to download some sort of Compiler or how can I create C++ files?
You should use CLion instead. It's the JetBrains IDE for C/C++.
61,725,758
61,725,885
Comparing two chrono timepoints with operators
How do i compare two chrono timepoints in C++20? This link says that the > and < operators are deprecated in C++20 ?
They are deprecated in favour of the comparisons automatically provided by the implementation of operator<=>. You can still compare with < or >, it's just that explicit definitions for these operators is no longer necessary.
61,726,229
61,745,915
In win32 api using c++ i want to track double click and triple click and so on
LRESULT handleDoubleClicks(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, POINT ptLastClickPos, DWORD dwLastClickTime) { DWORD dwClickTime = GetMessageTime(); POINT ptClickPos = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; switch(message) { case WM_LBUTTONDOWN: if (dwLastClickTim...
You could use SetTimer, after one click, not immediately judge it as a click, but start the timer, check whether there is another click within the timer range, if there is, it is judged as double-click, if not, and the previous time is determined as a single click. #define TIMER_ID 10 static int click_count = 0; static...
61,726,264
61,726,716
Why is a member function with a pointer parameter requiring a pointer to a pointer?
I have a generic class: template<typename T> class QuadTree { The class has member variables for its nodes like this QuadTree<T*>* nw; The problem that I have is with following member function: bool insert(T *obj) { //... if (nw->insert(obj)) return true; //... I thought this would work, but ...
In your class template... template<typename T> class QuadTree {} ... if T is a pointer during instantiation (which it is)... QuadTree<T*>* nw; //NOTE <T*>, not <T> ... this implies that bool insert(T* obj) , when instantiated, becomes bool insert((T*)* obj) (as T was already type pointer - brackets for emphasis). The...