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 properly implement this? Thanks in advance! EDIT: Here is the non-working code I found somewhere #include "windows.h" #include <iostream> using namespace std; HHOOK hookHandle; LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam); int main(int argc, char *argv[]) { hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, keyHandler, NULL, 0); if (hookHandle == NULL) { cout << "ERROR CREATING HOOK: "; cout << GetLastError() << endl; getchar(); return 0; } MSG message; while (GetMessage(&message, NULL, 0, 0) != 0) { TranslateMessage(&message); DispatchMessage(&message); } cout << "Press any key to quit..."; getchar(); UnhookWindowsHookEx(hookHandle); return 0; } LRESULT CALLBACK keyHandler(int nCode, WPARAM wParam, LPARAM lParam) { cout << "Hello!" << endl; // Checks whether params contain action about keystroke if (nCode == HC_ACTION) { cout << ((KBDLLHOOKSTRUCT *)lParam)->vkCode << endl; } return CallNextHookEx(hookHandle, nCode, wParam, lParam); } I am compiling it with Mingw-W64 on Linux, but error reproduces on MSVC and Mingw-W64 on Windows.
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 exactly what you are doing. So, if your goal is to hook every running process globally (ie, dwThreadId=0), you need to pass a non-NULL HMODULE to the hMod parameter. Low-level hooks are not required to be implemented as DLLs, so you should be able to use the GetModuleHandle() function (for instance, with either lpModuleName=NULL or lpModuleName="kernel32.dll" should suffice). [I] don't know how to cancel the keypresses Per the LowLevelKeyboardProc documentation: Return value ... If nCode is greater than or equal to zero, and the hook procedure did not process the message, it is highly recommended that you call CallNextHookEx and return the value it returns; otherwise, other applications that have installed WH_KEYBOARD_LL hooks will not receive hook notifications and may behave incorrectly as a result. If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure.
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){ delete next; // é tipo uma chamada recursiva, vai deletando tudo. } } friend class List; }; class List{ Node * head; Node * tail; public: Node * begin(){ return head; } List():head(NULL),tail(NULL){} void push_front(char data){ if(head == NULL){ Node * n = new Node(data); head = tail = n; } else{ Node * n = new Node(data); n->next = head; head = n; } } void push_back(char data){ if(head==NULL){ Node * n = new Node(data); head = tail = n; }else{ Node * n = new Node(data); tail->next = n; tail = n; } } void insert(char data, int pos){ if(pos==0){ push_front(data); return; } Node* temp = head; for(int jump = 1; jump <=pos-1;jump++){ temp = temp->next; } Node *n = new Node(data); n->next = temp->next; temp->next = n; } ~List(){ if(head!=NULL){ delete head; head = NULL; } } }; int main() { List l; int i=0; char temp; char str[10000]; int posx=0; while(scanf("%s", str) != '\0'){ while(str[i] != '\0'){ temp = str[i]; if(str[i] == '['){ while(str[i+1] != ']' && str[i+1] != '[' && str[i+1] != '\0'){ i++; temp = str[i]; l.insert(str[i], posx); posx++; } }else if(str[i] == ']'){ while(str[i+1] != ']' && str[i+1] != '[' && str[i+1] != '\0'){ i++; l.push_back(str[i]); } }else{ l.push_back(str[i]); } i++; posx=0; Node *head = l.begin(); while(head!=NULL){ cout << head -> getData(); head = head->next; } printf("\n"); } i=0; l.~List(); } return 0; } Being straight: The program gets a string, if the user types '[' the new characters (letters and underscores) will be added to the front, if the user inputs ']' then the cursor will move to the back. The problem is: if I input [_text_[rinti]has[_the_]], before reaching has I have rinti_text_, and it's fine, but when it gets to has, the function push_back is called and it simply overwrites the word text, and after that I'll have rinti_has, instead of rinti_text_has. I do not know whats happening, but the problem seem to be with the function push_back. I would appreacite any hints or answers
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(pos==0){ push_front(data); return; } Node* temp = head; for(int jump = 1; jump <=pos-1;jump++){ temp = temp->next; } if(temp == tail) { push_back(data); } else { Node *n = new Node(data); n->next = temp->next; temp->next = n; } }
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 pointers to other maps that are identical in structure/definition to the map in which the vector is contained. I know there are workarounds using classes and structs, the question is whether it is possible using only templates. I was hoping I could somehow define the whole outer map as some kind of "template-variable" or other place-holder such as "T", then write the following: map<some_type,vector<T*>> elements; where I would separately define T as referring to the whole map. But due to recursion, such a variable T would be defined in terms of itself, ie sub-components that are themselves T. Later I would then at runtime as necessary allocate more maps on the heap and insert pointers to them in the vector, such that I can then recursively (indefinately often), traverse into the map within the vector, just so that I can then instantiate more maps on the heap, again holding pointers to them within the vector. Is there an (elegant) way to do this (if at all)?
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 that Fix<F> == F<Fix<F>>. Abstractly, in a lazy functional language, Fix<F> = F<Fix<F>> could serve as a definition of Fix<F>. This coincidentally tells us exactly what breaks down in C++. In C++ notation this hypothetical definition would look like: template <template<typename> typename F> using Fix = F<Fix<F>>; // does not compile This depends fundamentally on laziness, but templates are lazy by nature so that isn't a problem. The real problem is name lookup. We cannot refer to Fix on the right-hand side in C++. That's a somewhat artificial restriction, but that's the language we have. I cannot see a way around that, so I cannot avoid introducing one generic helper struct: template <template<typename> typename F> struct Fix : F<Fix<F>> { }; Although aliases cannot reference their own name in the definition, classes and structs can. With all of that out of the way, we have our solution: // Our type using Type = Fix<F>; // It instantiates auto map = Type{}; // The inner type is the same as the outer type using inner_type = std::decay_t<decltype(*std::declval<Type::mapped_type::value_type>())>; static_assert(std::is_same_v<Type, inner_type>); // We can push_back the address of ourself map[0].push_back(&map); See this on godbolt.
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'; std::cout << s[-1] << s[0] << s[1]; } Output: MI² My problem is that, whenever I try to use malloc/calloc/realloc I always have the same error message pop up that says that s (cf. code above) is an 'unreferenced NULL-pointer'. I really don't see the problem here. Especially because both 'M' and 'I' have been allocated to the array I initialized via malloc, but they're in odd places. I'd expect: s[0] = 'M' and s[1] = 'I' but instead it's s[-1] = 'M' and s[0] = 'I', which I find rather strange. Where did I go wrong?
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 = 'M'; s++; *s = 'I'; std::cout << s[-1] << s[0] << s[1]; } There is another warning though https://learn.microsoft.com/en-us/cpp/code-quality/c6200?view=msvc-170 This is warning that s[-1] looks very odd. Its ignoring the fact that you did s++ earlier which makes this ok. Whats not ok is std::cout << s[-1] << s[0] << s[1]; ------------------------------***** this is accessing data beyond the end of the allocation, result is Undefined Behavior. if you do int main() { char* s = (char*)malloc(2 * sizeof(char)); if (s != NULL) { s[0] = 'M'; s[1] = 'I'; std::cout << s[0] << s[1] << s[2]; } } which is a much more straightforward way of doing the same thing then VS will warn you about that s[2] being out of bounds
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: I write main and child applications.
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 to it as a command line parameter, converted to hex-ascii, say, or you can devise some other method. In the child process, call GetDC to retrieve the HDC of the parent's window and pass it to wglCreateContext (I imagine you know all about doing that sort of thing). In the child process, draw, draw, draw. Before exiting the child process, make sure you call ReleaseDC to free up any resources allocated by GetDC. This ought to work. I know that Chrome uses a separate process for each browser tab, for example (so that if the code rendering into any particular tab should crash, it affects that tab only). Also, if you're thinking of jumping through all these hoops just because you want to reload some (different) DLLs, maybe you're looking for LoadLibrary and GetProcAddress instead. Hmmm, maybe I didn't need to write all that :)
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 wfile; char byte[40]; int n=0; int main() { while(true) { wfile.open("/dev/ttyUSB1"); sprintf(byte,"message : %d\n",n); wfile << byte; wfile.close(); printf("%s",byte); n++; sleep(1); } } And in the terminal window, I see result as message : 0 message : 1 message : 2 message : 3 message : 4 message : 5 message : 6 message : 7 message : 8 message : 9 In the receiver part, my C++ script is written as #include <stdio.h> #include <stdlib.h> int main() { char var[100]; FILE *fp; while(true) { fp=popen("cat /dev/ttyUSB0","r"); fgets(var,sizeof(var),fp); printf("%s",var); pclose(fp); } return 0; } I am expecting to get same result at the terminal window of my receiver's side. I see a result something like message : 1 1 1 1 1 1 1 1 1 ... (repeats about 100 time) 1 1 1 message : 2 ...(void for about 100 line) message : 3 ... message : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 : 4 ... Something like this. I am assuming this is a problem with the buffer in the serial port. Moreover, Receiver is showing messages from old buffers which is not even initialized! Is there any way to fix this as I intended?
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 shell, because it could easily fall apart if it was transferred to a different operating system with a different shell. In the post How do I execute an external program within C in Linux with arguments, the second answer states that execve() is a wrapper for the system() function, and this makes me wary of the other functions in the exec() family. I have also looked at the following articles: How do you write a C program to execute another program? http://www.cplusplus.com/forum/beginner/168287/ Run Another Program in Linux from a C++ Program All help is appreciated!
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 initialize any std:: data types such as a map, vector, or stack. It's weird because I was never receiving this error before and using those classes worked perfectly up to this point. I'm not really sure what's up, could someone point me in the right direction as to how to fix this? I've attached a screenshot below showing the error. I have been looking around and I can't find anyone else with a similar problem. Thanks! #include <vector> #include <map> #include <iostream> #include <cstdlib> #include <string> #include <stdlib.h> using namespace std; /** * @brief Rules: * 1. Open brackets must be closed by the same type of brackets. * 2. Open brackets must be closed in the correct order. * * Leetcode Challenge can be found here: https://leetcode.com/problems/valid-parentheses/ */ //correlate the opening character with the closing character. map<char, char> legend {{'{','}'},{'(',')'},{'[',']'}};//Error vector<int> vect{0,2,3,4,5};//Error bool isValid(string s) { //if s is odd then we know a bracket hasn't been closed. Return false. if (s.length() % 2 != 0) { return false; } vector<char> stack; //initiate our stack where we'll store opening characters "(, {, [" bool stackIsModified = false; //We need to make sure an opening character has been added to the stack at least once. for (int i = 0; i < s.length(); i++) { if (s[i] == '{' || s[i] == '[' || s[i] == '(')//Check and see if s[i] is an opening character. { stackIsModified = true; stack.push_back(s[i]); cout << s[i] << endl; } else if(stack.size() != 0) //See if s[i] is a closing character. { if (legend[stack.at(stack.size() - 1)] == s[i]) { stack.pop_back(); } else //If s[i] is a closing character that doesn't match the corresponding opening character. Ex: "{)" { return false; } } else //If s[i] isn't an opening character and the stack is empty then we know there's a mismatch, return false. { return false; } } if (stack.size() > 0 || !stackIsModified) //Make sure the stack doesn't have remaining opening characters and that the stack has been changed at least once. { cout << stackIsModified << endl; return false; } return true; } int main() { cout << isValid("()))") << endl;//Random test case. return 0; } And these are the errors I'm recieving (at the two lines that have error commented next to them): no instance of constructor "std::__1::map<_Key, _Tp, _Compare, _Allocator>::map [with _Key=char, _Tp=char, _Compare=std::__1::less<char>, _Allocator=std::__1::allocator<std::__1::pair<const char, char>>]" matches the argument listC/C++(289) std::__1::vector<int> vect no instance of constructor "std::__1::vector<_Tp, _Allocator>::vector [with _Tp=int, _Allocator=std::__1::allocator<int>]" matches the argument listC/C++(289)
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 ++ ) { inc = inc++; cout << pam+inc << endl; } return 0; } What I want to get is 1040, 1060, 1080, 10A0, etc. Example; Output: pam + inc pam + inc + inc pam + inc + inc + inc etc...
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) << endl; } Applying some math: for (int i = 0; i < 10; ++i) { std::cout << ((inc * i) + pam) << std::endl; }
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 there are only active threads (assuming there are multiple consumer threads). #include <queue> #include <condition_variable> #include <mutex> using Item = int; std::queue<Item> q; std::condition_variable cv; std::mutex m; void process(Item i){} void pop() { while (true) { std::unique_lock<std::mutex> lock(m); // This thread releases the lock and start waiting. // When notified, the thread start trying to re-acquire the lock and exit wait(). // During the attempt (and thus before `pop()`), can another `push()` call acquire the lock? cv.wait(lock, [&]{return !q.empty();}); auto item = q.front(); q.pop(); process(item); } } void push(Item i) { std::lock_guard<std::mutex> lock(m); q.push(i); if (q.size() == 1) cv.notify_one(); } int main() { /* ... */ } However, is the following scenario possible ? Suppose that all the consumer threads are waiting. the pushing thread acquires the lock and push a new element and calls notify_one because the queue was empty. a notified thread tries to re-acquire the lock (and exit wait()) the pushing thread acquires the lock again and pushes another element before a notified thread re-acquires the lock. In this case, no notify_one call wouldn't occur after 3. and there would be only one active thread when the queue isn't empty.
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 reason, lock is reacquired and wait exits. Means your code is atomic between #1 to #2 when it's woken up. Don't need to worry about the synchronization since your compiler should handle it. void pop() { while (true) { std::unique_lock<std::mutex> lock(m); // When sleep, cv release the lock cv.wait(lock, [&]{return !q.empty();}); // <----#1 // When wake up, it acquires the lock auto item = q.front(); q.pop(); process(item); // <----#2 } } For spurious wakeup The second overload with predicate would handle spurious wakeup for you. template< class Predicate > void wait( std::unique_lock<std::mutex>& lock, Predicate stop_waiting ); (2) (since C++11) Equivalent to while (!stop_waiting()) { wait(lock); } This overload may be used to ignore spurious awakenings while waiting for a specific condition to become true. Note that lock must be acquired before entering this method, and it is reacquired after wait(lock) exits, which means that lock can be used to guard access to stop_waiting(). That is the condition_variable overload with predicate would save you from spurious wake up. The handmade while loop for checking spurious wake up is not needed.
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 reduced to an int data type I can't get it to work. Here's the code: #include <iostream> class testing{ public: testing(); int getValue(); private: int* asdf; }; int main(){ int* test = NULL; int test2, test3; testing test1; test2 = test1.getValue(); test = new int(test2); test3 = *test; std::cout << test3 << std::endl; return 0; } testing::testing(){ int* asdf = new int(3); } int testing::getValue(){ return *asdf; } I expect the code to print out just 3, but it doesn't. What am I messing up?
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 main(){ int* test = NULL; //null pointer. You did not give any valid address. int test2, test3; testing test1; test2 = test1.getValue(); test = new int(test2); test3 = *test; //ERROR! Trying to dereference the null pointer std::cout << test3 << std::endl; return 0; } testing::testing(){ asdf = new int(3); // removed int*, as original expression does hide your member variable. } Additionally, naked new expression easily produces memory leak problem. I recommend you to be familiar to the smart pointers in C++.
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 a connection from this pool, the following function gets executed: gardener_db &connection_pool_inner::get_connection() { bool expected = false; for(auto & pair : pool) { std::atomic_bool &ref = pair->get_is_busy_ref(); if (ref.compare_exchange_strong(expected, true)) { return pair->get_conn(); }//if false it means that its busy } std::lock_guard<std::mutex> guard(vector_mutex);//increment size std::atomic_bool t = true; pool.emplace_back(std::make_shared<pool_elem>()); pool.back()->get_is_busy_ref().store(t);// because we are giving the resource to the caller return pool.back()->get_conn(); } So I made a simple test to see if my vector is resizing: constexpr unsigned int CONNECTION_POOL_START_SIZE = 20; TEST(testConnPool, regrow) { auto saturation = std::vector<connection_handler>(); ASSERT_EQ(saturation.size(), 0); for(int i = 0; i < CONNECTION_POOL_START_SIZE; i++) { saturation.emplace_back(); } auto ptr = connection_pool_inner::instance(); auto size = ptr->get_pool().size(); //it should be full at this point ASSERT_EQ(size, CONNECTION_POOL_START_SIZE); } the problem is that I get 22 as my size as opposed to 20 which is what I would expect. I was able to narrow down the problem to the compare_exchage_strong() but, it was my understanding that the "strong" variant wouldn't fail. So I debugged it, and its always the third element of my vector that gets skipped, (even when working on a single thread). I already test it the same thing on a different computer(and architecture) but the same problem still occurs so I'm guessing the problem is the logic. Any ideas about what's going on? MRE #include <mutex> #include <atomic> #include <iostream> #include <vector> #include <memory> class foo { std::atomic_bool inner; public: explicit foo(): inner(false){}; std::atomic_bool &get(){return inner;} }; std::mutex vector_mutex; std::vector<std::shared_ptr<foo>> resources; void get_resource() { bool expected = false; for(auto & rsc : resources) { if (rsc->get().compare_exchange_strong(expected, true)) { return; } } std::lock_guard<std::mutex> guard(vector_mutex);//increment size resources.emplace_back(std::make_shared<foo>()); } int main() { std::vector<std::shared_ptr<foo>> *local = &resources; for(int i = 0; i < 20; i++) { resources.emplace_back(std::make_shared<foo>()); } for(int i = 0; i < 20; i++) { get_resource(); } std::cout << resources.size(); }
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::atomic::compare_exchange_strong: <...> loads the actual value stored in *this into expected (performs load operation). Let's vector busy to be a conditional name for busy states. The first get_connection() call results in the vector busy to be { true, false, ... false }. The second get_connection() call: expected = false; busy[0] is true is not equal to expected, it gets expected = true; busy[1] is false is not equal to the updated expected, it gets expected = false; busy[2] is false is equal to the updated expected, results in the vector busy to be { true, false, true, false, ... false }. The further 8 get_connection() calls result in the vector busy to be { (true, false) * 10 }. The 11th and 12th get_connection() calls add yet a couple of true and result in the vector busy to be { (true, false) * 10, true, true }, the size is 22. Other get_connection() calls do not modify the vector anymore: <...> busy[10] is true is not equal to expected, it gets expected = true; busy[11] is true is equal to the updated expected, return. The fix // bool expected = false; ───────┐ // │ for(auto & pair : pool) { // │ bool expected = false; // ◄──┘ std::atomic_bool &ref = pair->get_is_busy_ref(); if (ref.compare_exchange_strong(expected, true)) { return pair->get_conn(); }//if false it means that its busy }
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): #include<iostream> using namespace std; const string CORRECT = "\033[7;32m"; const string CLOSE = "\033[7;33m"; const string INCORRECT = "\033[7;37m"; const string END = "\033[0m"; int main() { char word[] = "break"; char guess[] = "water"; char result[5]; string color; for (int i = 0; i < 5; i++){ if (guess[i] != word[i]) { color = INCORRECT + guess[i] + END; result[i] = color } if (guess[i] != word[i] && ) { color = CLOSE + guess[i] + END; result[i] = color } if (guess[i] == word[i]) { color = CORRECT + guess[i] + END; result[i] = color } } return 0; } I've got it to where it checks to see if its not the same position but I need it to also check for it being elsewhere in the char array. Any help is greatly appreciated, thank you.
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 = 0; } Distance(int f, int i) { feet = f; inches = i; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator++ () { feet = feet+1; inches = inches+1; return Distance(feet, inches); } }; int main() { Distance D1(11, 10), D2(-5, 11); ++D1; // increment by 1 D1.displayDistance(); // display D1 ++D2; // increment by 1 D2.displayDistance(); // display D2 return 0; } when I use above code then I can successfully use prefix operator ++D1 and ++D2 but I am not getting how to overload postfix operator D1++ and D2++ even if I try these in above code it showing me error so how can we use concept of operator overloading for postfix and prefix separately?
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 any other unary operator; the postfix form accepts an extra argument of type int.
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 namespace std; int * sort (const int * const ,int ); void display_origin_order(const int * const ,int ); int * sort(const int * const array,int size) { for (int i;i<size;++i) { if(i+3<size||i+3==size) { cout<<*(array+i+3)<<" "; } if (i+3>size) { cout<<*(array+i-2)<<" "; } } return 0; cout<<endl; } void display_origin_order(const int * const array,int size) { for (int i;i<size;++i) { cout<<array[i]<<" "; } cout<<endl; } int main () { int * first_array{nullptr}; int size{0}; first_array = new int [size]; int init_value{0}; cout<<"Please enter the size of the array \n"; cin>>size; cout<<"Now its elements \n"; for (int i;i<size;++i) { cout<<"input variable \n"; cin>>init_value; first_array[i] = init_value; } cout<<"The array's elements in origin order are : "; display_origin_order(first_array,size); cout<<"The array's elements in required order are: "; sort (first_array,size); delete [] first_array; return 0; }
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(const int * const array,int size) { for (int i=0;i<size;++i) { if(i+3<size) { cout<<*(array+i+3)<<" "; } else { cout<<*(array+i+3-size)<<" "; } } return 0; cout<<endl; } Addition : sort is not a proper name for this function. I suggest the name display_shift to reduce the reader's confusion. EDIT: As @user17732522 pointed out, main function also has some bugs. you initialized the first_array by new int[size], when the size is 0. you have to initialize the first_array after getting the size like this: int main () { int * first_array{nullptr}; int size{0}; int init_value{0}; cout<<"Please enter the size of the array \n"; cin>>size; first_array = new int [size]; // initialize the first_array AFTER you get its size... cout<<"Now its elements \n"; for (int i=0;i<size;++i) // You forgot the initialization here, too! { // rest is same... } } Addition 2 : When you trying to shift the elements, there is more simpler, safer way to do this, using the operator %: void display_shift(const int * const array,int size) { for (int i=0;i<size;++i) { cout<<*(array+(i+3)%size)<<" "; } } That's because when the size is so small that i+3 is more than twice the size, you actually have subtract 2*size, and the program will be more complicated. modulo operator(%) reduces those complication, and you do not have to check bound when using this operator!
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 % 2) == 0); } template<class T, class = std::enable_if_t<std::is_floating_point_v<T>>> bool is_even(T value) { std::cout << "\n Floating point version "; return false; } int main() { std::cout << "is_even (4) = " << std::boolalpha << is_even(4); std::cout << "is_even (4.4) = " << std::boolalpha << is_even(4.4); } Errors as below Error(s): 462942513/source.cpp:13:6: error: redefinition of ‘template<class T, class> bool is_even(T)’ bool is_even(T value) ^~~~~~~ 462942513/source.cpp:7:6: note: ‘template<class T, class> bool is_even(T)’ previously declared here bool is_even(T value) ^~~~~~~ 462942513/source.cpp: In function ‘int main()’: 462942513/source.cpp:22:69: error: no matching function for call to ‘is_even(double)’ std::cout << "is_even (4.4) = " << std::boolalpha << is_even(4.4); ^ 462942513/source.cpp:7:6: note: candidate: template<class T, class> bool is_even(T) bool is_even(T value) ^~~~~~~ 462942513/source.cpp:7:6: note: template argument deduction/substitution failed: Even this syntax without default arguments doesn't work #include <iostream> #include <type_traits> template<class T, std::enable_if_t<std::is_integral_v<T>>> bool is_even(T value) { return ((value % 2) == 0); } template<class T, std::enable_if_t<std::is_floating_point_v<T>>> bool is_even(T value) { return false; } int main() { std::cout << "is_even (4) = " << std::boolalpha << is_even(4) << "\n"; std::cout << "is_even (4.4) = " << std::boolalpha << is_even(4.4) << "\n"; }
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 are not accounted for in function template equivalence). One way to solve this problem in your given example would be to use the enable_if_t expression when specifying the return type of the function template instead of as a default argument, as shown below: template<class T> std::enable_if_t<std::is_integral_v<T>,bool> is_even(T value) { return ((value % 2) == 0); } template<class T> std::enable_if_t<std::is_floating_point_v<T>, bool> is_even(T value) { std::cout << "\n Floating point version "; return false; } Demo Solution 2 #include <iostream> #include <type_traits> template<class T, std::enable_if_t<std::is_integral_v<T>, bool> = true> auto is_even(T value) { return ((value % 2) == 0); } template<class T, std::enable_if_t<std::is_floating_point_v<T>, bool> = true> auto is_even(T value) { std::cout << "\n Floating point version "; return false; } int main() { std::cout << "is_even (4) = " << std::boolalpha << is_even(4); std::cout << "is_even (4.4) = " << std::boolalpha << is_even(4.4); } Demo
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> #include<deque> #include<queue> #include<set> #include<list> #include<limits> #include<string> #include<memory> using namespace std; class random_Point_CCS_xy_generator; class Point_CCS_xy{ private: long double x_coordinate_ {0.0}; long double y_coordinate_ {0.0}; public: Point_CCS_xy () = default; Point_CCS_xy(long double x, long double y); ~Point_CCS_xy() = default; Point_CCS_xy(const Point_CCS_xy& cpyObj); Point_CCS_xy(Point_CCS_xy&& moveObj) noexcept; Point_CCS_xy& operator=(const Point_CCS_xy& l_val_RHS); Point_CCS_xy& operator=(Point_CCS_xy&& r_val_RHS) noexcept; __attribute__((unused)) inline void set_x_coordinate(long double x); __attribute__((unused)) inline void set_y_coordinate(long doubley); __attribute__((unused)) inline long doubleget_x_coordinate() const; __attribute__((unused)) inline long doubleget_y_coordinate() const; bool operator<(const Point_CCS_xy& pnt) const; bool operator==(const Point_CCS_xy& RHS) const; long double direct_pnt_to_pnt_distance(const Point_CCS_xy& a, const Point_CCS_xy& b) const; long double squared_direct_pnt_to_pnt_distance(const Point_CCS_xy& a, const Point_CCS_xy& b) const; long double distance_to_this_pnt_sq(const Point_CCS_xy& other) const; void print_point_xy () const; friend ostream& operator<<(ostream& os, const Point_CCS_xy& pnt); vector<Point_CCS_xy> Random_Point_CCS_xy(long double Min, long double Max, size_t n); vector<shared_ptr<Point_CCS_xy>> Random_Point_CCS_xy2_(long double Min, long double Max, size_t n); }; // the comparator under question class Less_Distance : public std::binary_function<Point_CCS_xy, Point_CCS_xy, bool> { Point_CCS_xy& point_; public: explicit Less_Distance(Point_CCS_xy& reference_point) : point_(reference_point) {} bool operator () (const Point_CCS_xy& a, const Point_CCS_xy& b) const { return point_.distance_to_this_pnt_sq(a) < point_.distance_to_this_pnt_sq(b); } }; int main() { vector<Point_CCS_xy> points { move(Point_CCS_xy(68.83402637, 38.07632221)), move(Point_CCS_xy(76.84704074, 24.9395109)), move(Point_CCS_xy(16.26715795, 98.52763827)), move(Point_CCS_xy(70.99411985, 67.31740151)), move(Point_CCS_xy(71.72452181, 24.13516764)), move(Point_CCS_xy(17.22707611, 20.65425362)), move(Point_CCS_xy(43.85122458, 21.50624882)), move(Point_CCS_xy(76.71987125, 44.95031274)), move(Point_CCS_xy(63.77341073, 78.87417774)), move(Point_CCS_xy(8.45828909, 30.18426696)) }; cout << "we are here" << endl; for(auto p : points) { cout << p << endl; } Point_CCS_xy inquiry_pnt(16.452, 70.258); Less_Distance nearer_point(inquiry_pnt); vector<Point_CCS_xy> nn_points; // Problematic part of the code: priority_queue<Point_CCS_xy, vector<Point_CCS_xy>, nearer_point> pQ; for(auto pnt : points) { pQ.push(pnt); } while(!pQ.empty()){ nn_points.push_back(move(pQ.top())); pQ.pop(); } for(auto p : nn_points) { cout << p << endl; } return 0; } The error is Template argument for template type parameter must be a type. since I am a newbie, any comment would be helpful, thus appreciated.
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> T* get(std::size_t bshift) { return static_cast<T*>( reinterpret_cast<void*>( reinterpret_cast<unsigned char*>(data) + bshift ) ); } Is it safe or UB? Why? float &fvalue2 = *get<float>(sizeof(float)); fvalue2 = 0.02f; Is it safe or UB? Why? float &fvalue_reserve = *get<float>(sizeof(float)*2 + 1); fvalue = 0.03f; Is it safe or UB? Why? double &dvalue = *get<double>(sizeof(float)*3 + 1); dvalue = 0.04; Is it safe or UB? Why? // assume that somehow there is no unused internal padding in struct struct POD_struct{ float fvalue1; //[0..sizeof(float)] float fvalue2; //[sizeof(float)..sizeof(float)*2] char reserved[sizeof(float) + 1];//[sizeof(float)*2..sizeof(float)*3+1] double dvalue; //[sizeof(float)*3+1..sizeof(float)*3+1+sizeof(double)] }; POD_struct pod_struct; std::memcpy(&pod_struct, get<void*>(0), sizeof(POD_struct)); pod_struct.fvalue2 == 0.02f; //true ?? pod_struct.dvalue == 0.04f; //true ?? Is it safe or UB? Why? is it any different from №4? // assume that somehow there is no unused internal padding in struct struct POD_struct{ float fvalue1; //[0..sizeof(float)] float fvalue2; //[sizeof(float)..sizeof(float)*2] char reserved[sizeof(float) + 1];//[sizeof(float)*2..sizeof(float)*3+1] double dvalue; //[sizeof(float)*3+1..sizeof(float)*3+1+sizeof(double)] }; POD_struct pod_struct; std::memcpy(&pod_struct, get<POD_struct*>(0), sizeof(POD_struct)); pod_struct.fvalue2 == 0.02f; //true ?? pod_struct.dvalue == 0.04f; //true ?? Would it make any significant difference if we "fill" memory pointed by data pointer not from zero offset (f.e. 1, 2, 3?) and then memcpy to POD_struct object from that offset? Is it safe to assume that if we manage required size of continuous block of raw memory buffer to fit all POD members without paddings (aligned by 1 byte) then it's ok to interpret it as any POD type? Is it safe to reuse raw memory and interpret it as another POD type storage since we done using it?
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 pointer to a suitable created object, but that object would have to be a unsigned char object part of an unsigned char array in order to give the pointer arithmetic in reinterpret_cast<unsigned char*>(data) + bshift defined behavior. However, then the return value of get<float>(sizeof(float)); would also be a pointer to an unsigned char object. Writing through a float glvalue to a unsigned char violates the aliasing rules. This could be remedied by either using std::launder before returning the pointer from get or better by explicitly creating the object: template<class T> T* get(std::size_t bshift) { return new(reinterpret_cast<unsigned char*>(data) + bshift) T; } Although this will create a new object with indeterminate value each time it is called. std::launder would be sufficient here without creating a new object since ::operator new can implicitly create an unsigned char array which provides storage for a float object which is also implicitly-created. (Assuming all objects used in this way fit in the storage, are correctly aligned (see below), do not overlap and are implicit-lifetime types): template<class T> T* get(std::size_t bshift) { return std::launder(reinterpret_cast<T*>(reinterpret_cast<unsigned char*>(data) + bshift)); } However, 2. and 3. have undefined behavior even with this modification if alignof(float) != 1 (which is very likely to be true). You cannot create and start the lifetime of an object with wrong alignment either implicitly or explicitly. (Although it may technically be possible to create an object with wrong alignment explicitly without starting its lifetime.) For 4. and 5., assuming the above weren't undefined behavior due to misalignment or out-of-bounds access and given the assumptions in the question, I think these snippets should have defined behavior. Note however that it is extremely unlikely that these requirements are satisfied. For 6., if you offset everything you need to again take care not to go out-of-bounds of the allocation and not to violate the alignment of any of the involved types. (Including the alignment of POD_struct for 5.) For 7. the formulation is very vague, so I am not sure what you mean. But you explicitly generally can't interpret memory as a different type than it is. In your examples 4. and 5. you are copying object representations, which is different. To be clear again: Practically speaking your code has UB due to the alignment violations. This probably extends even to platforms that allow unaligned access, because the compiler may optimize code based on the assumption of pointer alignment. Compilers may offer type annotations to indicate that a pointer may be unaligned. You need to use these or other tools if you want to implement unaligned access in practice.
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. There is a field called "Treat Specific Warnings As Error", which has an "Edit" functionality. But what do I enter there? The compiler warning as I get it from the build output: C4390. The compiler switch: /We4390 No matter what I do, when I have a look at the complete command line, there is no compiler switch for that warning.
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, that's how you'd declare an array variable. Add a typedef, and the variable name becomes a new name for the type. Of course, a modern type alias will actually look more like what you expect using yes = char[1]; using no = char[2]; Which is good in the sense that it doesn't require one to understnad C++'s declarator syntax just to see what the name of the type is. One still has to understand the syntax to write the type on the right hand side, though...
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; A::BPtr b = a.funct(); std::cout << b->x << std::endl; } outputs "1234", and so does class A { private: struct B{ int x = 1234; } b; public: B funct(){ return b; }; }; int main() { A a; std::cout << a.funct().x << std::endl; } even though A::B b = a.funct(); would not compile (but auto b = a.funct() would). Lesson: if you hand someone a thing, they can use it - even if they don't know what to call it.
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, num2; char operation = ' ', I, D; cout << "Enter the first variable: "; cin >> num1; cout << "Enter the second variable: "; cin >> num2; cout << endl; cout << "Do you want Auto increment, decrement or both? (Type 'I', 'D' or 'B'): "; cin >> operation; if (operation == 'I') { cout << inc(num1,num2); } else if (operation == 'D') { cout << dec(num1,num2); } else if (operation == 'B') { cout << inc(num1,num2); cout << endl; cout << dec(num1,num2); } else { cout << "Error please enter 'I', 'D' or 'B' as a option" << endl; } return 0; } int inc (int num1, int num2) { num1++; num2++; cout << "Number 1 ++ is: " << num1 << endl; cout << "Number 2 ++ is: " << num2 << endl; return 0; } int dec (int num1, int num2) { --num1; --num2; cout << "Number 1 -- is: " << num1 << endl; cout << "Number 2 -- is: " << num2 << endl; return 0; } I just started taking Fundamentals of programming I at college and i have this assignment and this 0 keeps appearing after the function has completed
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 resuls (that happens in inc and dec).
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(Binary_TreeNode* bt) { if (bt == NULL) { return; } inorder(bt->Left); cout << bt->data << endl; inorder(bt->Right); } inorder traversal void BinaryTree_Functions::postorder(Binary_TreeNode* bt) { if (bt == NULL) { return; } postorder(bt->Left); postorder(bt->Right); cout << bt->data << endl; } postorder traversal I know how these traversals work but I did not understand the code.
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<iostream> #include<string> struct fake_tree { unsigned size = 4; void preorder(const std::string& node){ if (node.size() >= size) return; std::cout << node << "\n"; preorder(node+"l"); preorder(node+"r"); } void postorder(const std::string& node){ if (node.size() >= size) return; postorder(node+"l"); postorder(node+"r"); std::cout << node << "\n"; } void inorder(const std::string& node){ if (node.size() >= size) return; inorder(node+"l"); std::cout << node << "\n"; inorder(node+"r"); } }; int main() { fake_tree ft; ft.preorder("0"); std::cout << "\n"; ft.postorder("0"); std::cout << "\n"; ft.inorder("0"); } output is: 0 0l 0ll 0lr 0r 0rl 0rr 0ll 0lr 0l 0rl 0rr 0r 0 0ll 0l 0lr 0 0rl 0r 0rr The output tells you directly where in the call stack the output is produced. For example the last 0rr is produced by inorder("0") calling inorder("0r") which in turn calls inorder("0rr"). Because inorder("0") first calls inorder("0l") then prints "0" and then calls inorder("0r"), thats the order you see in the output. Similarly inorder("0r") first calls inorder("0rl") then prints "0r" then calls inorder("0rr"). If you now draw the tree on paper you can track how the different traversals go through the tree in different ways.
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("long long long long long long long string"); vector.push_back("long long long long long long long string"); So let's imagine the vector memory block is 256 bytes wide, the two long string will be allocated after the vector memory block. Now, let's imagine we do another push_back to the vector. If the current capacity is not enough, we will reallocate everything. It seems to be fair to me. So actually, we do have only one BIG memory block at a time. (which is componed by the vector block, and the 2 long string) Now let's imagine we change the first "short_string" by doing something like vector[0] = getLongString(). If the memory resource still have place inside it, when we call the allocate function, it will returns a pointer to a valid address, without any problem. However, let's imagine the memory resource object does not have any space anymore. There is several possibilities : The memory resource just throw an exception : We keep the only one big memory block The memory resource just allocate new space (for example from the heap) and the string is now allocated on an another place than the first memory block allocated : we have 2 big memory block (1 componed by the vector and some string, and one componed only by the new big string) The memory resource allocates new space, and tell the vector (by magic ?) to reallocate everything using this new big block. I think only the 1 and 2 are corrects, but I am not sure. Is the third possibilities possible?
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 sequences of do_allocate calls. Either it keeps handing out memory forever, or it throws under some circumstances.
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 template, i.e., template<Type, Type2> Oh, please ignore the unknown classes such as Foam, fvMatrix. Thanks~ template<class Type> template<class Type2> void Foam::fvMatrix<Type>::addToInternalField ( const labelUList& addr, const Field<Type2>& pf, Field<Type2>& intf ) const { if (addr.size() != pf.size()) { FatalErrorInFunction << "addressing (" << addr.size() << ") and field (" << pf.size() << ") are different sizes" << endl << abort(FatalError); } forAll(addr, facei) { intf[addr[facei]] += pf[facei];//intf是diag } }
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& operator= (const Foo<U>&); // can be assigned from any other specilizations }; // definition template <typename T> template <typename U> Foo<T>& Foo<T>::operator= (const Foo<U>&) { ... } For copy assignments from different specializations, you have to do this. The first template <typename T> belongs to the class template Foo, and the second template <typename U> belongs to the copy assignment operator, it's an inner template. For your second question, the answer is No. One template parameter list can only introduce one template. There are two templates here. The second class template Foam::fvMatrix is of no business with template parameter T2. (For those who are interested in source code, see header and implementation) Aside: this topic is covered in the 5.5.1 section of C++ Templates: The Complete Guide.
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 false; }
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, bool B, bool A) { if (A) return true; else if (!B) { if (C) return true; else return false; } else return false; } is equivalent to: bool f(bool C, bool B, bool A) { if (A) return true; else if (!B and C) return true; else return false; } is equivalent to: bool f(bool C, bool B, bool A) { if (A or (!B and C)) return true; else return false; } is equivalent to: bool f(bool C, bool B, bool A) { return (A or (!B and 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 C++, but would be nice if it would also work for other programming languages /** * This the version of quicksort that actually performs partitioning, recursive calls, etc. * * @param ar = pointer til arrayet * @param start = sted man skal starte med at sorte * @param end = stedet sorting skal slutte * * @pre gets an unsorted array * */ template<typename T> void quicksort(T* ar, int start, int end) { // if (base case reached) return; // Base case: No sorting necessary // select pivot index and position pivot; // partition ar[start; end]; // Assume: Pivot is at index k after partitioning // quicksort(ar, start, k - 1); // quicksort(ar, k + 1, end); } How it looks with parameter descriptions I have tried searching on google, and I can see something with doxygen and xml documentation, but I'm not sure how to get it to work.
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_name = G_CAN_INLINE; Give Intellisense a moment to catch up. Right-click on G_CAN_INLINE and select 'Go To Definition'. With a bit of luck, VS will then show you where that macro is (also) being defined and that should help you figure out what to do. Having said which, G_CAN_INLINE doesn't look to be all that important. You will probably find that you can just #undef it before you include glibconfig.
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 C++, how can I process only one line from standard input in each test case iteration. The code that I have tried is like this. #include <iostream> #include <iterator> #include <algorithm> using namespace std; int main() { freopen("input.txt","r",stdin); int T; cin>>T; for(int i=1; i<=T; ++i) { vector<int> arrayInt; int n; //Should only process one line for each test case while(cin>>n) { arrayInt.push_back(n); } int max = *max_element(arrayInt.begin(), arrayInt.end()); int min = *min_element(arrayInt.begin(), arrayInt.end()); cout<<"Test case " << i << ": Max :" << max << ", Min :"<< min << "\n"; } } Output that I got when I run it on the command line Test case 1: Max :1000, Min :1 Please help me to fix my code. Thanks in advance for the answers.
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); std::istringstream linestream{line}; while(linestream >> n) { arrayInt.push_back(n); } Also note that there is std::minmax_element which can get both min and max in a single pass.
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() { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int* copyPtr = new int[8]; copyPtr = copyArray(a, 8); for (int i = 0; i < 8; ++i) cout << copyPtr[i] << " "; delete[] copyPtr; } Is there any way that I can delete copy array from the main function? I understand the use of smart pointers but I cant use it in this case because of the prototype given by my teacher.
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 the array. What you miss is to delete the initial array you created via int* copyPtr = new int[8]; and because you lost any pointer to it you cannot delete it anymore. You could keep the pointer to that initial array and delete it as well. Though, there is no point in allocating an array just to throw it away and create a new array inside the function. Change your code to int main() { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int* copyPtr = copyArray(a, 8); for (int i = 0; i < 8; ++i) cout << copyPtr[i] << " "; delete[] copyPtr; } PS: I understand the use of smart pointers but I cant use it in this case because of the prototype given by my teacher. Your conclusion is not right. Smartpointers can interoperate with raw pointers quite well. You just need to take care with ownership. int* arr is passed as raw pointer. Thats completely fine, because the function does not participate in ownership of that array. It merely reads its values. Raw pointers are for non-owning pointers. If you want to take ownership of the returned pointer you can use a std::unique_ptr<int[]>: int main() { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; auto copy = std::unique_ptr<int[]>(copyArray(a,8)); for (int i = 0; i < 8; ++i) std::cout << copy[i] << " "; // no delete !!! the unique_ptr does that for you }
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>, 1>; void foo(const std::pair<Cursor_matrix,std::string> &out) { Cursor_matrix PosTextfield; PosTextfield = std::get<0>(out); std::string val = std::get<1>(out); std::cout << PosTextfield[0][0] << PosTextfield[0][1] << val << "\n"; } int main() { Cursor_matrix pos; pos[0][0] = 1; pos[0][1] = 2; std::string str = "hello"; std::pair<Cursor_matrix, std::string> pos_text; pos_text = std::make_pair(pos, str); return 0; }
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 well, since auto will deduce it, but writing it explicitly makes it clear to the reader that the two references are non-modifiable. This doesn't create any new objects. The references refer to the elements of the pair passed to the function. Or just refer to the element directly where you want to use them with out.first and out.second or std::get<0>(out) and std::get<1>(out).
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.gnu.org/wiki/cxx-modules#Example) with that command : g++-11 -std=c++20 -fmodules-ts main.cpp -o app -Xlinker libhello.so In module imported at main.cpp:1:1: hello: error: failed to read compiled module: No such file or directory hello: note: compiled module file is 'gcm.cache/hello.gcm' hello: note: imports must be built before being imported hello: fatal error: returning to the gate for a mechanical issue Should I share hello.gcm file too ? And put it in /usr/local/lib too ?
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 theirs): The CMI is not a distributable artifact. Think of it as a cache, that can be recreated as needed. (Where CMI stands for Compiled Module Interface, and corresponds to your gcm file.) So I guess you shouldn't do that. For one thing, your link states that it might contain absolute paths (to include files referenced by the module interface via your include path, typically), and that sounds like a recipe for trouble. Also, these files are not portable across different compilers (and possibly even compiler versions). So, the solution seems to be to supply your module interface file(s) along with your library and tell your users to recompile them before they try to do anything else. You can tell them how in your readme file.
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 understanding how the push_back function works. This is the function I am using: vector<int> inorderTraversal(TreeNode* root) { vector<int> order {}; if (root != nullptr) { inorderTraversal(root->left); cout << "pushing back : " << root->val << std::endl; order.push_back(root->val); inorderTraversal(root->right); } return order; } For the input tree [1,null,2,3] My stdout is printing: pushing back : 1 pushing back : 3 pushing back : 2 Which is correct but my returning array (order) is only [1].
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); auto tmp = inorderTraversal(root->right); order.insert(order.end(), tmp.begin(), tmp.end()); } return order; } Much More Efficient That said, if you counted the number of local vectors created in this, though short, they will be many (as many as there are nodes in your tree, in fact). You can eliminate all of those middle-men vectors by providing a shim between the actual traversal and the creation of the order vector: void inorderTraversal_v(TreeNode const *root, std::vector<int>& order) { if (root != nullptr) { inorderTraversal(root->left, order); order.push_back(root->val); inorderTraversal(root->right, order); } return order; } std::vector<int> inorderTraversal(TreeNode const *root) { std::vector<int> order; inorderTraversal_v(root, order); return order; } Doing this creates a single vector, and in so doing eliminates (N-1) temporary vectors along the way, where N is the number of nodes in the tree.
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 machineName; if ((res = GetComputerNameA(buf, &size))) { machineName = QString::fromAscii(buf, size); } else machineName = "FALSE!"; return machineName; }
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::cout << "destr\n"; } }; int main() { try { test t{3}; } catch(...) { std::cout << "caught\n"; } } output: default constr argument constr destr caught But, Stroustrup says the following in his book (4th edition, page 503): An object is not considered constructed until its constructor completes (...). When using a delegating constructor, the object is not considered constructed until the delegating constructor completes – just completing the delegated-to constructor is not sufficient. A destructor will not be called for an object unless its original constructor completed. Am I misreading this or does he mean something else?
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_traits> lib as codes below: template <typename T> long double SumValue(T first) { if (is_arithmetic<T>::value) return first; else return 0; } template <typename T, typename... Args> long double SumValue(T first, Args... args) { if (is_arithmetic<T>::value) return first + SumValue(args...); else return SumValue(args...); } But compiler reports an error: error: invalid operands of types 'const char*' and 'long double' to binary 'operator+' return first + SumValue(args...); ~~~~~~^~~~~~~~~~~~~~~~~~~ I can understand the error described, but, I cannot figure out a solution for it.
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; } template <typename T, typename... Args> long double SumValue(T first, Args... args) { return SumValue(first) + SumValue(args...); } LIVE BTW: Since C++17 you can use Constexpr If. template <typename T> long double SumValue(T first) { if constexpr (std::is_arithmetic<T>::value) return first; else return 0; } template <typename T, typename... Args> long double SumValue(T first, Args... args) { return SumValue(first) + SumValue(args...); } LIVE
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 all the elements of A are contained in B. This question is different from the one in the title. For the first, there std::is_permutation. However, for some container types, there are more efficient algorithms. For example, if the container is sorted (such as std::set), then you can simply compare for equality. For the second, there's no general algorithm. If the containers are sorted, then you can use std::includes. Otherwise you can write an algorithm that sorts first, and then uses std::includes. I used std::all_of with a predicate that checks membership in the other container If the larger container has fast lookup (such as unordered set), then this solution is good.
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; } Calling code: bool VPLIB_Return; string verstring = "XX"; VPLIB_Return = GetLibVersion(verstring); This works fine in the release version of the calling program but in the debug version, the verstring parameter appears to be completely mangled (i.e. verstring = "\x11ta\x2") between the call and the target function GetLibVersion. I have closely inspected the project properties between the debug and release versions, setting them equal and back to no avail. Just wondering if anyone has any insight as to why parameter passing would be different between a debug and release build. One other point, this DLL library has many other functions which appear to working just fine.
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 using debug versions of std. The fix required making 2 changes to the Project Properties for the debug config: 1) change C/C++->Code Generation->Runtime Library from Multi-threaded Debug DLL to Multi-threaded DLL and 2) changed the C/C++->Preprocessor Definitions to include NDEBUG instead of _DEBUG. I did not realize that the std library had debug and nodebug versions.
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 be placed at the center of a node and then rotated to end in the next node on the path. Currently I hardcoded every coordinateS difference and match it to the corresponding angle with a switch statement, are there better ways?
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++) { ans = ans ^ arr[i]; } // XOR [1, n-1] for (int i = 1; i < arr.size(); i++) { ans = ans ^ i; } cout << ans; return ans; } int main() { vector<int> arr = {5, 2, 5, 2, 7, 6, 6}; findDuplicate(arr); }
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, which is ignored in main(). You probably want to do this in main: int answer = findDuplicate(arr); cout << "And the answer is " << answer << endl; Or something like that. That's all fine and good. That's the easy stuff. But why do you think this XOR code is going to tell you what duplicates their are, especially when there might be multiples of the same value or more than one value with duplicates. Maybe there is some algorithm you know about that none of us do. But it's printing out 0 when the data clearly has duplicates. Every duplicate finder I know about that's remotely efficient sorts the data then does a loop through it, keeping track of the last value, and if the next value equals the previous value, you have a duplicate. #include <algorithm> std::sort(vec.begin(), vec.end()); int prevValue = vec[0]; for (int index = 1; index < vec.size(); ++index) { int thisValue = vec[index]; if (thisValue == prevValue) { ... Print it } prevValue = thisValue; } You can make this smarter if you want to know how many are duplicated, and want to be smart about not printing 6 is duplicated 17 times in a row.
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 is neither asking for mapping memory (like malloc) and nor it is checking weather the memory pointed by rbp is allocated to the process. So it assumes that startup code has mapped enough memory for the entire depth of call stack. So exactly how much memory is allocated for call stack? How does startup code can know the maximum depth of call stack? It also means that, I can access array out of bound for a long distance since although it is not in current frame, it mapped to the process. So I wrote this code: int main() { int arr[3] = {}; printf("%d", arr[900]); } This is exiting with SIGSEGV when index is 900. But surprisingly not when index is 901. Similarly, it is exiting with SIGSEGV for some random indices and not for some. This behavior was observed when compiled with gcc-x86-64-11.2 in compiler explorer.
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, arrays) in automatic storage, and why you must avoid recursion with linear depth (such as recursive linked list algorithms). So exactly how much memory is allocated for call stack? On most desktop/server systems it's configurable, and defaults to one to few megabytes. It can be much less on embedded systems. This is exiting with SIGSEGV when index is 900. But surprisingly not when index is 901. In both cases, the behaviour of the program is undefined. Is it possible to know the allocated stack size? Yes. You can read the documentation of the target system. If you intend to write a portable program, then you must assume the minimum of all target systems. For desktop/server, 1 megabyte that I mentioned is reasonable. There is no standard way to acquire the size within C++.
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 it's most likely a process handle, but on *nix there's no such thing of course. ... And Ted beat me to it :)
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?), e.g. field<0, 1, int, 3> compiles and run. But I cannot access it afterwards.
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 with int field;: `-CXXRecordDecl 0x168af90 <test2.cpp:1:1, line:3:1> line:1:8 struct foo definition `-FieldDecl 0x168b150 <line:2:3, col:7> col:7 field 'int' So, it looks like Clang thinks that an int field is being declared, but the name of the field is empty. This seems to be corroborated by being able to initialise this "unnamed" field: foo f{0}; // compiles in Clang The first Clang version to have this bug seems to be 9: https://gcc.godbolt.org/z/d386oz8v8
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 to it. Could anyone please explain? And don't point me to the documentation please. I have spent time there and still its not clear to me else i wouldn't be posting this question here. #include <iostream> #include <type_traits> //template<class T, std::enable_if_t<std::is_integral_v<T>, bool>> template<class T, std::enable_if_t<std::is_integral_v<T>, bool> K = true> void fun(T value) { std::cout << "\n In Integral version"; } //template<class T, std::enable_if_t<std::is_floating_point_v<T>, bool>> template<class T, std::enable_if_t<std::is_floating_point_v<T>, bool> K = true> void fun(T value) { std::cout << "\n In Floating point version"; } int main() { fun(4); fun(4.4); } following errors are shown when i use commented code and i dont know what they mean or how the above code resolves them. Error(s): 2044199993/source.cpp: In function ‘int main()’: 2044199993/source.cpp:22:10: error: no matching function for call to ‘fun(int)’ fun(4); ^ 2044199993/source.cpp:8:6: note: candidate: template<class T, typename std::enable_if<is_integral_v<T>, bool>::type <anonymous> > void fun(T) void fun(T value) ^~~ 2044199993/source.cpp:8:6: note: template argument deduction/substitution failed: 2044199993/source.cpp:22:10: note: couldn't deduce template parameter ‘<anonymous>’ fun(4); ^ 2044199993/source.cpp:15:6: note: candidate: template<class T, typename std::enable_if<is_floating_point_v<T>, bool>::type <anonymous> > void fun(T) void fun(T value) ^~~ 2044199993/source.cpp:15:6: note: template argument deduction/substitution failed: 2044199993/source.cpp:22:10: note: couldn't deduce template parameter ‘<anonymous>’ fun(4); ^ 2044199993/source.cpp:23:12: error: no matching function for call to ‘fun(double)’ fun(4.4); ^ 2044199993/source.cpp:8:6: note: candidate: template<class T, typename std::enable_if<is_integral_v<T>, bool>::type <anonymous> > void fun(T) void fun(T value) ^~~ 2044199993/source.cpp:8:6: note: template argument deduction/substitution failed: 2044199993/source.cpp:23:12: note: couldn't deduce template parameter ‘<anonymous>’ fun(4.4); ^ 2044199993/source.cpp:15:6: note: candidate: template<class T, typename std::enable_if<is_floating_point_v<T>, bool>::type <anonymous> > void fun(T) void fun(T value) ^~~ 2044199993/source.cpp:15:6: note: template argument deduction/substitution failed: 2044199993/source.cpp:23:12: note: couldn't deduce template parameter ‘<anonymous>’ fun(4.4); ^
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"; } Its templates with two template arguments. The issue arises when you want to call them. If you try to call them like you do in main: int main() { fun(4); fun(4.4); } You will get an error along the line of: <source>:18:5: error: no matching function for call to 'fun' fun(4); ^~~ <source>:5:6: note: candidate template ignored: couldn't infer template argument '' void fun(T value) ^ <source>:11:6: note: candidate template ignored: couldn't infer template argument '' void fun(T value) ^ <source>:19:5: error: no matching function for call to 'fun' fun(4.4); ^~~ <source>:5:6: note: candidate template ignored: couldn't infer template argument '' void fun(T value) ^ <source>:11:6: note: candidate template ignored: couldn't infer template argument '' void fun(T value) ^ The templates have 2 template arguments. One is T the other is either a bool or a substitution failure. The second argument cannot be deduced from the function parameters, hence the error. Consider what you get in case of T==int. std::enable_if_t is just an alias. In your case either for bool or the alias is not defined: template<int, bool> // because int is integral void fun(T value) { std::cout << "\n In Integral version"; } template<int, "substitution failure"> // because int is integral void fun(T value) { std::cout << "\n In Floating point version"; } The second is a substitution failure, so overload resolution picks the first. And it has two template arguments. The second template argument is not used for anything but to fail when the condition is false. You do not want the user to call fun<int,true>(42); You want the caller to call it via fun(42); because explicitly specifying the tempalte argument would defeat the whole purpose of SFINAE here. The way to not reqiure the caller to specify the template argument in case it cannot be deduced is to supply a default. And thats the K = true. K = false would work as well. And as you do not have to name the argument the following works as well: template<class T, std::enable_if_t<std::is_integral_v<T>, bool> = true> void fun(T value) { std::cout << "\n In Integral version"; } template<class T, std::enable_if_t<std::is_floating_point_v<T>, bool> = true> void fun(T value) { std::cout << "\n In Floating point version"; }
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 the file pointers closed and the file on my PC is closed in every program. Here's the code static bool correctFile(string fileName) { string name = fileName; FILE* test = fopen(fileName.c_str(), "rb"); FILE *in, *out; char stringTest[1000]; bool isWinFile = false; if (!test) { return false; } fread(stringTest, 1, 1000, test); fclose(test); for (size_t i = 0; i < strlen(stringTest) && !isWinFile; i++) { if (stringTest[i] == '\r') { isWinFile = true; } } if (isWinFile) { in = fopen(fileName.c_str(), "rb"); string tempFile = name + ".temp"; out = fopen(tempFile.c_str(), "wb"); if (!in || !out) { return false; } char temp; while (fread(&temp, sizeof(temp), 1, in) > 0) { if (temp != '\r') { fwrite(&temp, sizeof(temp), 1, out); } } fclose(in); fclose(out); if (std::remove(fileName.c_str())) { std::cerr << "Error: " << strerror(errno); return false; } if (std::rename(tempFile.c_str(), fileName.c_str())) { return false; } } return true; } If you find an error in this please tell me, thanks
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. void functionTwo(){} // as well here. int main (){ cout<<"Type the length number of the array : "; cin >> RangeOfArray;` } As you can see I need the array (arr) everywhere in my program but I can't why? I don't know
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 is implicitly converted to the maximum value of the type size_t due to the usual arithmetic conversions because in C++ an expression that specifies a size of an array in its declaration is converted to the type size_t. For starters variable length arrays is not a standard C++ feature. And moreover you may not declare a variable length array with static storage duration. And secondly using the expression -1 as the size of an array does not make a sense. If you need a global variable that simulates an array then use the standard container std::vector<int>. For example #include <iostream> #include <vector> //global variables std::vector<int> arr; void functionOne(){ /* ... */ } // I need to access the array here. void functionTwo(){ /* ... */ } // as well here. int main() { size_t RangeOfArray; std::cout<<"Type the length number of the array : "; std::cin >> RangeOfArray;` arr.resize( RangeOfArray ); //... } The vector provides member function size that reports the current number of elements stored in the vector. So you need not to make the variable RangeOfArray global. Pay attention to that it is not a good idea to use global variables. So you could declare the vector in main and pass it by reference to functions where it is required.
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 couldn't scan line correctly which I've translated into : string line; string word; stringstream ss(line); float x, y, z; if (!(ss >> word >> x >> y >> z)) // "vn x y z" break; // quitting loop because couldn't scan line correctly The difference is that I use a string to skip the first word but I'd like it to match "vn" the same as sscanf does. Is this possible with stringstream or should I keep relying on sscanf for exact pattern matching ? Also I'm trying to translate sscanf(line, " %d/%d/%d", &i1, &i2, &i3); but I'm having a hard time which again orients me towards not using modern cpp for my file reader.
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::ios::skipws) { while (std::isspace(is.peek())) is.ignore(1); while (std::isspace((unsigned char)* s)) ++s; } while (*s && is.peek() == *s) { is.ignore(1); ++s; } if (*s) is.setstate(std::ios::failbit); return is; } In your case, you'd use it something like this: if (!(ss >> "vn" >> x >> y >> z)) break; As you can see from the code, it pays attention to the skipws state, so it'll skip leading white space if and only if you have skipws set. So if you need to match a pattern that includes a precise number of leading spaces, you want to turn skipws off, and include those spaces in your pattern.
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(int subIndex); glm::ivec4 position; glm::vec4 color; int halfSize; int sub; int leaf; }; In the shader it looks like this struct Node { vec4 position; vec4 color; int data[3]; }; layout(std430, binding=4) readonly buffer Octree_data { Node nodes[]; }; In the process of calculations, I find out that in all elements of the array (except for the first element) there are incorrect data (most likely displaced) in what could I make a mistake?
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 probably 4 bytes. This is because nothing in C++'s layout for your Node structure requires higher alignment. GLM's 4-element vector types are 4-byte aligned (or rather, they're float aligned, which is almost always 4 bytes). This means that the sizeof(Node) will be 44 bytes, as will the array stride. If you want your C++ struct to match the GLSL required layout, you need to align it properly: 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(int subIndex); alignas(16) glm::ivec4 position; alignas(16) glm::vec4 color; int halfSize; int sub; int leaf; };
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 } else { throw; } } that calls different functions depending on the template parameter given and returns a value which, at runtime, is guaranteed to have the same type as T. However, the compiler gives me this error: 'return': cannot convert from 'int' to 'T' I guess I could use something like reinterpret_cast, but this seems to be unsafe and bad practice in this scenario. So, is there a way to return different types from a template function depending on the template parameter in C++?
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 } else if constexpr (std::is_same<T, bool>::value) { return getBool(); // A library function returning a bool } else { throw; } }
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_PARAMS)lParam->rgrc[0] or (LPARAM)lParam no matter of the rest of NCCALCSIZE_PARAMS will be! Refs: https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-nccalcsize_params
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 application can use to calculate the new size and position of the client rectangle. If wParam is FALSE, lParam points to a RECT structure. On entry, the structure contains the proposed window rectangle for the window. On exit, the structure should contain the screen coordinates of the corresponding window client area. Since the 1st data member of NCCALCSIZE_PARAMS is a RECT[3] array: typedef struct tagNCCALCSIZE_PARAMS { RECT rgrc[3]; PWINDOWPOS lppos; } NCCALCSIZE_PARAMS, *LPNCCALCSIZE_PARAMS; Then logically, there will always be a RECT located at the memory address pointed at by the lParam, yes. But technically, under C++, what you are proposing is a Strict Alias Violation when wParam is TRUE, since the lParam will be pointing at a NCCALCSIZE_PARAMS, not a RECT. Per cppreference.com: Strict aliasing Given an object with effective type T1, using an lvalue expression (typically, dereferencing a pointer) of a different type T2 is undefined behavior, unless: T2 and T1 are compatible types. T2 is cvr-qualified version of a type that is compatible with T1. T2 is a signed or unsigned version of a type that is compatible with T1. T2 is an aggregate type or union type type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union). T2 is a character type (char, signed char, or unsigned char). Your proposal to access a NCCALCSIZE_PARAMS as if it were a RECT does not satisfy those requirements. But, since the Win32 API is primarily designed for C not C++, your proposal will likely "work" in most C++ compilers. But, to be on the safe side, you really should cast lParam to the correct type based on the value of wParam, eg: LPRECT pRect; if (wParam) { pRect = &(reinterpret_cast<NCCALCSIZE_PARAMS*>(lParam)->rgrc[0]); // or: // pRect = reinterpret_cast<NCCALCSIZE_PARAMS*>(lParam)->rgrc; } else { pRect = reinterpret_cast<LPRECT>(lParam); }
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[index]; }
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 does not provide access to the indexes of the elements being iterated through, so a separate i variable is being used to index into fCount, where i is initialized to index 0, and i++ increments the value of i by 1 on each loop iteration. For example: vector<int> list = {5, 10, 15, 20, ...}; int i = 0; vector<int> fCount(1001,0); for(auto index : list) { fCount[i] = index; i++; } This is effectively filling fCount like this: vector<int> fCount(1001,0); fCount[0] = 5; fCount[1] = 10; fCount[2] = 15; fCount[3] = 20; ... The second code is using each element of list as an index into fCount, using the ++ operator to increment the value of each indexed element of fCount. This is because ++fCount[index] is using the prefix increment operator, which has a lower precedence than vector::operator[], so ++fCount[index] is parsed as ++(fCount[index]), not as (++fCount)[index] (IOW, fCount is indexed into first, and then the increment is applied to what operator[] returns). And since fCount is initialized with 0s before the loop, after the loop finishes then every element that was indexed will have a value of exactly 1. For example: vector<int> list = {5, 10, 15, 20, ...}; vector<int> fCount(1001,0); for(auto index : list) { ++fCount[index]; } This is effectively filling fCount like this: vector<int> fCount(1001,0); fCount[5] += 1; fCount[10] += 1; fCount[15] += 1; fCount[20] += 1; ...
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 said memory?: void delArr(int **&numArr, int size) { for (int i = 0; i < size; ++i) { delete[] numArr[i]; } delete[] numArr; } Key note: Do I pass just a double pointer or a double pointer reference to the function for deleting? Thank you in advance
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 in the first place. In this case, std::vector<std::vector<int>> could be appropriate. Or, more efficient (probably; depends on how you intend to use it) alternative would be to use a single dimensional vector and translate the indices.
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; char c_string_buffer[] {"For example"}; list.push_back(c_string_buffer); // 1 list.emplace_back(c_string_buffer); // 2 list.push_back(std::move(std::string(c_string_buffer))); // 3 } I use ReSharper C++, and it complains about #1 (and suggests #2). When I read push_back vs emplace_back, it says that when it is not an rvalue, the container will store a "copied" copy, not a moved copy. Meaning, #2 does the same as #1. Don’t blindly prefer emplace_back to push_back also talks about that. Case 3: When I read What's wrong with moving?, it says that what std::move() does "is a cast to a rvalue reference, which may enable moving under some conditions". -- Does #3 actually give any benefit? I assume that the constructor of std::string is called and creates a std::string object with the content of the c_string. I am not sure if later the container constructs another std::string and copies the 1st object to the 2nd object.
// 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 element via copy or move construction from another object of the element type. If you write list.push_back(c_string_buffer); // 1, then because push_back expects a std::string&& argument (or const std::string&), a temporary object of type std::string will be constructed from c_string_buffer and passed-by-reference to push_back. push_back then constructs the new element from this temporary. With // 3 you are just making the temporary construction that would otherwise happen implicitly explicit. The second step above can be avoided completely by emplace_back. Instead of taking a reference to an object of the target type, it takes arbitrary arguments by-reference and then constructs the new element directly from the arguments. No temporary std::string is needed.
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/letto/OneDrive/Things/sonoio.jpg"; //Mat image = imread(filename); // Error Handling if (image.empty()) { cout << "Image File " << "Not Found" << endl; // wait for any key press cin.get(); return -1; } // Show Image inside a window with // the name provided imshow("Window Name", image); // Wait for any keystroke waitKey(0); return 0; } With the code above I'm trying to open an image. There are two ways I'm trying to do it: COMMAND LINE: I pass the image url as a command; EXPLICIT WAY: I write explicitly the image url. The second method works perfectly. With the first method I get this exception: Exception thrown at 0x00007FFAC1FFF551 (ucrtbased.dll) in OpenImg.exe: 0xC0000005: Access violation reading location 0x0000000000000000. I'm using Visual Studio Code 2022 so this is the way I'm passing the url through the command line: Where is the error? Help me find out please, thanks!
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 checking args would've showed that accessing argv[1] would've been out of bounds. Its a good habit to learn.)
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;" Which not violate the c++ syntax. In another case, if we added curly-bracket if (condition1){ statement1; } else if (condition2){ statement2; } Which equivalent to if (condition1){ statement1; } else { if (condition2){ statement2; } } Or, if we add more "else if" condition as following. if (condition1){ statement1; } else if (condition2){ statement2; } else if (condition3){ statement3; } else{ statement4; } We got if (condition1){ statement1; } else { if (condition2){ statement2; } else { if (condition3){ statement3; } else{ statement4; } } }
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 hide it from descendants? How can I do that?
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" #include "B.h" int main() { B obj_00; A obj_01(obj_00); return 0; } B.h: #include <iostream> #ifndef _B_H_ #define _B_H_ class B { private: public: B(); ~B(); }; B::B(){//some code}; B::~B(){//some code}; #endif //_B_H_ A.h: #ifndef _A_H_ #define _A_H_ class A { private: public: A(); A(class B &temp); A(class A &temp); ~A(); }; #endif //_A_H_ A.cpp #include <iostream> #include "A.h" #include "B.h" A::A(A &temp){//some code}; A::A(B &temp){//some code}; A::~A(){//some code}; Error: C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::B()': E:/Personal/Programming/VSCode/test/B.h:13: multiple definition of `B::B()' C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:13: first defined here C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::B()': E:/Personal/Programming/VSCode/test/B.h:13: multiple definition of `B::B()' C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:13: first defined here C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::~B()': E:/Personal/Programming/VSCode/test/B.h:18: multiple definition of `B::~B()' C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:18: first defined here C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::~B()': E:/Personal/Programming/VSCode/test/B.h:18: multiple definition of `B::~B()' C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:18: first defined here collect2.exe: error: ld returned 1 exit status
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 automatically inlined, avoiding this issue. Since you have it out of the class you need to tell the compiler and the linker that you intended this using the inline keyword: inline B::B(){//some code}; inline B::~B(){//some code}; Read more about the inline keyword here.
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 elapsed_time function and make use of a function pointer, pointing to the function that has been passed as an argument of the elapsed_time function, and thus compute its elapsed running time. I am not sure if my code is even close to be correct, but I did my best as a newbie in programming, as follows: MWE: #include <iostream> #include <chrono> template<class return_type, class ... argument_types> void elapsed_time(return_type func(argument_types ... args)){ return_type (* func_ptr)(argument_types ... args) = & func; 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(); /* Put the Function whose elapsed time matter right HERE */ func_ptr(); /// What to pass here? /* Put the Function whose elapsed time matter right HERE */ end_ = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed_time (end_ - start_); const double seconds(elapsed_time.count()); cout << "\nRuntime: " << seconds << " s\n\n"; } and now lest consider I have a function to be passed to elapsed_time function, as follows: vector<Point_CCS_xy> fun(const vector<Point_CCS_xy> point_vec, const Point_CCS_xy inquiry_pnt, const int sz); where Point_CCS_xy is a class of cartesian coordinates (x,y), i.e., struct Point_CCS_xy { long double x_coordinate; long double y_coordinate; }; My questions: Is the function I have written correct? what should I pass to func_ptr() as commented in the body of the elapsed_time function? Passing argument_types ... args leads to the error: 'argument_types' does not refer to a value In the main(), how to pass vector<Point_CCS_xy> fun(const vector<Point_CCS_xy> point_vec, const Point_CCS_xy inquiry_pnt, const int sz); function to the elapsed_time function? In advance, I appreciate that you share your thoughts and comments.
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(); std::invoke(f, std::forward<Args>(args)...); end_ = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed_time (end_ - start_); const double seconds(elapsed_time.count()); cout << "\nRuntime: " << seconds << " s\n\n"; } In the above I make the entire function type a single template parameter. This has the advantage of allowing you to pass any type of callable object, not just function pointers. I then use std::invoke to actually call the passed in object as it is design to handle invoke any callable with the provided arguments. So for your fun function, you would pass it to this version of the elapsed_time like elapsed_time(fun, point_vec, inquiry_pnt, sz); If the callable you are passing happens to be an overloaded function, then you would just need to wrap that call in a lambda expression like elapsed_time([&](){ fun(point_vec, inquiry_pnt, sz); });
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> void MyList<T>::addInMiddle(const T& x) { list<T>::iterator it = this->begin(); int location = (this->size()) / 2; //where we want to insert the new element for (int i = 0; i < location; i++) { it++; } this->insert(it,x); } int main() { MyList<int> list1; list1.push_back(1); list1.push_back(2); list1.push_back(3); list1.push_back(4); list1.addInMiddle(5); list1.printList(); return 0; } The program compiles and shows 1,2,3,4. It should actually show 1,2,5,3,4. I don't think the iterator is working. Any thoughts?
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, you can (and should) just use auto instead: auto it = this->begin(); Online Demo That being said, standard C++ containers are not intended to be inherited from (no virtual destructor, etc). You should use encapsulation instead of inheritance, eg: template<class T> class MyList { private: list<T> m_list; public: void addToBack(const T&); void addInMiddle(const T&); void insertInSortedOrder(const T&); void printList(); }; template<class T> void MyList<T>::addToBack(const T& x) { m_list.push_back(x); } template<class T> void MyList<T>::addInMiddle(const T& x) { list<T>::iterator it = m_list.begin(); // or: auto it = m_list.begin(); int location = m_list.size() / 2; //where we want to insert the new element for (int i = 0; i < location; i++) { it++; } m_list.insert(it, x); } int main() { MyList<int> list1; list1.addToBack(1); list1.addToBack(2); list1.addToBack(3); list1.addToBack(4); list1.addInMiddle(5); list1.printList(); return 0; } Online Demo
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 - 1; while (lower <= upper) { int mid = lower + (upper - lower) / 2; int res; if (x == (arr[mid])) res = 0; if (res == 0) return mid; if (x > (arr[mid])) lower = mid + 1; else upper = mid - 1; } return -1; }
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; int upper = n - 1; while (lower <= upper) { int mid = lower + (upper - lower) / 2; int res = -2; if (x == (arr[mid])) res = 0; if (res == 0) return mid; if (x > (arr[mid])) lower = mid + 1; else upper = mid - 1; } return -1; } Calling it with binarySearchString(words, "bbb", 3); returns -1. int main() { vector<string> words; words.push_back("aah"); words.push_back("aal"); words.push_back("aas"); int retVal = binarySearchString(words, "bbb", 3); std::cout << "Returned: " << retVal << std::endl; system("pause"); return 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 the body of that if statement? int statistician::length() const { return count; } Code (test3() call in int main()): statistician s, t, u, v; if (s.length( ) || t.length( )) return 0; // <-- HERE if (s.sum( ) || t.sum( )) return 0; t.next(5); u.next(0); u.next(10); u.next(10); u.next(20); v = s + s; if (v.length( ) || v.sum( )) return 0; v = s + u; if (!(u == v)) return 0; v = t + s;
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 probably missed this, but you probably // want to know if the string is greater than 0, not "2 or more" for the way you have probably implemented it. However! int can also be negative, and negative values are still not 0, and therefore also will be true. So if your function was something like this: int length() { if (some condition) { return -1; // error code } return count; } Then your if statements are suddenly not equivalent. So, ... best thing to do if this is not the case, is to represent your data as you intend it. AKA, if your count value can't be negative, then do not allow it to be. Use an unsigned int, or size_t: size_t length();
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 reference to the AND function with Gate_Func but why output = Gate_Func(InputArr); this one has an error: C++ expression preceding parentheses of apparent call must have (pointer-to-) function type #include <iostream> #include <vector> using namespace std; class TestClass { public: int AND(vector<int> inputarr) { return (inputarr[0] == 1 && inputarr[1] == 1); } int OR(vector<int> inputarr) { return (inputarr[0] == 1 || inputarr[1] == 1); } int NOT(vector<int> inputarr) { if (inputarr[0] != 0) return 0; else return 1; } int (TestClass::* Gate_Func)(vector<int>); TestClass(int ChooseFunction, vector<int> inputarr) { InputArr = inputarr; switch (ChooseFunction) { case 1: Gate_Func = &TestClass::AND; break; case 2: Gate_Func = &TestClass::OR; break; case 3: Gate_Func = &TestClass::NOT; break; default: break; } } void calculation() { output = Gate_Func(InputArr); //C++ expression preceding parentheses of apparent call must have (pointer-to-) function type } vector<int> InputArr; int output = 2; void printOutput() { cout << output << endl; } }; int main() { vector<int> input = { 1, 1 }; TestClass obj(1, input); obj.printOutput(); } Oh! I see, thank you guys, so when I use 'this', it's basically like calling the object of the Class and I have to call the function from that object! Here is the code: #include <iostream> #include <vector> using namespace std; class TestClass { public: int AND(vector<int> inputarr) { return (inputarr[0] == 1 && inputarr[1] == 1); } int OR(vector<int> inputarr) { return (inputarr[0] == 1 || inputarr[1] == 1); } int NOT(vector<int> inputarr) { if (inputarr[0] != 0) return 0; else return 1; } int (TestClass::* Gate_Func)(vector<int>); TestClass(int ChooseFunction, vector<int> inputarr) { InputArr = inputarr; switch (ChooseFunction) { case 1: Gate_Func = &TestClass::AND; break; case 2: Gate_Func = &TestClass::OR; break; case 3: Gate_Func = &TestClass::NOT; break; default: break; } calculation(); } void calculation() { output = (this->*Gate_Func)(InputArr); //C++ expression preceding parentheses of apparent call must have (pointer-to-) function type } vector<int> InputArr; int output = 2; void printOutput() { cout << output << endl; } }; int main() { vector<int> input = { 1, 1 }; TestClass obj(1, input); obj.printOutput(); }
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 (just as you would have to do in order to call AND, OR, or NOT directly). You also need to supply the arguments to the function. This is done using a special syntax: (p->*Gate_Func)(InputArr); Here, p is a pointer to the instance on which to invoke the function, and InputArr is the argument. If there are multiple arguments, they are separated by commas just like in an ordinary function call. If you can't remember this syntax, you can also do std::invoke(Gate_Func, p, InputArr). (The instance pointer p goes before all the arguments.) In your case, I suspect you want to invoke the function on the current instance. You can do this by using this (e.g., (this->*Gate_Func)(InputArr)).
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 caseInsensitiveCompare { bool operator() (const std::string& a, const std::string& b) const { return (copyToUpper(a).compare(copyToUpper(b)) < 0); } }; std::set<std::string, caseInsensitiveCompare> keys;
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 map, a set or a sort function.
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 —---- After about 5 minutes, it becomes 1>----— Build started: Project: MyConsoleApp, Configuration: Release x64 —---- 1>A task was canceled. 1>A task was canceled. ========= Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== All my cpp projects have the same problem now. My time zone is correct. I have tried to reopen VS, restart my computer and reinstall Visual Studio, but this problem still exists.
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 uninstalling the anti-virus software installed on your computer, which may solve the problem
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 number int count = 0;//for checking if the current line contains more than 1 integer if(inputFile) { //go line by line while(std::getline(inputFile, line)) { std::istringstream ss(line); //go int by int while(ss >> num) { ++count; //check if count is greater than 1 meaning we are checking if line contains more than 1 integers and if yes then print out the line and break if (count > 1) { std::cout<<line <<std::endl; break; } } //reset count and num for next line count = 0; num = 0; } } else { std::cout<<"input file cannot be opened"<<std::endl; } return 0; } Demo.
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 == false) ++ret.first->second; ++file_iter; }
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 encountered. Once that happens, the stream is in error or eof state, the reads are done, and the vector is finished being populated. Then, back to your next line of code: while (file_iter != eof) Remember, that's still the original file_iter before a copy of it was used to run the stream to eof. The initial prime of that iterator is still intact, but as soon as you advance it (++file_iter) the stream is discovered to be at eof, the iterator is set as such, and now the while-condition will compare as false. If you want to load your vector and build the frequency map, use an iterator over the vector for the latter, or better still, a ranged-for loop: istream_iterator<string> file_iter(in), eof; map<string, size_t> word_cout; vector<string> vec(file_iter, eof); for (auto const& s : vec) ++word_count[s]; Now vec contains every word in your file, and your map contains the frequencies of said-same.
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 class has their own kind of storage: struct DerivedStorage : Storage{ int derivedData; } In the derived class, class Derived{ protected: virtual void createStorage() override{ delete storage; _storage = new DerivedStorage(); } } Hence _storage can be used for all the base class members and the derived class members. The downside is, because for each derived class, I would have to cast the type of storage to DerivedStorage, or whatever type of storage the derived class uses, it is very tedious to type out the cast statement each time. Is there an elegant way around it ? My solution is to just have one more variable of type DerivedStorage, and just use that in the derived classes member functions. Eg: class Derived{ protected: DerivedStorage* _ds = nullptr; virtual void createStorage() override{ delete storage; _storage = new DerivedStorage(); _ds = _storage; // Use _ds in all member functions of Derived instead of _storage } void exampleUseOfDerivedStorage(){ _ds->derivedData++; //some complex calculation } } Is there a more elegant pattern to use for this use case?
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> #include<iostream> #include<vector> #include<algorithm> struct Storage{ int baseData{}; }; struct DerivedStorage{ int derivedData{}; }; class Base{ public: Storage _storage; void exampleUseOfBaseStorage(){ _storage.baseData++; //some complex calculation } }; class Derived: Base{ public: DerivedStorage _ds; void exampleUseOfDerivedStorage(){ _ds.derivedData++; //some complex calculation std::cout << "baseData: " << _storage.baseData << std::endl; std::cout << "derivedData: " << _ds.derivedData << std::endl; } }; int main(){ Derived d; d.exampleUseOfDerivedStorage(); return 0; } Example for CRTP Here's the example to elaborate on user17732522's answer about CRTP usage. Live Demo I changed all member to public since the example doesn't elaborate on when to call createStorage() #include<string> #include<iostream> #include<vector> #include<algorithm> struct Storage{ int baseData{}; }; struct DerivedStorage : Storage{ int derivedData{}; }; template<typename DS> class Base{ public: Storage* _storage; virtual void createStorage(){ delete _storage; _storage = new Storage(); } DS* getStorage(){ return static_cast<DS*>(_storage); } void exampleUseOfBaseStorage(){ _storage->baseData++; //some complex calculation } }; class Derived: Base<DerivedStorage>{ public: virtual void createStorage() override{ delete _storage; _storage = new DerivedStorage(); } void exampleUseOfDerivedStorage(){ getStorage()->derivedData++; //some complex calculation std::cout << "derivedData: " << getStorage()->derivedData << std::endl; } }; int main(){ Derived d; d.createStorage(); d.exampleUseOfDerivedStorage(); return 0; }
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, including the functions for allocating and freeing memory and system resources such as fonts, colormaps etc. In my code I use objects' constructors and destructors to allocate and free resources by calling these functions. And here is the problem: int main() { ::Display* const display = ::XOpenDisplay(nullptr); // ... Object1 object1(display, ...); // uses display inside the destructor Object2 object2(display, ...); // uses display inside the destructor Object3 object3(display, ...); // uses display inside the destructor // ... ::XCloseDisplay(display); // invalidates the display structure return 0; } This example leads to segmentation fault, because the display structure had been invalidated by XCloseDisplay() before any of the destructors using it was called. To avoid this issue I can embrace all the code before XCloseDisplay() in curly braces to limit the scope of objects, but it makes the code to be shifted to right which looks pretty ugly. Is there any way to somehow call XCloseDisplay() after the main()?
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 of a global or function-local static object. A function-local static is better than a global variable because it avoids the static init order fiasco.
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 saying If you allocate/obtain some storage using certain operations (such as defining char/byte array, malloc, operator new, ...), you can treat and use the storage itself as implicit-lifetime types without explicit object creation because the implicit types you want would be created implicitly. If my thought is correct, doesn't the above code now violate strict-aliasing rule? In the above code, Is a float array object created implicitly? (If not, #1 is UB because I tried pointer arithmetic on the storage which is not array) (If you can't understand what i'm saying, tell me plz.. I'm not good at English..)
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 pointers (for copy problems) and virtual functions (for optimization reasons) template <typename T> struct A {T _value; void foo(){cout<<_value;}}; A<int> a_1{1}; A<float> a_2{2.0f}; ... void foo_all(){ a_1.foo(); a_2.foo(); ... } // for (auto i :{a_1,a_2, ...}) is not possible // array<A<T>,10>; is not also possible, if T is variable Is some sort of design pattern/ idiom known for this use case Is it planned to have an iteratable container for concepts some when in the future?
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*/ { tuple(T&& first): m_first(first){}; T m_first; }; template<class functor,typename... Tn> void apply(functor&& fcn, tuple<Tn...>& t) { fcn(t.m_first); if constexpr(sizeof...(Tn)>1) apply(std::forward<functor>(fcn), t.m_rest); }; and calling apply([](auto& x){x.foo();},tuple{A<int>{1},A<float>{2.0f}}); Another solution is having an std::variant and a visitor function using var = std::variant<A<int>,A<float>>; std::array<var ,2> arr {A<int>{1},A<float>{2.0f}}; std::visit([](auto& x){x.foo();}, arr);
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 objects between Java and C++. The final issue is presented at the end of this pos. First, I present the implementation. public class ExampleJNI { static { System.loadLibrary("nativeObject"); } public static void main(String[] args){ ExampleJNI tmp = new ExampleJNI(); Order o = tmp.createOrder(1,2,3,4); if (o != null){ System.out.println(o.toString()); } else { System.out.println("Errors present"); } } // Try passing a list public native Order createOrder(int a, int b, int c, int d); } The order class is defined to be: public class Order { // Order attributes public final int a; public final int b; public final int c; public final int d; private int e; public Order(int a, int b, int c, int d){ this.a = a; this.b = b; this.c = c; this.d = d; } @Override public String toString(){ return a+","+b+","+c+","+d; } } I have the following implementation in C++. #include "ExampleJNI.h" #include <iostream> #include <vector> /* * Class: ExampleJNI * Method: createOrder * Signature: (IIII)LOrder; */ JNIEXPORT jobject JNICALL Java_ExampleJNI_createOrder(JNIEnv* env, jobject thisObject, jint a, jint b, jint c, jint d){ // Get a class reference for Order jclass cls = env->GetObjectClass(thisObject); if (cls == NULL){ std::cout << "Class not found" << std::endl; return NULL; } // Get the method ID of the constructor whick takes four integers as input jmethodID cid = env->GetMethodID(cls, "<init>", "(IIII)V"); if (cid == NULL){ std::cout << "Method not found" << std::endl; return NULL; } return env->NewObject(cls, cid, a, b, c, d); } When I run the code, "Method not found" is printed, which indicates that something is going wrong when calling the GetMethodID. I also retrieve the following exception error: Exception in thread "main" java.lang.NoSuchMethodError: <init> at ExampleJNI.createOrder(Native Method) at ExampleJNI.main(ExampleJNI.java:11) Any suggestions on what I should have instead of the <init> are highly appreciated!
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) { std::cout << "bar " << i << std::endl; } // mechanism to identify them enum function_kind { foo_kind, bar_kind }; std::map<function_kind, std::function<void( int)>> kind_to_function{{foo_kind, foo}, {bar_kind, bar}}; // wrapper around jthread // (additional functionality ommitted for brevity) template<typename Callable, typename... Args> class MyThread { public: explicit MyThread(Callable &&function, Args &&...args) : m_thread{ std::forward<Callable>(function), std::forward<Args>(args)...} {} private: std::jthread m_thread; }; int main() { std::jthread t1(kind_to_function[foo_kind], 3); // works MyThread t2(kind_to_function[foo_kind], 3); // complains return 0; } I am really just trying to mimic whatever std::jthread is doing with my own class. The IDE (clion) complains, that the first argument to t2 is not an rvalue. The compiler complains a little more complicated: main.cpp: In function ‘int main()’: main.cpp:29:46: error: class template argument deduction failed: 29 | MyThread t2(kind_to_function[foo_kind], 3); // complains | ^ main.cpp:29:46: error: no matching function for call to ‘MyThread(std::map<function_kind, std::function<void(int)> >::mapped_type&, int)’ main.cpp:20:14: note: candidate: ‘MyThread(Callable&&, Args&& ...)-> MyThread<Callable, Args> [with Callable = std::function<void(int)>; Args = {int}]’ (near match) 20 | explicit MyThread(Callable &&function, Args &&...args) : m_thread{std::forward<Callable>(function), | ^~~~~~~~ main.cpp:20:14: note: conversion of argument 1 would be ill-formed: main.cpp:29:46: error: cannot bind rvalue reference of type ‘std::function<void(int)>&&’ to lvalue of type ‘std::map<function_kind, std::function<void(int)> >::mapped_type’ {aka ‘std::function<void(int)>’} 29 | MyThread t2(kind_to_function[foo_kind], 3); // complains | ^ main.cpp:18:7: note: candidate: ‘template<class Callable, class ... Args> MyThread(MyThread<Callable, Args>)-> MyThread<Callable, Args>’ 18 | class MyThread { | ^~~~~~~~ main.cpp:18:7: note: template argument deduction/substitution failed: main.cpp:29:46: note: ‘std::function<void(int)>’ is not derived from ‘MyThread<Callable, Args>’ 29 | MyThread t2(kind_to_function[foo_kind], 3); // complains | ^ In any case, the arguments work for std::jthread, which also just takes rvalues... So what am I missing?
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 template, and its constructor is not a template constructor, the behavior is not the same. After instantiation, it's a regular constructor that accepts only rvalues. Forwarding references are contingent on template argument deduction happening for the function template they are a part of. So a non-template constructor means no forwarding references. Okay, but you didn't specify template arguments to MyThread, why was there seemingly no error? Because class template argument deduction allows you to omit those. And CTAD happens in its own overload resolution step, completely disjoint from actually choosing a constructor to initialize the object. One step can be ill-formed while the other is not.
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::vector<struct A *> vec; //library_function(struct A **array); library_function(vec.data()); Of course, if I change the elements in the vector then the pointer returned by data() will be invalidated, but that is not an issue here (I can call the function again when updating the vector). I am just afraid this might be undefined behavior, since I can't see anywhere mentioned that data() is terminated by a null pointer and not by random garbage. The standard does say : const T* data() const noexcept; Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range So there is a terminating element, but it doesn't say if that element is initialized and if it is, with what value. Is it specified somewhere else that I missed? Or do I have to allocate a raw array and null terminate it myself?
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 null, then you must insert the null element. Example: std::vector<A> vec_of_struct(size); std::vector<A*> vec_of_ptrs; vec_of_ptrs.reserve(size + 1); std::ranges::copy( std::views::transform( vec_of_struct, [](A& a) { return &a; } ), std::back_inserter(vec_of_ptrs) ); vec_of_ptrs.push_back(nullptr); // null terminator pointer library_function(vec_of_ptrs.data()); // C function
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 you agree/disagree. Note: below code is an example of an NxN array. My question is in general for NxN array and not specific to the following code. #include <iostream> int M[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; int x = 20; bool searchM(){ for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(M[i][j]==x) { return true; } } } return false; } int main() { std::cout << searchM(); }
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++) { if (M[i][j] == x) { return true; } } } return false; } int main() { std::cout << searchM(3, 20) << std::endl; } Since the input size is N, it would be correct to say that the worst-case complexity of this algorithm is O(N2).
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<typename T> T func() { int x = 4; std::cout<<"x: "<<x<<std::endl; throw; } int main() { func<double>(); } Example 2 #include <iostream> //this function does not have a return statement int func() { int x = 4; std::cout<<"x: "<<x<<std::endl; throw; } int main() { func(); } My question is that are example 1 and example 2 valid? Or we have UB/ill-formed.
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 x;} valid It's valid. But it never returns a value. Everything after the throw is dead code.
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 because it points at a temporary instance which was destroyed. I'm new to C++ and don't have access to any books to teach me at the moment, hence I'm not entirely sure what a "dangling" pointer is or what it means, but I'm fairly certain it's the reason I can't display any text on my nodes. Here's my Node class: class Node { private: int x; int y; int value; int radius; public: Vector2 get_pos() { return Vector2{ (float)x, (float)-value * 25 }; } void set_radius(int newRadius) { radius = newRadius; } void set_value(int newValue) { value = newValue; } void set_x(int newX) { x = newX; } void set_y(int newY) { y = newY; } void draw() { if (value) { const char* text = std::to_string(value).c_str(); Vector2 size = MeasureTextEx(GetFontDefault(), text, 32.0f, 0.0f); Vector2 pos = get_pos(); DrawCircle(pos.x, pos.y, radius, WHITE); DrawText(text, pos.x - size.x / 2, pos.y - size.y / 2, 32, BLACK); } } }; Any help or explanation as to what's going on would be appreciated. EDIT: Other people have had similar issues on other questions but none of the answers made sense to me or felt applicable to my situation.
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 DrawText copies the string (rather than just copying the pointer you pass) you can fix it via std::string text = std::to_string(value); Vector2 size = MeasureTextEx(GetFontDefault(), text, 32.0f, 0.0f); Vector2 pos = get_pos(); DrawCircle(pos.x, pos.y, radius, WHITE); DrawText(text.c_str(), pos.x - size.x / 2, pos.y - size.y / 2, 32, BLACK);
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 the raw email text sent. The corresponding header (subject in this case) is: Subject: =?UTF-8?B?15TXldeT16LXlCDXotecINeQ15kg15TXoteR16jXqiDXqtep15zXlQ==?= =?UTF-8?B?150g16rXp9eV16TXqteZINeR16rXm9eg15nXqiDXnNep15vXmdeo15nXnQ==?= The encoding mentioned in the comments, is only for the content (body). Headers should be in ASCII only, but some email client do send some kind of 8bit encoding (ISO-8859-?). This is not the case for the message I describe. I assume there is something else I am missing - where can I find documentation about this subject? I am looking for solutions in C or C++ (the utf7 library I am using is C, and the mime parsing library is in C++). C++ is always a better alternative.
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 an utf-8 encoded string.
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 a function? What should it look like? I first considered the old-school FILE*: FILE *open_for_read(const char *filename) { if (strcmp(filename, "-") == 0) { return stdin; } else { auto fp = fopen(filename, "r"); if (fp == NULL) { throw runtime_error(filename); } return fp; } } It works, and it's safe to fclose(stdin) later on (in case one doesn't forget to), but then I would lose access to the stream methods such as std::getline. So I figure, the modern C++ way would be to use smart pointers with streams. At first, I tried unique_ptr<istream> open_for_read(const string& filename); This works for ifstream but not for cin, because you can't delete cin. So I have to supply a custom deleter (that does nothing) for the cin case. But suddenly, it fails to compile, because apparently, when supplied a custom deleter, the unique_ptr becomes a different type. Eventually, after many tweaks and searches on StackOverflow, this is the best I can come up with: unique_ptr<istream, void (*)(istream *)> open_for_read(const string &filename) { if (filename == "-") { return {static_cast<istream *>(&cin), [](istream *) {}}; } else { unique_ptr<istream, void (*)(istream *)> pifs{new ifstream(filename), [](istream *is) { delete static_cast<ifstream *>(is); }}; if (!pifs->good()) { throw runtime_error(filename); } return pifs; } } It is type-safe and memory-safe (or at least I believe so; do correct me if I'm wrong), but this looks kind of ugly and boilerplate, and above all, it is such a headache to just get it to compile. Am I doing it wrong and missing something here? There's gotta be a better way.
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(!is) { /* error */ } while(std::getline(is, line)) { // ... } ifs will, if it was opened, be closed when it goes out of scope as usual. A throwing version might look like this: std::istream& open_for_read(std::ifstream& ifs, const std::string& filename) { if(filename == "-") return std::cin; ifs.open(filename); if(!ifs) throw std::runtime_error(filename + ": " + std::strerror(errno)); return ifs; }
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 <math.h> #include <iostream> #include <chrono> using namespace std; using namespace std::chrono; #define CHECK_RANGE 100 inline float msqrt(float a) { int i; for (i = 0;i * i <= a;i++); float lb = i - 1; //lower bound if (lb * lb == a) return lb; float ub = lb + 1; // upper bound float pub = ub; // previous upper bound for (int j = 0;j <= 20;j++) { float ub2 = ub * ub; if (ub2 > a) { pub = ub; ub = (lb + ub) / 2; // mid value of lower and upper bound } else { lb = ub; ub = pub; } } return ub; } void check_msqrt() { for (size_t i = 0; i < CHECK_RANGE; i++) { msqrt(i); } } void check_sqrt() { for (size_t i = 0; i < CHECK_RANGE; i++) { sqrt(i); } } int main() { auto start1 = high_resolution_clock::now(); check_msqrt(); auto stop1 = high_resolution_clock::now(); auto duration1 = duration_cast<microseconds>(stop1 - start1); cout << "Time for check_msqrt = " << duration1.count() << " micro secs\n"; auto start2 = high_resolution_clock::now(); check_sqrt(); auto stop2 = high_resolution_clock::now(); auto duration2 = duration_cast<microseconds>(stop2 - start2); cout << "Time for check_sqrt = " << duration2.count() << " micro secs"; //cout << msqrt(3); return 0; } output of above code showing the implemented method 4 times more slow than sqrt of math.h file. I need faster than math.h version.
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 the standard library function would require a special case, such as: Availability of a suitable assembler instruction - or other specialized hardware support - on the particular system for which the standard library has not been specialized. Knowledge of the needed range or precision. The standard library function must handle all cases specified by the standard. If the application only needs a subset of that or maybe only requires an approximate result then perhaps an optimization is possible. Making a mathematical reduction of the calculations or combine some calculation steps in a smart way so an efficient implementation can be made for that combination.
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 head recursion void removeX(char input[]) { if (input[0] == '\0') return; removeX(input+1); if (input[0] == 'x') { strcpy(input, input+1); removeX(input); } } One with tail recursion void removeX(char input[]) { if (input[0] == '\0') return; if (input[0] == 'x') { strcpy(input, input+1); removeX(input); } removeX(input+1); } P.S. The program is supposed to remove all character 'x' from the input string. Example test cases: input -----------------> output xxxxxss ----------------> ss aaaxxx ----------------> aaa Now these are simple test cases in which both the solutions with head and tail recurison gives correct answers. But, there are some test cases for which tail recursion fails and I am trying to figure out in what are those cases and why does it fail.
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 redundant or incorrect if the last character in the string is an x. Here is a modified version with tail recursion: void removeX(char *input) { if (input[0] == '\0') return; if (input[0] == 'x') { memmove(input, input + 1, strlen(input + 1) + 1); removeX(input); } else { removeX(input + 1); } } Using recursion for this type of problem is not idiomatic in C. A simple loop is preferred, with linear time complexity instead of potential quadratic time for strings with long sequences of x: void removeX(char *input) { char *p = input; while ((*p = *input++) != '\0') { if (*p != 'x') p++; } }
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' \ -DCUDNN_LIBRARY='/${CONDA_PREFIX}/lib' \ -DC_INCLUDE_PATH=${CONDA_PREFIX}/include:/usr/local/include:/usr/include/x86_64-linux-gnu: \ -DINCLUDE_PATH=${CONDA_PREFIX}/include:/usr/local/include:/usr/include/x86_64-linux-gnu \ -DC_PATH=${CONDA_PREFIX}/include:/usr/local/include:/usr/include/x86_64-linux-gnu \ -DLD_LIBARY_PATH=${CONDA_PREFIX}/lib:/usr/lib/x86_64-linux-gnu \ Indeed, CMake is able to find the libraries it needs, like CUDA, CuDNN, OpenBlas, FFMpeg, etc. Everything seems to go well for a while. At the linking stage, however, CMake keeps attaching a weird library reference "-llib". lib is a non-existent library, of course. For example, one such command is cd /home/albert/app/src/opencv/build/modules/cudev && /usr/bin/cmake -E cmake_link_script CMakeFiles/opencv_cudev.dir/link.txt --verbose=1 /usr/bin/c++ -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Winit-self -Wpointer-arith -Wsign-promo -Wuninitialized -Winit-self -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -Wno-undef -Wno-missing-declarations -Wno-unused-function -Wno-unused-variable -Wno-enum-compare -Wno-shadow -O3 -DNDEBUG -DNDEBUG -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -Wl,--gc-sections -Wl,--as-needed -shared -Wl,-soname,libopencv_cudev.so.4.4 -o ../../lib/libopencv_cudev.so.4.4.0 CMakeFiles/opencv_cudev.dir/src/stub.cpp.o -L/usr/local/cuda/lib64 -L/home/albert/.conda/envs/denseflow -Wl,-rpath,/usr/local/cuda/lib64:/home/albert/.conda/envs/denseflow::::::::::::::::::::::: -ldl -lm -lpthread -lrt ../../3rdparty/lib/libippiw.a ../../3rdparty/ippicv/ippicv_lnx/icv/lib/intel64/libippicv.a -lcudart_static -lpthread -ldl -lrt -lnppc -lnppial -lnppicc -lnppidei -lnppif -lnppig -lnppim -lnppist -lnppisu -lnppitc -lnpps -lcublas -llib -lcufft -L/usr/local/cuda/lib64 -L/usr/lib/x86_64-linux-gnu -L/home/albert/.conda/envs/denseflow -lcudart_static -lpthread -ldl -lrt -lnppc -lnppial -lnppicc -lnppidei -lnppif -lnppig -lnppim -lnppist -lnppisu -lnppitc -lnpps -lm -lpthread -lcublas -llib -lcufft This causes the following error. /usr/bin/ld: cannot find -llib collect2: error: ld returned 1 exit status make[2]: *** [modules/cudev/CMakeFiles/opencv_cudev.dir/build.make:89: lib/libopencv_cudev.so.4.4.0] Error 1 If I manually remove the "-llib" (both occurrences) from the C++ command, the command executes successfully. What is happening here? Although I'm unfamiliar with CMake, it feels like there should be a straightforward way to prevent CMake from doing this. Thank you so much for your help. Update: There does seem to be something wrong with the OpenCV CMake files. When I run CMake, one of its output is -- Extra dependencies: dl m pthread rt cudart nppc nppial nppicc nppidei nppif nppig nppim nppist nppisu nppitc npps cublas lib cufft -L/usr/local/cuda-11.6/lib64 -L/home/albert/.conda/envs/denseflow The mysterious lib already appears here. Someone on the Internet suggests modifying CMakeCache.txt manually, but I wasn't able to get it to work. CMake just overwrites it after my modifications.
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 A { public: int b = 1000; ~B() { std::cout << "Release B" << std::endl; } void printer() override { std::cout << "B's printer" << std::endl; } B() { std::shared_ptr<A> tmp(this); arr.push_back(tmp); (*arr.begin())->printer(); std::cout << "inside B's c'tor test B counts: " << tmp.use_count() << std::endl; } }; int main(int argc, char const *argv[]) { std::shared_ptr<B> B_ptr = std::make_shared<B>(); std::shared_ptr<A> A_ptr(B_ptr); std::cout << "list address: " << (*arr.begin()).get() << std::endl; std::cout << "test B address: " << B_ptr.get() << std::endl; std::cout << "test A address: " << A_ptr.get() << std::endl; std::cout << "list counts: " << (*arr.begin()).use_count() << std::endl; std::cout << "test B counts: " << B_ptr.use_count() << std::endl; std::cout << "test A counts: " << A_ptr.use_count() << std::endl; return 0; } My expectation is: A's reference count should be three, but only got 2. I think when I push_back to the list, there should be a temporarily created share_ptr object, even it is get destroyed, the one in list should also pointing to the same address as A_ptr and B_ptr. It turns out that they (those three), did pointing at the same address, but use_count got different results. (*arr.begin()).use_count() is 1, the others are both 2. Why? Please help. Ps: I know turning this pointer to share_ptr is stupid operation, but the result doesn't make sense and even disobey the syntax.
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 was already owned by another shared pointer, the behaviour of the program will be undefined when the two separate owners attempt to destroy it. Creating a shared pointer from this is possible using std::enable_shared_from_this, but it's not simple.
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. Unfortunately I am getting same output. double my_exp(double x) { bool minus = x < 0; x = abs(x); double exp = (double)1 + x; double temp = x; for (int i = 2; i < 100000; i++) { temp *= x / (double)i; exp = exp + temp; } return minus ? exp : (double)1 / exp; } I found that issue is when such small numbers like 1.00000000000000000003e-030 doesn't work well when we try to subtract it, neither both if we subtracting or adding such a small number the result always is equal to 1. Have U any idea how to manage with this?
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.00000000000000000000000000000100000000000000000003) = " << std::expm1(-0.00000000000000000000000000000100000000000000000003) << '\n'; } Run the example in the below source by changing the arguments to your very small numbers. Source: https://en.cppreference.com/w/cpp/numeric/math/expm1
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 test the numeration of the test is in two parts : [ <number of this test> / <total number of tests> ] If I add a test or remove one, I don't have to hard-written the <number of this test>, because it's an int that increment itself each time. But, I have to count the <total number of test> and write it down manually (for example, in a macro, but that could be a variable as well). here is how the code looks like : #include <iostream> #define N_TEST "2" int main() { int i = 0; std::cout << "\n[" << ++i << "/" N_TEST "] test something :\n"; { // some tests here } std::cout << "\n[" << ++i << "/" N_TEST "] test another thing :\n"; { // some different tests here } return 0; } Is there a way to fill the <total number of tests> automatically ?
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> int main(int argc, char *argv[]) { std::vector<std::function<void()>> tests; tests.push_back( [](){ std::cout << "hello test\n"; } ); tests.push_back( [](){ std::cout << "hello another test.\n"; } ); int counter = 0; for (const auto& test : tests){ std::cout << ++counter << "/" << tests.size() << " "; test(); } } Output: 1/2 hello test 2/2 hello another test.
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 way of achieving this.
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 documented by the package itself. The QUIET option disables informational messages, including those indicating that the package cannot be found if it is not REQUIRED. The REQUIRED option stops processing with an error message if the package cannot be found. A package-specific list of required components may be listed after the COMPONENTS keyword. If any of these components are not able to be satisfied, the package overall is considered to be not found. If the REQUIRED option is also present, this is treated as a fatal error, otherwise execution still continues. As a form of shorthand, if the REQUIRED option is present, the COMPONENTS keyword can be omitted and the required components can be listed directly after REQUIRED. Additional optional components may be listed after OPTIONAL_COMPONENTS. If these cannot be satisfied, the package overall can still be considered found, as long as all required components are satisfied. Note keywords: QUIET REQUIRED OPTIONAL_COMPONENTS You can alter behavior of you cmake code by using <PackageName>_FOUND to handle failure.
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 delete it (to free the allocated memory) you need apply the operator delete [] to the pointer s2. delete [] s2;
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>hierachy; findContours(Canny_img , contours , hierachy , RETR_EXTERNAL , CHAIN_APPROX_SIMPLE); sort(contours.begin(), contours.end() , greater<Point>()); //This line getting error for(int i = 0; i < contours.size(); i++) { drawContours(img , contours , i , Scalar(0,255,0) , 2); imshow("Contour Image" , img); waitKey(0); }
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(), contours.end(), [](std::vector<cv::Point> const & v1, std::vector<cv::Point> const & v2) { return true; }); As you can see the lambda simply returns true. This is just a stub. Instead you should implement the criterion you want for sorting. You have to determine when you consider one element (which is a vector of Points) to be greater than another (also a vector of Points). It depends on what you want to actualy do with the contours. Note: it is better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?. In my opinion it's better to avoid using namespace cv as well, from a similar reason.
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 << tree->toStringTree(true) << "\n";
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 more information /// based upon the parser. virtual std::string toStringTree(Parser *parser, bool pretty = false) = 0; So, to fix the "error", replace tree->toStringTree(true) with tree->toStringTree(&parser, true)
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& bar1) { m_bar1 = bar1; emit bar1Changed(); } int bar1() const { return m_bar1; } void setBar2(const int& bar2) { m_bar2 = bar2; emit bar2Changed(); } int bar2() const { return m_bar2; } signals: void bar1Changed(); void bar2Changed(); private: int m_bar1; int m_bar2; }; And a QOuterItem that is composed with a QInnerItem and an int. class QOuterItem : public QObject { Q_OBJECT Q_PROPERTY(int foo READ foo WRITE setFoo NOTIFY fooChanged) Q_PROPERTY(QInnerItem bar READ bar) public: void setFoo(const int& foo) { m_foo = foo; emit fooChanged(); } int foo() const { return m_foo; } const QInnerItem& bar() const { //must return either the property's type or a const reference to that type return m_bar; } signals: void fooChanged(); private: int m_foo; QInnerItem m_bar; }; This gives me the error: moc_Model.cpp:264: error: C2280: 'QInnerItem &QInnerItem::operator =(const QInnerItem &)': attempting to reference a deleted function I believe this is because a QObject has an explicitly deleted copy assignment operator: https://doc.qt.io/qt-5/qobject.html#no-copy-constructor-or-assignment-operator Is there any way to access a reference to m_bar without the copy assignment operator? From the same link, it also says: "The main consequence is that you should use pointers to QObject (or to your QObject subclass) where you might otherwise be tempted to use your QObject subclass as a value. For example, without a copy constructor, you can't use a subclass of QObject as the value to be stored in one of the container classes. You must store pointers." So I have tried: class QOuterItem : public QObject { Q_OBJECT Q_PROPERTY(int foo READ foo WRITE setFoo NOTIFY fooChanged) Q_PROPERTY(QInnerItem bar READ bar) public: void setFoo(const int& foo) { m_foo = foo; emit fooChanged(); } int foo() const { return m_foo; } const QInnerItem& bar() const { //must return either the property's type or a const reference to that type return *m_bar; } signals: void fooChanged(); private: int m_foo; QInnerItem* m_bar = new QInnerItem(this); }; But this gives the exact same error. How can I achieve what I am trying to do? i.e: Have a QObject with properties, and one of those properties is a QObject with it's own properties.
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 bar) public: QInnerItem *bar() const { return &m_bar; } private: QInnerItem m_bar; };
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]; } //assign value for (int i = 0; i < 2; ++i) for (int j = 0; j < 4; ++j) cin >> *((int*)A + i * 4 + j); //cin >> A[i][j]; //if I do this instead of the line above, I will get trash values in the output for (int i = 0; i < 2; ++i) { for (int j = 0; j < 4; ++j) { cout << *((int*)A + i * 4 + j) << " "; } cout << "\n"; } for (int i = 0; i < 2; ++i) delete[] A[i]; delete [] A; } Sample input: 1 2 3 4 5 6 7 8 I do not understand why when I do cin >> A[i][j]; then cout << *((int*)A + i * 4 + j) << " "; It gives me trash values. Does that mean I have to cin >> *((int*)A + i * 4 + j); if I am gonna cout << *((int*)A + i * 4 + j) << " ";? My other question is: Why must I explicitly cast (int*)? Why can't it be (A + i * 4 + j)?
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 cast is neither necessary nor advised, and can literally do nothing but hide bad code. If A is the right type it should be sufficient to do this: *(A + i*n + j) and if it isn't the right type, you probably shouldn't be doing this in the first place (which you just found out). Second, what your instructor did not tell you is that this is useful for establishing a faux multi-dimension array in the linear space of an single dimension array using creative indexing. The key there is single dimension array. The modus operandi is this: Given the desire to map a 2D space M rows by N columns into a 1D space of M*N elements, you can do this: constexpr size_t M = 10; constexpr size_t N = 5; int A[M*N]; A[row * N + col] = value; // equivalent to... *(A + row * N + col) = value; Note, row should be in the range 0...(M-1), and col should be the range 0..(N-1) inclusively. This model can be extended to more dimensions. For example, a "3D" mapping, with L denoting slabs, M denoting rows, and N denoting columns: constexpr size_t L = 10; constexpr size_t M = 8; constexpr size_t N = 5; int A[L*M*N]; A[slab * (M*N) + row * N + col] = value; // equivalent to... *(A + slab * (M*N) + row * N + col) = value; where slab is in the range 0...(L-1), row is in the range 0...(M-1), and finally col is in the range 0...(N-1). You should see a pattern forming. Any native single-dimension array can be indexed with subscripts manufactured with multi-dimension representation so long as you know the limits of each dimension, and the resulting index does not breach the single-dimension array bed. Most of the time you will have no need for this, but sometimes it comes in handy, especially in C++, as it lacks runtime-VLA support that C delivers. Therefore, the proper usage of what your instructor tried to tell you would be something like this: #include <iostream> int main() { static constexpr size_t M = 2; static constexpr size_t N = 4; int *A = new int[M*N]; //assign value for (size_t i = 0; i < M; ++i) { for (size_t j = 0; j < N; ++j) std::cin >> *(A + i * N + j); } for (size_t i = 0; i < M; ++i) { for (size_t j = 0; j < N; ++j) std::cout << *(A + i * N + j) << " "; std::cout << "\n"; } delete [] A; }
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(auto m: mapData){ cout << m.first << ": " << m.second << endl; } //C++17 for(auto [key, val]: mapData){ cout << key << ": " << val << endl; }
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] : copy) { std::cout << k << ": " << v << std::endl; } Finally, if you can use C++20, then you can simply do this: #include <ranges> for(auto&& [k, v] : map | std::views::take(10)) { std::cout << k << ": " << v << std::endl; }
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> createLineIterator(cv::Mat &frame) { cv::Point p1(400, 0); cv::Point p2(200, 800); cv::LineIterator line(frame, p1, p2, 8); std::vector<cv::Point> points(line.count); for (int i = 0; i <= line.count; i++, ++line) { points.push_back(line.pos()); } return points; //points that I will iterate over to create circles and draw the line } int main(int argc, char const *argv[]) { cv::Mat image(500, 1000, CV_8UC1); // cria imagem std::vector<cv::Point> points = createLineIterator(image); for (auto i : points) { cv::circle(image, i, 2, cv::Scalar(255, 100, 255)); //Point-by-point drawing of the iterator line } cv::imshow("image", image); cv::waitKey(0); return 0; }
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 drawing with cv::circle, but see that the random drawing no longer exists with cv::line
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 ThisType can be defined. However, in a large codebase that adds extra noise and is something that reviews will need to routinely check. Is there a way to wrap it in a type_trait such that I can write something along the lines of: this_type<SomeType>::value_type OR some other generic solution?
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 a template function (only declared) for every type you want extract from the possible types; one for type template <typename T, std::void_t<typename T::type>* = nullptr> typename T::type getType (tag<0u>); one for this_type template <typename T, std::void_t<typename T::this_type>* = nullptr> typename T::this_type getType (tag<1u>); one for ThisType template <typename T, std::void_t<typename T::ThisType>* = nullptr> typename T::ThisType getType (tag<2u>); and one (to be a little silly) for MySillyTypeName template <typename T, std::void_t<typename T::MySillyTypeName>* = nullptr> typename T::MySillyTypeName getType (tag<3u>); Observe that the number of the tag are differents: this avoid the possible ambiguity and give a priority order for the names. Now a trivial struct that uses getType() to extract the required type template <typename T, typename U = decltype(getType<T>(tag<100u>()))> struct GetType { using type = U; }; The following is a full compiling C++17 example #include <type_traits> template <std::size_t N> struct tag : public tag<N-1u> { }; template <> struct tag<0u> { }; template <typename T, std::void_t<typename T::type>* = nullptr> typename T::type getType (tag<0u>); template <typename T, std::void_t<typename T::this_type>* = nullptr> typename T::this_type getType (tag<1u>); template <typename T, std::void_t<typename T::ThisType>* = nullptr> typename T::ThisType getType (tag<2u>); template <typename T, std::void_t<typename T::MySillyTypeName>* = nullptr> typename T::MySillyTypeName getType (tag<3u>); template <typename T, typename U = decltype(getType<T>(tag<100u>()))> struct GetType { using type = U; }; struct foo1 { using type = short; }; struct foo2 { using this_type = int; }; struct foo3 { using ThisType = long; }; struct foo4 { using MySillyTypeName = long long; }; int main() { static_assert( std::is_same_v<short, GetType<foo1>::type> ); static_assert( std::is_same_v<int, GetType<foo2>::type> ); static_assert( std::is_same_v<long, GetType<foo3>::type> ); static_assert( std::is_same_v<long long, GetType<foo4>::type> ); }
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 = (brightness * maxval) / 100; So even though brightness * 255 is larger than what can be stored in an uint8_t, this still yields the correct result due to, if I'm correct, integer promotions. Brightness is a percentage so it should never be higher than 100 and therefore localoutput should never be higher than 255. My question is then whether or not any unexpected behaviour (such as brightness * maxval being larger than 255 therefore having overflow) or any significant differences between how this syntax is handled between c++ and c are the case. It seems to just output the correct answer, or would be more recommended to have the variables be of type uint16_t as the intermediate calculations may be higher than 255, and just take the memory loss for granted.
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 languages, this is not an issue because integers do not have a restricted range, but in C, C++, java, javascript and many other languages, integer types have a fixed number of bits so the multiplication can exceed this range. It is the programmer's responsibility to ascertain that the range of the operands ensures that the multiplication does not overflow. This requires a good understanding of the integer promotion and conversion rules, which vary from one language to another and are somewhat tricky in C, especially with operands mixing signed and unsigned types. In your particular case, both brightness and maxval have a type smaller than int so they are promoted to int with the same value and the multiplication produces an int value. If brightness is a percentage in the range 0 to 100, the result is in the range 0 to 25500, which the C Standard guarantees to be in the range of type int, and dividing this number by 100 produces a value in the range 0 to 100, in the range of int, and also in the range of the destination type uint8_t, so the operation is fully defined. Whether this process should be documented in a comment or verified with debugging assertions is a matter of local coding rules. Changing the order of the operands to maxval * brightness / 100 and possibly using more explicit values and variable names might help the reader: uint8_t brightness100 = 40; uint8_t localoutput = 255 * brightness100 / 100; The problem is more general than just a question of integer promotions, all such computations should be analyzed for corner cases and value ranges. Automated tools can help perform range analysis and optimizing compilers do it to improve code generation, but it is a difficult problem.
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 class member access expression, in which the class either has this member or is derived from a class that has this member, including the implicit this-> member access expressions that appear when a non-static member name is used in any of the contexts where this is allowed (inside member function bodies, in member initializer lists, in the in-class default member initializers). struct S { int m; int n; int x = m; // OK: implicit this-> allowed in default initializers (C++11) S(int i) : m(i), n(m) // OK: implicit this-> allowed in member initializer lists { this->f(); // explicit member access expression f(); // implicit this-> allowed in member function bodies } void f(); };
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, extract the threads into nodes based on sorted access times and information about the topology. Code: (Intel compiler, OpenMP) // create data which will be shared by multiple threads const auto part_size = std::size_t{50 * 1024 * 1024 / sizeof(double)}; // 50 MB const auto size = 2 * part_size; auto container = std::unique_ptr<double>(new double[size]); // open a parallel section auto thread_count = 0; auto thread_id_min_duration = std::multimap<double, int>{}; #ifdef DECIDE_THREAD_COUNT #pragma omp parallel num_threads(std::thread::hardware_concurrency()) #else #pragma omp parallel #endif { // perform first touch using thread 0 const auto thread_id = omp_get_thread_num(); if (thread_id == 0) { thread_count = omp_get_num_threads(); for (auto index = std::size_t{}; index < size; ++index) { container.get()[index] = static_cast<double>(std::rand() % 10 + 1); } } #pragma omp barrier // access the data using all threads individually #pragma omp for schedule(static, 1) for (auto thread_counter = std::size_t{}; thread_counter < thread_count; ++thread_counter) { // calculate the minimum access time of this thread auto this_thread_min_duration = std::numeric_limits<double>::max(); for (auto experiment_counter = std::size_t{}; experiment_counter < 250; ++experiment_counter) { const auto* data = experiment_counter % 2 == 0 ? container.get() : container.get() + part_size; const auto start_timestamp = omp_get_wtime(); for (auto index = std::size_t{}; index < part_size; ++index) { static volatile auto exceedingly_interesting_value_wink_wink = data[index]; } const auto end_timestamp = omp_get_wtime(); const auto duration = end_timestamp - start_timestamp; if (duration < this_thread_min_duration) { this_thread_min_duration = duration; } } #pragma omp critical { thread_id_min_duration.insert(std::make_pair(this_thread_min_duration, thread_id)); } } } // #pragma omp parallel Not shown here is code which outputs the minimum access times sorted into the multimap. Env. and Output How do OMP_PLACES and OMP_PROC_BIND work? I am attempting to not use SMT by using export OMP_PLACES=cores OMP_PROC_BIND=spread OMP_NUM_THREADS=24. However, I'm getting this output: What's puzzling me is that I'm having the same access times on all threads. Since I'm trying to spread them across the 2 NUMA nodes, I expect to neatly see 12 threads with access time, say, x and another 12 with access time ~2x. Why is the above happening? Additional Information Even more puzzling are the following environments and their outputs: export OMP_PLACES=cores OMP_PROC_BIND=spread OMP_NUM_THREADS=26 export OMP_PLACES=cores OMP_PROC_BIND=spread OMP_NUM_THREADS=48 Any help in understanding this phenomenon would be much appreciated.
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 memory page(s) on which my data lay. Furthermore, giving in to my programmer's paranoia, I ditched the std::unique_ptr for fear that it may lay its own first touch after allocating the memory. // create data which will be shared by multiple threads const auto size_per_thread = std::size_t{50 * 1024 * 1024 / sizeof(double)}; // 50 MB const auto total_size = thread_count * size_per_thread; double* data = nullptr; posix_memalign(reinterpret_cast<void**>(&data), sysconf(_SC_PAGESIZE), total_size * sizeof(double)); if (data == nullptr) { throw std::runtime_error("could_not_allocate_memory_error"); } // perform first touch using thread 0 #pragma omp parallel num_threads(thread_count) { if (omp_get_thread_num() == 0) { #pragma omp simd safelen(8) for (auto d_index = std::size_t{}; d_index < total_size; ++d_index) { data[d_index] = -1.0; } } } // #pragma omp parallel mlock(data, total_size); // page migration is a real thing... // open a parallel section auto thread_id_avg_latency = std::multimap<double, int>{}; auto generator = std::mt19937(); // heavy object can be created outside parallel #pragma omp parallel num_threads(thread_count) private(generator) { // access the data using all threads individually #pragma omp for schedule(static, 1) for (auto thread_counter = std::size_t{}; thread_counter < thread_count; ++thread_counter) { // seed each thread's generator generator.seed(thread_counter + 1); // calculate the minimum access latency of this thread auto this_thread_avg_latency = 0.0; const auto experiment_count = 250; for (auto experiment_counter = std::size_t{}; experiment_counter < experiment_count; ++experiment_counter) { const auto start_timestamp = omp_get_wtime() * 1E+6; for (auto counter = std::size_t{}; counter < size_per_thread / 100; ++counter) { const auto index = std::uniform_int_distribution<std::size_t>(0, size_per_thread-1)(generator); auto& datapoint = data[thread_counter * size_per_thread + index]; datapoint += index; } const auto end_timestamp = omp_get_wtime() * 1E+6; this_thread_avg_latency += end_timestamp - start_timestamp; } this_thread_avg_latency /= experiment_count; #pragma omp critical { thread_id_avg_latency.insert(std::make_pair(this_thread_avg_latency, omp_get_thread_num())); } } } // #pragma omp parallel std::free(data); With these changes, I am noticing the difference I expected. Further notes: this experiment shows that the latency of non-local access is 1.09 - 1.15 times that of local access on the cluster that I'm using, there is no reliable cross-platform way of doing this (requires kernel-APIs), OpenMP seems to number the threads exactly as hwloc/lstopo, numactl and lscpu seems to number them (logical ID?) The most astonishing things are that the difference in latencies is very low, and that memory page migration may happen, which begs the question, why should we care about first-touch and all the rest of the NUMA concerns at all?
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> data1; B b1; b1.setB(&data1); } Which doesn't work. As a solution, I can create the B class as a template class and create B object as B<A<size1>> b1; but this will create multiple objects if I multiply A<sizeX>, which I don't want since this code is for an embedded project which has finite resources. All I want is to pass the pointer of data1 object to another class function and store it inside. The code I'm looking for is for C++03, I cannot use C++11 features such as shared pointers. Is there a way to do this? Appreciate any help,
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(int n) { return b->getA(n); } void setB(A<size>* n) { b = n; } }; int main() { const int size1 = 10; A<size1> data1; B<size1> b1; b1.setB(&data1); int a = b1.getA(0); } Or by giving A a non-templated base class for B to hold, eg: class A_base { virtual ~A_base() {} virtual int getA(int n) = 0; }; template <int size> class A : public A_base { public: int a[size]; int getA(int n) { return a[n]; } }; class B { public: A_base* b; int getA(int n) { return b->getA(n); } void setB(A_base* n) { b = n; } }; int main() { const int size1 = 10; A<size1> data1; B b1; b1.setB(&data1); int a = b1.getA(0); } Otherwise, you will have to make B just hold a void* pointer, and then require the caller to extract that void* and decide what to cast it to, eg: template <int size> class A { public: int a[size]; int getA(int n) { return a[n]; } }; class B { public: void* b; void* getB() { return b; } void setB(void* n) { b = n; } }; int main() { const int size1 = 10; A<size1> data1; B b1; b1.setB(&data1); int a = static_cast< A<size1>* >(b1.getB())->getA(0); }