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
71,314,675
71,314,950
How to listen to all keypresses in Winapi and cancel some of them?
I'm trying to write an keyboard software debounce program in C(++) for my crappy keyboard that double-clicks. I apparently need to set a hook to WM_KEYBOARD_LL, but I a) couldn't do it, I have "invalid handle" errors and b) don't know how to cancel the keypresses, as I also want to do this for gaming. How would I prope...
I apparently need to set a hook to WM_KEYBOARD_LL, but I ... couldn't do it, I have "invalid handle" errors Per the SetWindowsHookEx() documentation: An error may occur if the hMod parameter is NULL and the dwThreadId parameter is zero or specifies the identifier of a thread created by another process. Which is exa...
71,315,077
71,315,344
Linked list push_back with an unusual behavior in c++
That's the code: #include <iostream> #include <string.h> using namespace std; class List; class Node{ char data; public: Node(char d):data(d),next(NULL){} // INICIALIZAÇÃO CONHECIDA COMO: inicialization list Node* next; char getData(){ return data; } ~Node(){ if(next!=NULL){ ...
The bug is in your insert function. If you try to insert at the end of your List, you never update tail. A simple solution without modifying your code too much is to check if temp is equal to tail and just call push_back directly. This code seems to work on my system. void insert(char data, int pos){ if(p...
71,315,224
71,327,438
Can a recursive/self-referential template (using pointers) be instantiated and/or specialized in C++?
I want to instantiate a template from the STL, using maps,vectors, and arrays, as follows: map<some_type,vector<map<some_type,vector...>*>> elements; The ellipses is just pseudo-code to represent the infinitely recursive definition, which is ofcourse impossible to type out. Basically, the vector should just hold poin...
You were on the right track by abstracting out the recursion variable: template <typename Self> using F = std::map<int, std::vector<Self*>>; The problem is to find a type T such that T == F<T>. This is known as finding the fixed point. In these terms, we want a template Fix taking a template template parameter such th...
71,315,334
71,315,599
Malloc always returns a NULL pointer; Visual Studio 2022
This may be a duplicate question but I checked out other question like this and never really found what I was looking for (or so i believe). Consider the following code: #include <iostream> #include <stdlib.h> int main() { char* s = (char*)malloc(2 * sizeof(char)); *s = 'M'; s++; *s = 'I'; s...
To be clear, that message is a warning by the compiler, its not that you are getting null from malloc, it warns that you might and have not checked https://learn.microsoft.com/en-us/cpp/code-quality/c6011?view=msvc-170 The message goes away if you do char* s = (char*)malloc(2 * sizeof(char)); if (s != NULL) { *s = ...
71,315,402
71,315,682
Capture OpenGL output of child process?
Is there any possibility of capturing opengl output of child process? Child should not have a different window. Output should be captured and displayed by parent instead. I know that i can create a layer that my child could use to create opengl callbacks in my parent application. And send data by socket or pipe. Edit: ...
OK, here's a rundown of how I think this can be done. This is totally untested, so YMMV. Create your window in the parent process. According to this page, you need to create it with the CS_OWNDC style, which means it has the same HDC permanently associated with it. Launch your child process. You can pass the HWND ...
71,315,769
71,316,200
buffer problem when making serial communication with C++
I am working on for serial communication using C++. I am calling linux command with C++. One port I am using works as transmitter and the other part is working as a receiver. This is how transmitter works, #include <stdio.h> #include <unistd.h> #include <iostream> #include <fstream> using namespace std; ofstream wfil...
Things to fix Check return value of fgets() Simplify as desired. if (fgets(var,sizeof(var),fp)) { printf("<%s>\n",var); } else { printf("Nothing this time.\n"); } GTG
71,316,137
71,316,509
Running a Linux Executable from C/C++ Executable Without Use of system() or system() Wrappers
I am looking for a way to execute a Linux executable from a separate Linux Executable that was compiled from C or C++. However, I have looked at numerous Stack Overflow posts which all direct the user asking to use the system() function or a wrapper of the system function and I do not want a program that relies on the ...
execve() is not a wrapper for system(); it is a wrapper for the execve syscall itself. execve() replaces the current process, so you’ll probably need to fork() and then execute execve() in the child process, thereby emulating the behaviour of system().
71,316,418
71,316,515
"No instance of constructor" error for all std data types (map, vector, stack, etc.)
I'm running into a weird problem. I'm thinking this could be possibly due to something wrong with Mac, but I'm not sure. Essentially, I solved this Leetcode problem on my windows laptop and pushed the code to my github repo. Then I fetched that code on my mac later on and all the sudden I get this error when trying to ...
Use -std=c++11 (or higher). You are trying to use constructors from std::initializer_list that were introduced in C++11. For further information, see the documentation for vectors and maps.
71,316,590
71,316,637
increment hex value by a certain value in C++?
I have a hexadecimal variable that I want to increase its inc value by x20 in every loop. For example for 10 rounds, inc value increase by 0x20 and add to the pam in each loop. but now i'm getting 1060,1061,1063,1066,106a,106f,1075 etc... int main() { int inc = 0x20; int pam = 0x1040; for ( int i = 0; i < 10; i ...
Here's a method to increment numbers using a fixed increment: const int inc = 0x20; //... for (int i = 0; i < 10; ++i) { pam += inc; std::cout << "pam: " << pam << "\n"; } If you can't modify pam then modify the increment: int inc = 0x20; for (int i = 0; i < 10; ++i) { inc += 0x20; std::cout << (pam + inc)...
71,316,613
71,317,083
notify_one only when there are waiting threads is correct?
I've seen the following type of a dispatch queue implementation several times where the thread pushing a new element to the queue calls notify_one only when the queue was empty before pushing the element. This condition would reduce unnecessary notify_one calls because q.size() != 0 before pushing a new element means t...
For the operation after wake up According to wake's doc Atomically unlocks lock, blocks the current executing thread, and adds it to the list of threads waiting on *this. The thread will be unblocked when notify_all() or notify_one() is executed. It may also be unblocked spuriously. When unblocked, regardless of the ...
71,317,146
71,317,166
returning the value of private dynamic int results in seg fault
I'm doing a quick test to see how to get the value of a dynamically allocated private data member to another dynamically allocated variable outside of the class, but I'm having trouble returning their value. Whenever I try, I result in a segmentation fault at runtime. I've been slowly simplifying the code and even redu...
There is null pointer referencing problem in here. Allocate some memory and initialize the test or make test point some other int. EDIT : As @songyuanyao pointed out, the constructor did not initialized original testing::asdf, but new local variable asdf. You also should remove int* specifier to avoid that problem. int...
71,317,172
71,317,544
cpp compare_exchange_strong fails spuriously?
So I'm pretty new to CPP and i was trying to implement a resource pool (SQLITE connections), for a small project that I'm developing. The problem is that I have a list(vector) with objects created at the beginning of the program, that have the given connection and its availability (atomic_bool). If my program requests ...
The code results in undefined behavior in a multithreaded environment. While the loop for(auto & pair : pool) is runing in one thread, pool.emplace_back(std::make_shared<pool_elem>()) in another thread invalidates pool iterators that are used in the running loop under the hood. You have the error in the loop. std::atom...
71,317,234
71,317,301
Need to see if character is in array but not in same position as other array c++
I'm making a wordle in C++ and I need to check two char arrays against each other to see if the letter in one is in the other one but not in the same position, here's my code so far, the second if in the for loop is where I need help (its going to be colored that's the reason for the constants and the color codes): #in...
You can call std::find: #include <algorithm> ... if (guess[i] != word[i] && std::find(word, word+5, guess[i]) != word + 5) { .. } See std::find in cppreference doc.
71,317,624
71,317,811
how to apply operator overloading for unary postfix operator
below is code for operator overloading for unary operator ++ #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance() { feet = 0; inches ...
if you want post-inc/dec then the code will be : Distance operator++ (int) { feet = feet+1; inches = inches+1; return Distance(feet, inches); } we use int in formal parameter . it is just crate different between post/pre-fix. The prefix form of the operator is declared exactly the same way as ...
71,317,952
71,318,035
I'm a newbie in C++,and I 'm now stuck in pointer
I create a function to display the element of an array with position shift to right 3,In case the element overload if will shift to the left, I used pointer to pass by value.The code almost worked but it display 0 instead of input elements. Can somebody show me why, pls! #include <iostream> #include <cmath> using names...
Actually, your bound check is actually out of bound. The array index starts from 0, and ends in size-1, and if you want to shift the element, you should substract size, not 2. In addition, you did not initialized i in the for loops in your program, which leads to undefined behavior. Here's my modification: int * sort(c...
71,318,755
71,320,029
Why can't functions with same name and argument type check can't co-exist?
I expected the 2 definitions below to co-exist because i am adding a type checking code but it gives error as already declared. Why so and what needs to be changed? #include <iostream> #include <type_traits> template<class T, class = std::enable_if_t<std::is_integral_v<T>>> bool is_even(T value) { return ((value %...
Why so and what needs to be changed? From std::enable_if 's documentation: A common mistake is to declare two function templates that differ only in their default template arguments. This does not work because the declarations are treated as redeclarations of the same function template (default template arguments ar...
71,318,828
71,318,963
What's wrong with my comparator? How to fix it?
I want to find k nearest neighbors of a 2d point from a each point within a vector of point. The comparator is defined as a class and the criteria is the distance of each point of the vector from the inquiry point. MVW: #include<iostream> #include<fstream> #include<functional> #include<algorithm> #include<vector> #incl...
The ordering argument must be a type, but you're passing an object. You pass an argument of this type when constructing the queue. priority_queue<Point_CCS_xy, vector<Point_CCS_xy>, Less_Distance> pQ(nearer_point);
71,318,980
71,319,850
Memory alignment and strict aliasing for continuous block of raw bytes
I have a question about using same continuous block of raw bytes as storage of various typed objects from the point of C++ standard rules. Consider we create continuous block of raw bytes, f.e. void *data = ::operator new(100); // 100 bytes of raw data - not typed Could then we use this memory like: template<class T> ...
First, it is unclear from your question, but I will assume that there is no other code inbetween the individual snippets you are showing. Snippet 1. has undefined behavior because the pointer get will return cannot actually be pointing to a float object. ::operator new does implicitly create objects and return a pointe...
71,319,351
71,319,352
Treat specific warning as error for C++ project in Visual Studio
I want to treat a specific warning as an error, and I want to configure that in Visual Studio (2019 in particular). From this question or this MSDN page I know it must be possible. I just con't figure out how to do it in Visual Studio. My project is a C++ project and I'm in the project settings under C++ / Advanced. Th...
Enter the numbers only, i.e. 4390. For multiple warnings, enter them semicolon separated: 4390;4391. If you don't see it in the command line, click the "Apply" button. In the command line, they will appear as /We"...".
71,319,773
71,319,891
What is the correct placement of names and types in the typedef syntax?
Usually the syntax of typedef is as follows typedef <existing_name> <new_name> But in the following case, I am bit confused typedef char yes[1]; typedef char no[2]; This above seems to work. Why and how? Shouldn't this be written as below? typedef yes char[1]; typedef no char[2];
Usually the syntax of typedef is... No, that's not accurate. The usual syntax is typedef <variable declaration>; Then the declaration is decomposed, and the name of the variable becomes a new name for the type the variable would have had. The case you are confused about is inline with that. In the absence of typedef...
71,319,788
71,320,014
possible to using defined name from class outside of class?
I want to keep the actual struct hidden, but provide a interface name for user. so my code goes: class A { private: struct B{...}; public: using BPtr = B*; B* funct(){...}; } my usage would be A a; BPtr p = a.funct();
The full name is A::BPtr, so this will work: A::BPtr p = a.funct(); On the other hand, this is pretty pointless, as only the name "B" is private – the class definition isn't. For example, class A { private: struct B{ int x = 1234; } b; public: using BPtr = B*; B* funct(){ return &b; }; }; int main() { A a; ...
71,320,007
71,320,106
"0" appearing after function is completed in C++
// This program is able take two variables` // and apply Auto increment or decrement` // based on the user's input and by calling a function #include <iostream> using namespace std; int inc (int, int); // Increment function prototype int dec (int, int); // Decrement function prototype int main () { int num1, n...
This happens because your inc and dec print stuff, but also return an int. You then proceed to print the return value, on these lines: cout << inc(num1,num2); and cout << dec(num1,num2); . You can safely remove these cout << prefixes, and probably the entire return value, as it does not seem necessary to output your...
71,320,049
71,320,401
binary tree traversal code explaination needed
I have a question on how this binary tree traversal code works. void BinaryTree_Functions::preorder(Binary_TreeNode* bt) { if (bt == NULL) { return; } cout << bt->data <<endl; preorder(bt->Left); preorder(bt->Right); } preorder traversal void BinaryTree_Functions::inorder(B...
It is dificult to explain when you don't say what specifically is confusing you. The issue seems to be recursion. To see more easily what happens you could use an example tree and see how the output differs. To see how the different orders traverse the three differently you can also look at this fake tree: #include<ios...
71,320,674
71,320,884
Modifying inner elements of std pmr vector
If I understand things well, a std::pmr::vector<std::pmr::string> should use the same underlying std::pmr::memory_resource Let's say we have something near to class MyMemoryResource : public std::pmr::memory_resource{...}; std::pmr::vector<std::pmr::string> vector; vector.push_back("short string"); vector.push_back("...
Option 3 is not permitted. The allocator has no knowledge of how the memory it allocates is used. All it gets is std::size_t bytes, std::size_t alignment for each request. Reallocating the vector would invalidate pointers, references and iterators. MyMemoryResource needs to have a strategy to deal will all possible seq...
71,320,678
71,324,335
How to understand such "two consecutive templates" in c++ by using a mimic minimum example?
I only understan some simple template usage in C++. Recently I met the following code snippet from some OpenFOAM code, and it confues me for weeks long. (1) Could you please help me by giving a minimum working example to explain such "two consecutive templates" usage? (2) Can I just replace the two tempalte with single...
It's when you define a member template in a class template. A common example will be a copy assignment operator for a template class. Consider the code template <typename T> class Foo { // Foo& operator= (const Foo&); // can only be assigned from the current specilization template <typename U> Foo& operato...
71,320,797
71,320,924
How to simplify this logical expression in a single return statement?
I have been trying to simplify this function in a single return A ... B ... C statement but some cases always slip out. How could this checks be expressed in a logical way (with and, or, not, etc.)? bool f(bool C, bool B, bool A) { if (A) return true; if (B) return false; if (C) return true; return fa...
bool f(bool C, bool B, bool A) { if (A) return true; if (B) return false; if (C) return true; return false; } is equivalent to bool f(bool C, bool B, bool A) { if (A) return true; else if (B) return false; else if (C) return true; else return false; } is equivalent to: bool f(bool C...
71,320,810
71,331,422
Function descriptors in Microsoft Visual Studio
I have ben using microsoft visual studio for some time, and just discovered that you can give parameter descriptions for the functions. But I would also like to be able to use something like pre and post descriptions for the functions, is that possible? For info; I'm using Microsoft visual studio (as mentioned) Using ...
The XML document automatically generated after typing "///" is supported in Visual Studio 2019 16.6 and later versions. Examples are as follows: I entered "output a character" in <summary></summary>, so "output a character" appears in the function description below.
71,320,821
71,323,833
Macro redefinition problem in C++ header file
When I try to run the following header https://github.com/marmalade/glib/blob/master/glibconfig.h in Microsoft Visual Studio, I get the following error: 'G_CAN_INLINE': macro redefinition. What is the reason for this? Any help is appreciated. Thanks.
There's actually a trick for this which might work for you. What you can do is this: Comment out the #define(s) for G_CAN_INLINE in glibconfig.h (make a copy first!). After the relevant #include, add (temporarily) the following line to the source file that is generating the compiler error: int any_old_variable_nam...
71,321,404
71,321,445
Process from standard input line by line
Given problem like this: Find the min and max from a list of integers. There are T test cases, for each test, print no. of current test cases and the answer. Input.txt file 3 3 4 5 1 2 100 22 3 500 60 18 1000 77 10 300 Output Test case 1: Max :5, Min :1 Test case 2: Max :500, Min :3 Test case 3: Max :1000, Min :10 In...
In C++, how can I process only one line from standard input in each test case iteration. std::getline reads until it finds a line break (thats the default, other delmiters can be used). Replace while(cin>>n) { arrayInt.push_back(n); } With std::string line; std::getline(std::cin, line); s...
71,321,808
71,321,929
Is there any way to delete a dynamically allocated array in another function?
I am learning pointers in C++. This is the exercise given by my teacher: 6. Duplicate a given array. int* copyArray(int* arr, int n) My function: int* copyArray(int* arr, int n) { int* copy = new int[n]; for (int i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } My main function: int main() {...
My suspicion is that you are confused by the usual imprecision when we say "delete a pointer". More correct would be to say delete[] x deletes the array that x points to. In main you do copyPtr = copyArray(a, 8); Now copyPtr does point to the copy of the array. When you write delete[] copyPtr; You delete the copy of ...
71,321,863
71,321,993
read values of reference direct by std::pair<std::array<std::array<u_int16_t,2>,1>,std::string>>
can someone tell me how to access the individual values directly? To really use the referent of out and not store in the temporary variable PosTextfield and val between. #include <iostream> #include <utility> #include <string> #include <cstdint> #include <array> using Cursor_matrix = std::array<std::array<uint16_t,2>,...
std::get returns references. You can just store these references: const auto& PosTextfield = std::get<0>(out); const auto& val = std::get<1>(out); or const auto& PosTextfield = out.first; const auto& val = out.second; or you can replace the auto keywords with the actual types if you prefer. const can be removed as we...
71,322,076
71,323,330
Use C++ 20 modules to make shared libs
I'm looking C++20 modules, and I'm asking how to make shared libs with modules. All examples (I've found), works in same directory (lib + main) so there is no problem on compilation time. But if I want to make a .so file, and import it into another program in another dir. g++ give me (I've used that code https://gcc.gn...
Well, the error message tells you where the compiler is looking for that file, and it certainly isn't /usr/local/lib, so that's not going to work. You could distribute the gcm file and instruct the user to put it in the gcm.cache directory for their project I suppose, but, quoting from the link you posted (emphasis th...
71,322,100
71,322,307
push_back() is not adding element to the vector? (C++ Tree Traversal)
I'm working through a tree traversal problem and using 'push_back' vector function to update a vector with the in-order traversal. Alongside using this I am using cout to print out the solution to debug. The print output is correct but my returning vector doesn't match the print so I can only put this down to me not un...
You're ignoring the results from each recursion. You should be doing this: vector<int> inorderTraversal(TreeNode *root) { vector<int> order; if (root != nullptr) { order = inorderTraversal(root->left); cout << "pushing back : " << root->val << std::endl; order.push_back(root->val); ...
71,322,445
71,322,549
How to get QString::fromAscii in Qt5?
I have a function to get the name of the computer as QString. While updating my program to Qt5 the function QString::fromAscii still doesn't exist anymore. How can I get it to QString? QString AppConfig::GetMachinename() { char* buf = new char[512]; DWORD size; int res; QString m...
From the Qt documentation for the (obsolete) fromAscii function: This function does the same as fromLatin1(). So, try this code: //... if ((res = GetComputerNameA(buf, &size))) { machineName = QString::fromLatin1(buf, size); } Further documentation for the newer, replacement function.
71,322,981
71,323,155
object destruction & delegating constructor
According to this question about delegating constructors, a destructor is called when the first constructor has finished. This is consistent with the following code: struct test { test() { std::cout << "default constr\n"; } test(int) : test() { std::cout << "argument constr\n"; throw int{}; } ~test() { std:...
Am I misreading this I don't think so. or does he mean something else? I don't think so. This seems to be an error in the book as far as I can tell. The book's description may be based on the original delegating constructors proposal. The behaviour was changed in following revisions of the proposal.
71,323,065
71,323,297
In C++, is there any way for variatic template to ignore non-arithmetic type or object and return the sum of remain parameters?
I want to realize a function as the question title described, for example: cout << SumValue("abc", string("abcd"), 1.3, 1, 10, 2, 100) << endl; I want that C++ snippet output 114.3, the sum of 1.3, 1, 10, 2 and 100, and ignore "abc" and string("abcd"). I have tried the variatic template function and used the <type_t...
You can overload SumValue with the help of SFINAE. template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, long double>::type SumValue(T first) { return first; } template <typename T> typename std::enable_if<!std::is_arithmetic<T>::value, long double>::type SumValue(T first) { return 0; } templ...
71,323,111
71,323,215
Using an int variable in system() function c++
I need using an int veriable in system() function for my c++ program. for example: int a = 0; system("echo "a" "); but i get an error and i need help about how i use this like that Error: C++ user-defined literal operator not found
That's never going to work. C++ doesn't plug integers into strings that way. Instead, you can do: int a = 42; std::string s = "echo " + std::to_string (a); system (s.c_str ()); Also, you might consult this page, in order to learn the language properly.
71,323,742
71,323,831
Is there a standard algorithm to check if container A is a superset of container B?
I was looking for a standard algorithm that, given two containers A and B, both with no duplicates, returns true if all the elements of A compares to true with an element of B. I used std::all_of with a predicate that checks membership in the other container, but I was wondering if there was a more elegant solution..
Is there a STL algorithm to check if two containers contain same elements? I suppose that you mean "elements that compare equal". One object can only be an element of one container (at least in case of all standard containers). i was looking for an std:: algorithm that given two containers A and B, returns true if a...
71,323,902
71,328,395
DLL interface parameter mangled for debug version but not for release version c++ visual studio
I have a library packaged as a DLL and I am strange behavior when I access a simple function from calling program (both in c++ and using visual studio 2019). DLL header and function: bool libvpop_EXPORT GetLibVersion(string& version); bool GetLibVersion(string& version) { version = VPOPLIB_VERSION; return true...
Thanks to the hint from Richard Critten, I now understand what was going on. My dll library was compiled as a release configuration. The release configuration of my calling program worked fine it appears because the std::string objects were compatible but the debug configuration of my calling program must have been u...
71,323,994
71,324,120
Best way to find the angle between two nodes in an lattice graph?
If I have a lattice graph which looks like this: 0:0 0:1 0:2 0:3 1:0 1:1 1:2 1:3 2:0 2:1 2:2 2:3 3:0 3:1 3:2 3:3 , what is the best way to find an angle between two nodes? Example: angle(0:0, 0:1) = 0; angle(0:0, 1:1) = 45; This will be used during rendering to visualize a path in this graph with lines, a line will b...
Assuming x:y format, and an angle measured clockwise from the horizontal: angle(x1:y1, x2:y2) = arctan((x2-x1)/(y2-y1))
71,324,023
71,329,311
Find the duplicate numbers in this array,what i'm i doing wrong here?
I want to find the duplicate numbers in this array, I'm using vectors and want to print the answer, what am I doing wrong here? #include <iostream> #include <vector> using namespace std; int findDuplicate(vector<int> &arr) { int ans = 0; // XOR all elements for (int i = 0; i < arr.size(); i++) { ...
There are a number of things that are wrong. Let's start with the two easy ones. You have a cout statement that prints (it turns out) 0. But you don't do an endl, so you don't get a newline. cout << ans << endl; That will actually print a newline, which makes it easier to read. Second, your method returns a value, whi...
71,324,678
71,324,757
How much memory is allocated to call stack?
Previously I had seen assembly of many functions in C++. In gcc, all of them start with these instructions: push rbp mov rbp, rsp sub rsp, <X> ; <X> is size of frame I know that these instructions store the frame pointer of previous function and then sets up a frame for current function. But here, assembly...
How does startup code can know the maximum depth of call stack? It doesn't. In most common implementation, the size of the stack is constant. If the program exceeds the constant sized stack, that is called a stack overflow. This is why you must avoid creating large objects (which are typically, but not necessarily, a...
71,325,045
71,325,280
How to send SIGTERM to a child process using boost::process
boost/process.hpp provides a nice mechanism to spawn and manage processes. It provides a child.terminate() method to send SIGKILL to a child. How would I alternatively send SIGINT or SIGTERM to a child process?
Looks like you can do: #include <boost/process/child.hpp> pid_t pid = my_child.id (); kill (pid, SIGINT); The documentation states that id is a private member function, but in practise it seems not to be. There's also: native_handle_t native_handle() const; But what that actually returns isn't documented. On Windows...
71,325,428
71,326,263
Is the C++ syntax: T foo<U>; valid?
The following code compiles and run with Clang (tested on 13, 14, and current git head), but not with GCC. struct foo { int field<0, 1, int, 3>; }; But I do not understand what it is declaring: what is this field ? int field<0, 1, int, 3>; I can put whatever I want in the field<> template (if it is even a template?...
Assuming field isn't a template that has been declared, the program is ill-formed. But I do not understand what it is declaring: what is this field ? Clang AST says: `-CXXRecordDecl 0xdb6f20 <test.cpp:1:1, line:3:1> line:1:8 struct foo definition `-FieldDecl 0xdb7168 <line:2:3> col:7 'int' Clang AST for a program ...
71,325,514
71,325,625
Why enable_if_t needs to have datatype identifier and a default value?
I am unable to understand how the 2 commented code lines in below snippet are different than the lines just ahead of them? Is there an easy way to understand the meaning of the commented lines vs the meaning of lines just ahead of them? I am unable to speak in my mind as how to read the commented line and the line next...
The following in itself is completely fine: template<class T, std::enable_if_t<std::is_integral_v<T>, bool>> void fun(T value) { std::cout << "\n In Integral version"; } template<class T, std::enable_if_t<std::is_floating_point_v<T>, bool>> void fun(T value) { std::cout << "\n In Floating point version"; } It...
71,325,601
71,328,141
C++ remove() and rename() gives "Permission error"
I can't figure out what is happening in my program, it's a simple function to clear all the Windows '\r' from a file, putting all the chars in another file and then rename it to substitute the old file. Every time I execute the function the rename() and remove() functions give me "Permission error" even if I had all th...
I found out that the old file and the new file must not be in the same folder for some reason
71,325,698
71,325,774
I can't access a global array in c++
Hello first thing first forgives me if I have mistakes in my English, I am beginner in c++ and I need help with this problem please //global variables int RangeOfArray; int arr[RangeOfArray-1]; // error: array bound is not an integer constant before ']' token void functionOne(){} // I need to access the array here....
In these declarations //global variables int RangeOfArray; int arr[RangeOfArray-1]; // error: array bound is not an integer constant before ']' token there is declared the global variable RangeOfArray that is implicitly initialized by zero and then there is declared the variable length array arr with the size -1 that...
71,325,940
71,326,200
How to translate scanf exact matching into modern c++ stringstream reading
I am currenlty working on a project and I'd like to use modern cpp instead of relying on old c for reading files. For context I'm trying to read wavefront obj files. I have this old code snippet : const char *line; float x, y, z; if(sscanf(line, "vn %f %f %f", &x, &y, &z) != 3) break; // quitting loop because could...
I've run into this requirement as well, and wrote a little extractor for streams that lets you match literals. The code looks like this: #include <iostream> #include <cctype> std::istream& operator>>(std::istream& is, char const* s) { if (s == nullptr) return; if (is.flags() & std::io...
71,326,603
71,327,151
Invalid array values ​in compute shader?
I use a buffer to which I pass my C++ structures struct Node { Node(int size, glm::ivec3 position); bool isEmpty(); int getSubIndex(const glm::ivec3& vec); void divide(std::vector<Node> &nodes); void setColor(glm::vec4 color); int getSubNodeIndex(const glm::ivec3& vec); int getSubNodeIndex(...
The std430 required alignment for your Node structure is 16-bytes. This is because it contains a 16-byte-aligned type (vec4 and ivec4). Therefore, every array element in the Node array will have to start at a 16-byte boundary. So the array stride for nodes will have to be 48. The C++ alignment of your Node structure is...
71,327,008
71,327,112
Using type traits in C++ template functions, is it possible to convert a value to a T of the same type?
I'm trying to write a template function like this template<typename T> T doSomething() { //Code if (std::is_same<T, int>::value) { return getInt(); // A library function returning an int } else if (std::is_same<T, bool>::value) { return getBool(); // A library function returning a bool...
So, is there a way to return different types from a template function depending on the template parameter in C++? Yes, you can use C++17 constexpr if template<typename T> T doSomething() { //Code if constexpr (std::is_same<T, int>::value) { return getInt(); // A library function returning an int ...
71,327,144
71,327,362
Is it safe to reinterpret_cast LPNCCALCSIZE_PARAMS to LPRECT when intercepting WM_NCCALCSIZE?
Though it worked for me without problems, but I am afraid that it will explode in my face some day in the future, LPRECT pRect = reinterpret_cast<LPRECT>(lParam); I need to know if it is safe to reinterpret_cast LPNCCALCSIZE_PARAMS to LPRECT when intercepting WM_NCCALCSIZE, if I need to deal with only (LPNCCALCSIZE_PA...
The memory address of an object is the same as the memory address of its 1st data member. And the memory address of an array is the same as the memory address of its 1st element. Per the WM_NCCALCSIZE documentation: lParam If wParam is TRUE, lParam points to an NCCALCSIZE_PARAMS structure that contains information an ...
71,327,479
71,327,843
is a ++ before a container the same as moving the index by one?
I am unfamiliar with this syntax: ++fCount[index]. Where list is another vector. I was thinking it was the same as below, but its not: int i = 0; vector<int> fCount(1001,0); for(auto index : list) { fCount[i] = index; i++; } piece of code: vector<int> fCount(1001,0); for(auto index : list) { ++fCount[inde...
vector::operator[] returns a reference to an element at a given index. The ++ increment operator increments the value of a variable. The two codes examples you have shown are NOT equivalent. The first code is looping through list, assigning each of its elements as-is to sequential elements of fCount. A range-for loop ...
71,328,738
71,328,806
C++boost syntax - meaning of <>
I was generating a random number with the boost library, namely: boost::random::random_device rng; boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1); Now I understand that uniform_int_distribution is class, but what's the meaning of the empty <>? Is it a template?
It is indeed a template. With no given datatype it will fall back to a default datatype to work with. You can see that the default in this case is a regular int. https://www.boost.org/doc/libs/1_51_0/doc/html/boost/random/uniform_int_distribution.html
71,328,940
71,329,010
Function to delete dynamically allocated 2D array
Quick question here. Using this func to allocate memory for an arr: int **createDynamicNumArray() { int size; cout << "Enter size: " << endl; cin >> size; int **numArr = new int *[size]; for (int i = 0; i < size; ++i) { numArr[i] = new int[size]; } return numArr; } Is this the correct way for a function to clear s...
Is this the correct way for a function to clear said memory?: Yes. Key note: Do I pass just a double pointer or a double pointer reference to the function for deleting? Both work. I recommend not using a reference since that will be less confusing to the reader. However, I recommend avoiding owning bare pointers i...
71,329,019
71,329,168
What is the efficient way to add a std::string to a STL container with a value of a c-str buffer in memory?
Let's say I have a buffer of chars in memory that holds a c_string, and I want to add an object of std::string with the content of that c_string to a standard container, such as std::list<std::string>, in an efficient way. Example: #include <list> #include <string> int main() { std::list<std::string> list; ch...
// 3 is fully equivalent to // 1. std::move does absolutely nothing here since std::string(c_string_buffer) is already a rvalue. The problem with push_back is not related to move vs copy. push_back is always a bad choice if you don't yet have an object of the element type because it always creates the new container ele...
71,329,047
71,329,145
"Access violation reading location 0x0000000000000000", OpenCV with C++ trying to opening an image
#include <iostream> #include <opencv2/highgui.hpp> using namespace cv; using namespace std; // Driver code int main(int argc, char** argv) { //----- COMMAND LINE ----- const String& filename = argv[1]; Mat image = imread(argv[1]); //----- EXPLICIT WAY ----- //const String& filename = "C:/Users/let...
You have set - according to the image attached - additional command line arguments to the compiler and not to the app you run. To add command lines to the app, right click on the project (OpenImg) and choose Debugging -> Command Arguments. (And, as mentioned by @user4581301, verifying that the argument exists by checki...
71,329,526
71,329,730
Do "else if" exist in c++ or it just only "if" and "else"?
This might not be a problem but just for peace of mind and I think it good to know how c++ mechanic deal with this keyword. Consider this, if (condition1)statement1; else if (condition2)statement2; we can interprete as, if (condition1)statement1; else statement3; where "statement3" is "if (condition2)statement2;" Whi...
To answer your question as asked Do "else if" exist in c++ or it just only "if" and "else"? No, else if is not a c++ keyword. See https://en.cppreference.com/w/cpp/language/if Note the else statement-false part. Then your following if just becomes that statement-false
71,329,627
71,329,714
Preventing descendants from overriding method
In C++ (11/14/17, I don't care), I have a base class B which exposes method x as protected. In class D1, which derives from B, I want to prevent further descendants (of D1) from calling x(). Now, if I were overriding x in D1, I would simply mark it as final. But, what if D1 does not override x(), yet D1 still wants to...
How can I do that? By changing the program and overriding x in D1. You can just delegate to the base class version by calling it.
71,329,662
71,329,725
C++ Error : multiple definition of class_name::class_name()
I am trying to understand how to work with header file in C++. Faced an error and I need know why and how to solve this. I have 4 files. main.cpp B.h A.h A.cpp Among them in some file. for ex. main.cpp or B.h if the line #include "B.h" exists, it gives me error. Image: main.cpp: #include <iostream> #include "A.h...
This code: B::B(){//some code}; B::~B(){//some code}; Will be pasted by the pre-processor into multiple translation units (A.cpp and main.cpp). It will be compiled 2 times and therefore violates the ODR (One definition rule). If you implemented it in the class: class B { B() { ... } Then it would be automaticall...
71,329,810
71,329,965
What's the correct use of variadic function template here?
I happen to compute the elapsed running time of various functions and algorithms in my research project, so, I decided to define an elapsed_time function which might take various type of functions with various number of arguments(if any) and also various return types or none (void). I want to pass a function to this el...
I recommend the following approach template<typename Func, typename... Args> void elapsed_time(Func f, Args&&... args) { std::chrono::time_point<std::chrono::high_resolution_clock> start_; std::chrono::time_point<std::chrono::high_resolution_clock> end_; start_ = std::chrono::high_resolution_clock::now(); ...
71,330,683
71,330,751
How to implement an iterator for a custom class?
For an assignment, we had to create custom list class. One of the functions is to insert an element into the middle of the list. So far I have, template<class T> class MyList : public list<T> { public: void addInMiddle(const T&); void insertInSortedOrder(const T&); void printList(); }; template<class T> ...
Your code works fine for me once I add typename in front of list<T>::iterator, since the type of the iterator is dependent on the type of the T template parameter, eg: typename list<T>::iterator it = this->begin(); Online Demo See Where and why do I have to put the "template" and "typename" keywords? Alternatively, yo...
71,330,690
71,352,193
String vector binary search
I am trying to find a user input word inside a string vector using binary search. But it always returns a positive integer. The vector is sorted and read from a txt file. The file looks like. aah aal aas and so on. int binarySearchString(vector<string> arr, string x, int n) { int lower = 0; int upper = n -...
As it is, unless x == (arr[mid]) is true, this code should throw a runtime exception because res will be used in the next if statement before it's been initialized. When I initialize res to some negative value, the function seems to work. int binarySearchString(vector<string> arr, string x, int n) { int lower = 0; ...
71,330,694
71,330,749
is if(s.length()) saying that if it returns a value, proceed?
Typically, I see code with say if(s.length() > 1) ..., but here it only has if(s.length()). The length function is implemented as mentioned below. When used in the test3 function call within the file containing int main(), is if(s.length) saying that if it returns a count that is greater than zero then it will execute ...
In c++ an int can be implicitly converted to a bool. The rule is: int (0) -> false int (anything else) -> true In your case, the length will return some positive number if it exists, and 0 if it doesn't so this logic: if (s.length()) Is equivalent to if (s.length() >= 1) ^ // Very important, you probab...
71,330,860
71,330,922
Function Pointer inside Class (expression preceding parentheses of apparent call must have (pointer-to-) function type)
I want to use different functions depending on the input to calculate the output. but it says: (expression preceding parentheses of apparent call must have (pointer-to-) function type) int (TestClass::* Gate_Func)(vector); <<== this is the function I initiated. and then here: Gate_Func = &TestClass::AND; I can referenc...
The functions AND, OR, and NOT are non-static member functions. They can only be called when an instance of their class is supplied. Gate_Func is a pointer to non-static member function. It can point to a non-static member function such as AND, OR, or NOT. In order to invoke it, you must supply an instance of the class...
71,331,410
71,331,565
std::set custom string comparison using boost::iequals
Following code works well without issues but wondering, if it is possible to rewrite custom comparison operator using boost::iequals , which compares without converting to upper. std::string copyToUpper(std::string s) { std::transform(s.begin(),s.end(),s.begin(),::toupper); return s; } struct caseInsensitiv...
Almost all STL containers rely on strict weak ordering. So the comparison function needs to return, not whether the strings are equal to each other, but that one is "less" than the other. But boost::iequals checks for equality and not if one string is "less" than the other, so you can't use it for the comparator of a...
71,332,034
71,332,909
Visual Studio 2022 "A task was cancelled" after build
I'm using Visual Studio Community 2022. Now I have a similar problem with Visual studio 2013 "A task was cancelled". A few moments ago, everything went alright. However I suddenly found that when I try to build my cpp project, VS only output 1>----— Build started: Project: MyConsoleApp, Configuration: Release x64 —----...
I have the same problem as you, since February 28th, VS2022 could not build any project, until today, I uninstalled the anti-virus software (360 Security Guard) installed on my computer, it returned to normal work, I think this is due to the anti-virus software update caused by the incompatible VS2022, You can try un...
71,332,190
71,332,284
Is there a way in C++ to check if a line of an opened fstream file contains multiple integers?
I have myfile.in opened with the following text: 1 4 5 3 Going for every number while (myfile >> var) cout << var << endl; will output each integer one by one: 1 4 5 3 Is there any way I can check all the lines of myfile.in and output the lines with more than 1 integer? For the example above: 4 5 or 4 5
You can use a combination of std::getline and std::istringstream as shown below. The explanation is given in the comments. #include <iostream> #include<fstream> #include<string> #include <sstream> int main() { std::ifstream inputFile("input.txt"); std::string line; int num = 0; //for storing the current n...
71,332,613
71,333,389
Initializing a vector with istream_iterator before while loop, does this operation affect following loop?
When adding vector<string> vec(file_iter, eof); before the while loop, that loop will run only once. Why? istream_iterator<string> file_iter(in), eof; map<string, size_t> word_cout; vector<string> vec(file_iter, eof); while (file_iter != eof) { auto ret = word_cout.insert(make_pair(*file_iter, 1)); if (ret.second == ...
The construction here: vector<string> vec(file_iter, eof); passes a copy of the file_iter and eof iterators to the vector constructor, where it then abuses the former to load the vector with content. Whilst doing so the underlying stream in is continually read from until such time as a stream error or EOF is encounter...
71,332,646
71,335,588
Pattern for inheriting and using a member variable in derived classes without casting each time
I have a base class: class Base{ protected: Storage* _storage; virtual void createStorage(){ delete storage; _storage = new Storage(); } void exampleUseOfBaseStorage(){ _storage->baseData++; //some complex calculation } } struct Storage{ int baseData; } Each derived c...
I think the question should be "do you really need storage to be derived?". Most of time composition/aggregation should be enough. Even you need to calculate the data from both derived storage and base storage, you may still access both of them in derived class Example for composition Live Demo #include<string> #includ...
71,332,768
71,332,793
Is it possible to call a function outside of main()?
I guess my question is stupid, but nevertheless: In my C++ code I use some legacy C library(XLib). In order to use this library a connection to X server has to be opened first: ::Display* const display = ::XOpenDisplay(nullptr); This display structure is widely used across the vast majority of the XLib functions, incl...
It's possible, but unnecessary. Instead, wrap it in a class that closes it in the destructor, like you did with the other objects. Destructors are called in the reverse order, which means that if you create the display first, it'll die last. The way you would've called it after main is, similarily, from a destructor o...
71,333,190
71,333,287
Is it valid to cast and access to implicit-lifetime types without explicit object creation?
char* t = (char*)malloc(sizeof(float) * 2); *(float*)t = 1.0f; // or *reinterpret_cast<float*>(t) = 1.0f; *((float*)t + 1) = 2.0f; // #1 In some SO questions, there are answers saying that above code is undefined behaviour because of strict-aliasing violation. But, I read the paper P0593 recently. I think the paper is...
Yes, the code is legal, and the objects are created implicitly. (since C++20) I had doubts whether you need std::launder or not. Seems not, malloc does it implicitly (note "return a pointer to a suitable created object").
71,333,578
71,379,785
an array of non-coherent types, that have something in common (array of concepts)
I think the use case is frequent, when you have multiple templated classes that have an element (variable or fcn) in common, and you want to call the fcn for all of them in a loop-like way. Clearly, we can define a base class and make a list of base-class pointers, and use them to loop, but I am trying to avoid pointer...
I kind of found a solution by implementing my own tuple (without allocation) template <typename T1, typename... Tn> struct tuple { tuple(T1&& first, Tn&&... rest): m_first(first), m_rest(std::forward<Tn>(rest)...){}; T1 m_first; tuple<Tn...> m_rest; }; template <typename T> struct tuple<T> /*specialization*/ ...
71,333,649
71,334,103
GetMethodID of constructor of Java object
I have a short question related to the GetMethodID() function of C++. I have been searching for the answer here on StackOverflow, but could not find it. My main code is in Java, but for some parts I would need C++. The code below is a simplification of what I intend to implement, to test out how to retrieve and pass ob...
thisObject is a ExampleJNI not a Order so GetObjectClass will return ExampleJNI which doesn't have the constructor you are looking for. Change GetObjectClass to env->FindClass("Order").
71,334,240
71,334,473
rvalue reference forwarding
I am writing a wrapper around std::jthread and some surrounding infrastructure. I cannot wrap my head around why the following won't compile: #include <iostream> #include <map> #include <functional> #include <thread> // two random functions void foo(int i) { std::cout << "foo " << i << std::endl; } void bar(int i) { ...
In any case, the arguments work for std::jthread, which also just takes rvalues... So what am I missing? jthread is not a template, its constructor is a template. Which makes the rvalue references to template parameters into forwarding references, not plain rvalue references. However, since MyThread is itself a templ...
71,334,463
71,334,608
Is std::vector.data() null-terminated on a vector of pointers?
I am using a C library in my C++ application. One of the functions needs a null-terminated array of pointers. Since I am using C++, I am storing the elements of the array in a std::vector. I would like to know if it's safe to simply call data() on my vector and pass the result to the library function. Exemple : std::ve...
A vector of pointers is null terminated if the last element of the vector is null. There is no extra null element after the last element (like there would be a null terminator character after the last element of a std::string). The last element of a vector isn't null automatically. If you need the last element to be nu...
71,334,471
71,339,250
Time complexity of Search in 2D array
In my opinion, the best case time complexity of the following code is O(1), i.e. number to be searched is found as the first element but the worst-case time complexity is O(n**2) because there can be n number of elements in each array and there can be n arrays in 2d array (nested loop to search) Please let me know if y...
If your function could search an arbitrarily-sized (instead of fixed-size) NxN matrix M, then what you're doing is a sequential search. For example: int M[3][3] = { { 1,2,3 },{ 4,5,6 },{ 7,8,9 } }; bool searchM(int n, int x) { for (int i = 0; i<n; i++) { for (int j = 0; j<n; j++) { ...
71,335,628
71,335,744
Is it valid to omit the return statement of a non-void function template that throw
I am learning C++ using the resources listed here. In particular, i read about exceptions and want to know if is it valid to omit the return statement of a non-void function/function template that throw as shown below: Example 1 #include <iostream> //this function template does not have a return statement template<type...
are example 1 and example 2 valid? Yes. Or we have UB/ill-formed. No. Is it valid to omit the return statement of a non-void function/function template that throw Yes. A non-void returning function must either throw or return avalue. It cannot do both at the same time. So is int func(){ int x = 4; throw; return ...
71,335,788
71,335,853
C++ Dangling pointer issue
I am using the Raylib GUI framework for a project that displays all the nodes within an iteration of the Collatz Conjecture. In my program, I have a class for a Node object that acts simply as a circle with a labelled number. The variable text in my draw method, however, has an issue; C26815: The pointer is dangling be...
In this line const char* text = std::to_string(value).c_str(); You are calling c_str() which returns a pointer to the buffer of the temporary returned by std::to_string(value). This temporaries lifetime ends at the end of this line. The pointer returned from c_str is only valid as long as the string is still alive. If...
71,336,003
71,341,005
C++ imap-utf7 implementation in gmail
I am trying to decode what texts GMails sends, which should be utf7-imap (actually, if I am not mistaking, utf8 encoded inside utf7?) I have read: https://en.wikipedia.org/wiki/UTF-7 I am using: https://github.com/skeeto/utf-7 to parse the (for example) the text - and mimetic (https://github.com/tat/mimetic) to parse t...
UTF-7 is used to encode non-ASCII mailbox names in IMAP protocol. This is not related to your example, which shows the RFC 2822 Subject filed with MIME-encoded value according to RFC 2047. In your example (with the "=?UTF-8?B?" prefix) decoding is simple: the string that follows (up to "?=") is a base64 presentation of...
71,336,125
71,336,499
Best practice when dealing with C++ iostreams
I'm writing a command-line utility for some text processing. I need a helper function (or two) that does the following: If the filename is -, return standard input/output; Otherwise, create and open a file, check for error, and return it. And here comes my question: what is the best practice to design/implement such ...
I would probably make it into std::istream& open_for_read(std::ifstream& ifs, const std::string& filename) { return filename == "-" ? std::cin : (ifs.open(filename), ifs); } and then supply an ifstream to the function. std::ifstream ifs; auto& is = open_for_read(ifs, the_filename); // now use `is` everywhere: if(...
71,336,291
71,338,608
Fastest way to get square root in float value
I am trying to find a fastest way to make square root of any float number in C++. I am using this type of function in a huge particles movement calculation like calculation distance between two particle, we need a square root etc. So If any suggestion it will be very helpful. I have tried and below is my code #include ...
In short, I do not think it is possible to implement something generally faster than the standard library version of sqrt. Performance is a very important parameter when implementing standard library functions and it is fair to assume that such a commonly used function as sqrt is optimized as much as possible. Beating ...
71,336,311
71,336,485
Remove all occurrences of character x from a given string recursively
I have written two solutions to this problem one with the head recursion and the other with the tail recursion. One with the head recursion passes all the test cases but the solution with tail recursion is missing one case. I am not able to figure out which case I am missing. Can someone please help me here? One with h...
Both functions have undefined behavior because the arrays passed to strcpy should not overlap: change strcpy(input, input+1); to memmove(input, input + 1, strlen(input + 1) + 1); Furthermore, both functions have the same code, which is not tail recursion. They recurse twice on each occurrence of x, which is either red...
71,336,421
71,347,383
How to stop cmake from trying to link against non-existing library?
I am sorry if this is a naive question, as I'm quite unfamiliar with CMake in general. I am trying to compile a very large open-source software project (OpenCV). I seem to have get most libraries that is needed into the path using the following command line arguments. -DCUDNN_INCLUDE_DIR='${CONDA_PREFIX}/include' \ -DC...
The problem is caused by the following CMake option. -DCUDNN_LIBRARY='/${CONDA_PREFIX}/lib' Removing this option solved the problem. It seems that this path should be to a file, not a directory. I'm not sure which file it should point to for CUDA 11.6 and CuDNN 8.3.2, but simply removing this line is sufficient.
71,336,552
71,336,846
shared_ptr doesn't increase reference count, but point at the same address
here is my code snippet: #include <iostream> #include <list> #include <memory> class A { public: int a = 100; A() { std::cout << "Create A" << std::endl; } ~A() { std::cout << "Release A" << std::endl; } virtual void printer() = 0; }; std::list<std::shared_ptr<A>> arr; class B : public...
My expectation is: A's reference count should be three, but only got 2. Your expectation is wrong. You only made one copy of the shared pointer, so the use count is 2. std::shared_ptr<A> tmp(this); On this line you transfer the ownership of a bare pointer that you don't own into a new shared pointer. Since this wa...
71,338,581
71,338,647
C++ - dealing with infinitesimal numbers
I need to find some way to deal with infinitesimial double values. For example: exp(-0.00000000000000000000000000000100000000000000000003)= 0.99999999999999999999999999999899999999999999999997 But exp function produce result = 1.000000000000000000000000000000 So my first thought was to make my own exp function. Unfortu...
Try using std::expm1 Computes the e (Euler's number, 2.7182818) raised to the given power arg, minus 1.0. This function is more accurate than the expression std::exp(arg)-1.0 if arg is close to zero. #include <iostream> #include <cmath> int main() { std::cout << "expm1(-0.0000000000000000000000000000010000000000...
71,338,714
71,339,517
Is there a way to print the final value of an increment, before incrementing it, in C++?
EDIT TITLE (I changed the title because it was wrongly referring to macros and compilation time, leading to confusion about my question) In order to help with the output of my tests in c++ programs, I print the test number before each test. Something like this output : [1/2] test : // some test [2/2] test : // some te...
It is not clear why you are asking for a macro. If possible better avoid macros. As suggested in a comment, you can register tests in a container and once you know how many tests there are in total, you can print the total together with the running test number: #include <vector> #include <functional> #include <iostream...
71,338,950
71,339,041
Are CMake macros/definitions accessible from source files?
Are the default CMake macros/definitions exposed to the source files being build? For instance, can I access CMAKE_PROJECT_VERSION from a main.cpp? I understand I can just force them into the source files by creating a new macro with set() and add_compile_definitions(), but was looking for a cleaner / less redundant wa...
No. CMake variables such as CMAKE_PROJECT_VERSION are not accessible to the source files.
71,338,990
71,339,445
Bypass `find_package` in CMake for specific targets?
Is there a way to have a specific target that is still able to build even if find_package fails? For instance, I have a target that just compiles the code documentation and naturally has no hard requirements/dependencies, but cmake won't even finish configuration in case there is a missing dependency.
Did you read this part of documentation: find_package — CMake 3.23.0-rc2 Documentation Regardless of the mode used, a <PackageName>_FOUND variable will be set to indicate whether the package was found. When the package is found, package-specific information may be provided through other variables and Imported Targets ...
71,339,111
71,339,213
Is char* created with "..." and new are on stack and heap respectively? Just want a brief answer if my understanding is right or wrong?
const char* s1 = "John"; const char* s2 = new char[] {"Cena"}; // is s1 on stack? // is s2 on heap? ... // use s1 and s2 ... delete s1; // do I need to delete s1? delete[] s2? // s2 definitely must be deleted right? I have added my questions in the comments above. Thanks in advance.
You may delete what was created using the operator new. String literals have static storage duration. They are alive until the program ends. In this code snippet const char* s1 = "John"; const char* s2 = new char[] {"Cena"}; there is allocated dynamically only the array initialized by the string literal "Cena". So to ...
71,339,239
71,557,582
OpenCV C++ Sorting a vector of contour point in decending order
I'm trying to sort vector of contours point in decending order but whenever I used: sort(contours.begin(), contours.end() , greater<>()), It is poping out an error. How to sort vector that contains contour points in decending order? Mat img; im.copyTo(img); vector<vector<Point>>contours; vector<Vec4i...
contours is not a vector of Points. It is a vector of vectors of Points. I.e. each element is in itself a vector of Points. If you want to sort such a vector of vectors, you should supply some kind of a "greater" function. One of the convenient ways would be using a lamba function: std::sort(contours.begin(), ...
71,339,280
71,341,315
ANTLR4 parse tree doesn't contain rule names
ANTLR4 doesn't show rule names in parse tree. For example, 1 + 2 is printed as: Code in main: std::string test = "1 + 2"; ANTLRInputStream input(test); GrammarLexer lexer(&input); CommonTokenStream tokens(&lexer); GrammarParser parser(&tokens); auto *tree = parser.expression(); std::cout ...
I dived into ANTLR's C++ runtime source code and found these 2 functions: /// Print out a whole tree, not just a node, in LISP format /// {@code (root child1 .. childN)}. Print just a node if this is a leaf. virtual std::string toStringTree(bool pretty = false) = 0; /// Specialize toStringTree so that it can print out...
71,339,707
71,340,596
Create a Q_PROPERTY to a QObject which has it's own Q_PROPERTY's
I have an QInnerItem with two Q_PROPERTIES class QInnerItem : public QObject { Q_OBJECT Q_PROPERTY(int bar1 READ bar1 WRITE setBar1 NOTIFY bar1Changed) Q_PROPERTY(int bar2 READ bar2 WRITE setBar2 NOTIFY bar2Changed) public: QInnerItem(QObject* owner) : QObject(owner) {} void setBar1(const int& ba...
You were misunderstanding what you quoted: "you should use pointers to QObject". It doesn't matter if the actual member variable is a pointer or not. What matters is how the Q_PROPERTY is accessed. So you can do something like this: class QOuterItem : public QObject { Q_OBJECT Q_PROPERTY(QInnerItem *bar READ ba...
71,339,808
71,341,527
Why do A[i][j] and *((int*)A + i * n + j) give me different output?
I am learning C++ pointers. My instructor mentioned that *((int*)A + i * n + j) is another way to linearize A[i][j] notation. I tried testing out it with a 2x4 2D array in this main function. int main() { int** A = new int* [100]; for (int i = 0; i < 2; ++i) { A[i] = new int[100]; } //assig...
You drastically misunderstood what the instructor was trying to tell you. The keyword in their description is "notation", but they left out something important (which I'll get to in a minute) First off, if you're instructor is telling you to do this: *((int*)A + i * n + j) take everything they say into question. That ...
71,340,262
71,340,629
Can C++11 and C++17 Range-Based For Loop iterate to a specific position instead of full range of the map?
Are there versions of C++11 and C++17 Range-Based For Loop iterators that can iterate to a certain position in map? For example, if a map has 10 key-value elements, then how can I iterate through only the first three key-value elements? The following codes only iterate through the full range of the map. //C++11 for...
You either need an external counter to make early exit, eg: int n = 0; for(auto&& [k, v] : map) { if(++n > 10) break; std::cout << k << ": " << v << std::endl; } Or, if you are not afraid of copying the map, you can do: auto copy = std::map<...>{map.begin(), std::next(map.begin(), 10)}; for(auto&& [k, v] : co...
71,340,297
71,343,056
Drawing with cv::circle's over a line Iterator in c++ with openCV
I'm creating an iterator line, which I pass through a for() and draw with cv::circle points. So far so good, form a line drawing, by the iterator's line points. But there is a small drawing in the upper left corner that is not my intention, does anyone know where I could be going wrong? std::vector<cv::Point> createLi...
I got it by returning both cv::Point from the function std::pair<std::pair<cv::Point, cv::Point>, std::vector<cv::Point>> createLineIterator(cv::Mat &frame){...} and I called in main cv::line(image, points.first.first, points.first.second, cv::Scalar(255, 0, 0)); I don't know the reason for the error before when dra...
71,340,563
71,341,024
Dealing with inconsistent typedefs in generic code
I routinely come across code in large codebases that do not follow the standard convention for typedefs e.g. ThisType instead of this_type. Writing generic code where I can no longer rely on this_type means I have to provide some scaffolding code for each type that does not have this_type. I suppose both this_type and ...
Maybe can be done in a simpler way... anyway, I propose a tag dispatching / SFINAE solution. First of all, a simple recursive tag struct template <std::size_t N> struct tag : public tag<N-1u> { }; template <> struct tag<0u> { }; to avoid ambiguities in cases more that one of the possible type names are defined. Then ...
71,340,614
71,688,030
Is relying on integer promotion a bad programming practice?
I'm currently writing some code for embedded systems (both in c and c++) and in trying to minimize memory use I've noticed that I used a lot of code that relies on integer promotions. For example (to my knowledge this code is identical in c and c++): uint8_t brightness = 40; uint8_t maxval = 255; uint8_t localoutput = ...
Your question raises an important issue in C programming and in programming in general: does the program behave as expected in all cases? The expression (brightness * maxval) / 100 computes an intermediary value brightness * maxval that may exceed the range of the type used to compute it. In Python and some other langu...
71,340,776
71,340,875
Chain member initializers
Is it possible to refer to class members inside "in class initializers"? Example: struct Example { std::string a = "Hello"; std::string b = a + "World"; }; It seems to work (compiles and runs) but is it ok to do?
This is allowed in default initializers since C++11. Scroll down to the "Usage" section and look at the first example. I copied the explanation and example here for easier reference: The name of a non-static data member or a non-static member function can only appear in the following three situations: As a part of cl...
71,340,798
71,393,043
Problem of sorting OpenMP threads into NUMA nodes by experiment
I'm attempting to create a std::vector<std::set<int>> with one set for each NUMA-node, containing the thread-ids obtained using omp_get_thread_num(). Topo: Idea: Create data which is larger than L3 cache, set first touch using thread 0, perform multiple experiments to determine the minimum access time of each thread,...
After more investigation, I note the following: work-load managers on clusters can and will disregard/reset OMP_PLACES/OMP_PROC_BIND, memory page migration is a thing on modern NUMA systems. Following this, I started using the work-load manager's own thread binding/pinning system, and adapted my benchmark to lock the...
71,341,242
71,345,322
C++ - Pass Pointer of a Template Class to A Function
I am trying to pass a pointer to a templated object to another class. template <int size> class A { public: int a[size] = {0}; int getA(int n) { return a[n]; } }; class B { public: A<>* b; void setB(A<>* n) { b = n; } }; int main() { const int size1 = 10; A<size1> d...
You have gotten yourself into a bit of a catch-22 situation. You can't hold a templated A inside of B without making B templated as well, eg: template <int size> class A { public: int a[size]; int getA(int n) { return a[n]; } }; template <int size> class B { public: A<size>* b; int getA(in...