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
63,401,750
63,401,837
Trying to construct an object with another object as parameter
https://imgur.com/gallery/pEw8fBs https://pastebin.com/xvWFHrTU My errors are posted above..I don't understand what's wrong with this code..I'm trying to construct a book with a date object inside of it. Please help, this is my frist post as well!! :) #include<iostream> #include<string> #include<vector> #include<algor...
Both of your constructors are declared but not defined class Date { int y, m, d; public: Date(int _d, int _m, int _y) : y(_y), m(_m), d(_d) {} // definition }; class Book { string title; string author; string isbn; Date date; public: Book(string t, string a, string id, Date d) : title...
63,401,931
63,404,690
pybind with boost/dll - dual use DLL?
TL;DR Adding pybind11 bindings to a working C++ DLL project allows me to import and use the resulting DLL in Python but breaks my ability to use it in C++ code using boost/dll machinery. Summary I've got a C++ library that I compile to FooLib.dll. I use boost/dll's BOOST_DLL_ALIAS and boost::dll::import_alias() to exp...
The suggestion in @n.'pronouns'm. comment is correct. Simply copying the python DLL from the Anaconda distribution I built against to the C++ program's run directory fixes the problem. Makes sense in retrospect, but didn't occur to me. Makes it even more likely that I should keep the builds separate or at least set up ...
63,402,261
63,402,538
What is the difference between range-v3 views::drop and views::drop_exactly?
Can someone explain the difference between range-v3's view adaptors drop and drop_exactly? One difference I've observed is that if the number of elements in the range that is piped to these views is less than the argument to the view adaptors, drop seems to do the right thing, while drop_exactly seems to invoke UB. Whe...
From the documentation for drop_exactly: Given a source range and an integral count, return a range consisting of all but the first count elements from the source range. The source range must have at least that many elements. While the documentation for drop states: Given a source range and an integral count, return...
63,402,454
63,402,715
Redundant Data Members
I have a class A which stores a SquareMatrix. class A{ private: SquareMatrix mat; }; The class frequently uses the size of the matrix using mat.size() (a constant time operation). mat.size() really is another measure of the size of A. Following good coding practice, should A also store a copy of mat.size()? class ...
Storing a data member that represents the size of A in this example is not a good idea if "mat.size() really is another measure of the size of A". The primary issue here is: how is A::size supposed to keep track of changes to SquareMatrix::size()? This value can change in potentially many places, and keeping them both ...
63,402,458
63,402,509
What is std::map<K,V>::map; and how do you know what namespace to use when implementing/using stl containers and functions?
I am trying to write a class that inherits the std::map but I also want to overload one specific function while keeping the remaining inherited functions available for use. After reading a bit about that it seems you have to use the namespace of map to be able to use it's functions. However I had to use using std::map<...
using std::map<K,V>::map; You need to use it if u want to use the base ctors outside the class (to inherit the constructors). And this std::map<K,V>::map is the constructor and qualified by the class name.
63,402,611
63,403,667
How to add process arguments using CreateProcessAsUserA
I figured out how to open a process using CreateProcessAsUserA() from this: example code: A service calls CreateProcessAsUser() I want the process to run in the user's session, not session 0 Now, I need to add process arguments to run the program correctly, I mean arguments like -steam. I can't find any solution to do ...
If you find it tricky to get the quotes right, you could create a function to do it. C++17: #include <initializer_list> #include <string_view> #include <utility> // A function to prepare a commandline for execution by quoting auto prep_cmd(std::initializer_list<std::string_view> args) { if(args.size()==0) throw st...
63,403,176
63,403,544
Token in macro definition was not declared in this scope
I am trying to make a logic system using defines macros for implementation of my logger that will expand into nothing when certain toggles are defined. The problem is that when I stack multiple of these switches one nested inside the other (like with calling of the IF_SWITCH_1 function-like macro) I get multiple errors...
What causes these errors? The expansions are run kind-of once. Once a macro is expanded, it wont be expanded again, also in a nested macro calls. Anyway the chain is: IF_SWITCH_1(1, 1, 1) _LOGIC_SWITCH_(IF_SWITCH_1_, CONDITION_1, 1, 1, 1) // step 2 _ADD_PARTS(IF_SWITCH_1_, true, 1, 1, 1) _ADD_PARTS2(IF_SWITCH_1_, tr...
63,403,179
63,403,213
How to expand parameter pack for dependent types?
What is the syntax for expanding a parameter pack where the types I want are dependent on the types directly in the pack? For example: template <typename T> struct foo { typedef T value_type; }; template <typename ... T> struct aggregate_of_foo { typedef std::tuple<foo<T>::value_type...> tuple; // MSVC compiler ...
You have to use the keyword typename because value_type is a dependent name in this context. template <typename ... T> struct aggregate_of_foo { typedef std::tuple<typename foo<T>::value_type...> tuple; //here };
63,403,229
63,403,649
Parsing a YAML file?
How can I parse the following YAML file using yaml-cpp? scene: - camera: film: width: 800 height: 600 filename: "out.svg" - shape: name: "muh" I tried: #include <yaml-cpp/yaml.h> int main() { YAML::Node root_node = YAML::LoadFile("Scenes/StanfordBunny.flatland.yaml"); ...
The "-" in front of camera means it is an array of objects. So my guess would be: root_node["scene"][0]["camera"]["film"]["width"].as<int>();
63,403,287
65,793,676
Can't print out in both english and cyrillic in my C++ MFC application
Im writing a MFC application. I need to use the CString class not something else. I've done the following because it was the only way I could display cyrillic. Without I either got question marks or nothing showed up at all. _setmode(_fileno(stdout), _O_U16TEXT); So this works: CString strTestObj2("дададада"); wprintf...
This was fixed by setting the OS system locale to bulgarian.
63,403,646
63,403,697
I can't make my function calculate how much time has passed and print stuff accordingly
bool IsGameEnded() { static int i = 0; i++; if (i == 10) return true; return false; } int main() { bool GameEnd = false; float ElapsedTime = 0; while(!GameEnd) { chrono::steady_clock::time_point StartingTime = chrono::steady_clock::now(); if (ElapsedTim...
When you do: chrono::duration_cast<chrono::milliseconds>(EndingTime - StartingTime).count(); not enough time has passed, and the count of milliseconds always returns 0. This means you always add 0 to ElapsedTime and it never crosses 10. One fix is to use a smaller resolution: chrono::duration_cast<chrono::nanoseconds>...
63,403,986
63,404,087
How to call a function of inner class in outer class?
class student { private: int admno; char sname[20]; class Student_Marks { private: float eng, math, science, computer, Hindi; float total; public: void sMARKS() { cin >> eng >> math >> science >> computer >> Hindi; } float cTotal() ...
Your Student_Marks is just a class definition. Without having an object of the Student_Marks class in student, you can not call its member (e.g. cTotal()). You can have a look at the sample code below: class student { private: int admno; // better std::string here: what would you do if the name exceeds 20 char?...
63,404,539
63,769,749
Portable loop unrolling with template parameter in C++ with GCC/ICC
I am working on a high-performance parallel computational fluid dynamics code that involves a lot of lightweight loops and therefore gains approximately 30% in performance if all important loops are fully unrolled. This can be done easily for a fixed number of loops by using compiler directives: #pragma GCC unroll (16)...
Sadly currently there does not seem to be a consistent way to do so. I ended up using a pre-processor macro in combination with _Pragma(string-literal) and a stringification macro (similar to this) that decides whether to unroll depending on the template parameter if the Intel C++ Compiler ICC or Clang is available, to...
63,404,787
63,404,855
c++ : Defining array within an if-else condition erases after it exits
I have a script that fills in an array, either by using a function, or not. It takes in an argument readmode, it decides whether to use the function or not; and an argument len_arr, which decides the length of the array. I simplified the code so that every iteration the array length increases every iteration, but in ac...
uncomment this // double *buffer; buffer should be defined above for loop. double *buffer; in if-else blocks just use buffer without defining it. buffer = (double *)malloc(len_arr * sizeof(double));
63,404,967
63,406,582
Is it possible to continue debugging past an unhandled exception in Visual Studio?
A variety of other questions hint that it is possible to continue debugging past an "Exception Unhandled" popup like this: This is the popup from Visual Studio 2019, but VS 2015 gives similar behaviour. In both cases, for all combos of Win32/x64 and Debug/Release I have tried, the debugger refuses to go past the point...
Yes - it's possible. If you get to that pop up repeatedly, and the exception settings are such that the exception is NOT intercepted by the debugger (and therefore passed to the application's own exception handling), then it could be that your "unhandled" exception handling has already run, or does not exist in the for...
63,405,344
63,422,426
C++ construct vector from raw array without copy
Is it possible to construct a vector from a raw pointer without copy? I know the vector itself has ownership semantics, it allocate space when constructed, and responsible for releasing that memory when destroyed. But that's not what I want, what I want to do is more like an adapter, it has no ownership regarding the u...
This is quite easy as long as you don't require ownership, as you mention. The solution is to use a type-erased contiguous sequence. If at some point you do desire ownership, it gets a bit more complicated. I've added information on this to the bottom of this answer. Non-owning If you are using c++20, you can make use ...
63,405,373
63,405,650
Are there any C++ graphic libraries for mobile?
I’m currently attempting to design a Pong clone as a way of testing my coding abilities. However, being on mobile, I can’t use a keyboard as an input to move the paddle, so I must use buttons, or some other method that involves the touch screen. After doing some research, it seems most people just use a graphic library...
SDL2 has pretty nice support for mobile stuff, including iOS. There's a nice explanation/intro here
63,405,519
63,451,770
Why does std::push_heap generate a -Wstrict-overflow=3 warning even if no signed types are involved?
According to the documentation of -Wstrict-overflow, level 3: Also warn[s] about other cases where a comparison is simplified. For example: x + 1 > 1 is simplified to x > 0. The MWE shown below throws the following warning on level 3 and up, but not below, AND if optimisation is set to -O2 and up but not below. g++ v...
Is this a bug in the library implementation? I don't see any signed types whatsoever. No. The library implementation is correct. Using -fsanitize=undefined confirms there is no overflow. The warning only tells you that the compiler is assuming no overflow occurs. It can optimise the code more aggressively if it ass...
63,405,587
63,407,390
ncurses not doing anything even after initialized
So I was following a tutorial of ncurses in linux, but it doesnt do anything. Here's my code: #include <ncurses.h> int main() { initscr(); printw("Tset"); refresh(); endwin(); } When i compile it using g++ main.cpp -lncurses it works but it doesnt even output a single thing. Not even clearing the scree...
It is because endwin() is closing your ncurses window after printing "Tset". It is quick and you don't see it. You could make the program wait for some key to be pressed before closing the window to see the output. Use getch() before ending the window. #include <ncurses.h> int main() { initscr(); printw("Tset"...
63,406,035
63,452,021
PyImport_Import cannot find module
I'm trying to call a python function inside my c++ When i import my python module it gives this error: ModuleNotFoundError: No module named 'test' Here is how i'm importing the module: #define PY_SSIZE_T_CLEAN #include <Python.h> int main() { Py_Initialize(); PyObject *pName = PyUnicode_FromString("test"); ...
Use Py_SetPath before Py_Initialize() to set the sys.path. Here is a longer list of what can be done before you initialize the interpreter: pre-init-safe Isolate the embedded Python interpreter and set the path properly to avoid problems with partially using the modules of the installed Python version.
63,406,103
63,413,621
Seeding independent bits engine with boosts multiprecision
I have a simple rejection sampling application which is wrapped in a class and used externally as the dummy example below shows. I was able to adapt this post to a boost::multiprecision use case. However I'm not sure how to appropriately seed the generator and can't find any random_device equivalent for boost. The belo...
This works: #include <iostream> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <random> #include <boost/random.hpp> using namespace boost::multiprecision; typedef boost::random::independent_bits_engine<boost::mt19937, std::numeric_limits<cpp_dec_float_50>::digit...
63,406,200
63,406,397
Post increment of index in a string in c++
This is a function that generates all possible strings with different combinations of characters in a given string, and for the generated strings if their length is equal to the specified length in function argument return these strings in a set. Code 1 works fine, whereas code 2 has one line of change that changes ind...
The difference is the if: if(num&1) comb = comb + s[i]; num = num>>1; i++; If the condition is true, concatenate strings and then do the rest regardless of the condition. if(num&1) comb = comb + s[i++]; num = num>>1; If the condition is true, concatenate and increment, but if the condition is false no increme...
63,406,389
63,572,641
C++ Variable Assignment with If statement
I'm trying to program a system where the user gets to choose if they were to enter a date in Day, Month, or Year with a combo box. Here's my code: double Years; if (FinancialTermType->SelectedIndex == 0) { String ^ TermTextbox = Term->Text; std::wstring TermString(TermTextbox->Data()); ...
Have a initial value for Years, for example Double Years = 0 when defining the variable.
63,406,706
63,406,733
initializing default parameter with class member function/variable
class C { private: int n{ 5 }; public: int return5() { return 5; } void f(int d = return5()) { } void ff(int d = n) { } }; Why I can't initialize the functions default parameters with member class? I get an error: a nonstatic member reference must be relative to a specific object. I thin...
The default argument is considered to be provided from the caller side context. It just doesn't know the object on which the non-static member function return5 could be called on. You can make return5 a static member function, which doesn't require an object to be called on. E.g. class C { ... static int return...
63,406,852
63,408,658
QT live camera on QImage. Application crashes due to out of memory. Memory increases with speed
I am using QT Qpixmap to show the image captured from the camera using the OpenCV frame. I am doing following steps Capture image using OpenCV Convert the OpenCV image to QImage Convert QImage to Qpixmap Show it on Qlabel The problem I am facing is the memory start increasing at great speed and after few time the appli...
After trying many things here is the conclusion and code is now working perfectly fine I removed the tic toc part time(&start); timer = double(getTickCount()); tic(); It was working but crashing then just to make sure that QImage is not NULL I removed the img = QImage(); // releasing memory with if(!img.isNull()) ...
63,407,013
63,429,409
Horizontally tiling QMdiArea sub winows that contains QScrollArea
The following piece of code (mainwindow.cpp) is a simplified version of my problem. I tried to tile QMdiArea sub windows horizontally, but somehow the sub windows' are not fully shown - the horizontal scroll bars at the bottom of those sub windows are not shown properly. It seems to me that the problem is the height se...
In case someone runs into this: QMdiArea::tileSubWindows() does the trick. mdiArea->tileSubWindows();
63,407,026
63,407,113
How to pass in a brace-enclosed initializer list to a function?
I want to write a function that can be used with an argument that otherwise could directly occur in a range-based loop: template <typename Iterable> void sayIt(const Iterable& stuff) { for (const auto& e : stuff) { cout << e << endl; } } This works fine with stl containers and other types, but not with...
Braced-init-list has no type and cause template argument deduction failing. Non-deduced contexts In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or e...
63,407,257
63,407,325
What is good way to name parameters in C++ constructors?
I've learning C++ but I come here from Python. Suppose I want to create a class named Dog with parameters such as name, height, breed and color. In Python,I would have described name of parameters in constructors with meaningful names, because that is what would appear in good IDE as a hint (or suggestion) while creati...
You can give the parameters the same name as the fields (just like your python example). This Dog(string name, double height, string breed, string color) : name(name), height(height), breed(breed), color(color) { } is perfectly correct code. So is Dog(string name, double height, string breed, string color) { t...
63,407,283
63,407,616
Reading a excel file in to struct c++
I want to read a excel file in to a structure.But the thing is it reads the excel columns as whole line.I need those data in columns one by one.Using fstreams I have a file opened that contains numerous columns I tried it with the knowledge that I have.But It displays all the details as a whole column as i've shown be...
You can use std::getline() string readString; if (file) { while (!(file.eof())) { getline(file,readString); // Read the column headers for (int i = 0; i <= 7; i++) { getline(file,limit[i].name,','); // ',' is the separator getline(file,limit[i].nickName,','); get...
63,407,321
63,407,530
Returning a 0 on my matrix hourglass calculating function
I'm having issues with this set of codes and I have no idea why, so the purpose of this code is to get a value of an hourglass figure in a matrix. For example. 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 And this is meant to take in the highest amount from all the possible hour glass, so fo...
That's because you initialized the maximumoutput with 0. So you will never get any value below 0 because of this check: maximumoutput = temp > maximumoutput ? temp : maximumoutput; To fix, you need to initialize maximumoutput with minimum possible value maximumoutput = std::numeric_limits<int>::min();
63,407,753
63,408,111
Is there any alternative ways I can follow without using syntax older than or equal to g++ 4.8.5?
I am trying to find the the words that are used in a maximum frequency in a text file. The function I wrote works perfectly fine with g++ 6.3.0 however my T.A. insisted that it should work with g++ 4.8.5. I have been working on this problem for two days now, I searched online but couldn't find anything that would help ...
"4.8.5 supports c++11, so compile with -std=c++11 and you're fine." would be my first sentence when handing in the assignment. You could follow up by converting the code to C++98. Since decltype doesn't exist and auto doesn't mean the same thing in C++98 (it exists but for a different purpose) you need to type the long...
63,408,365
63,411,174
Anagram of 2 string : I don't understand what is the problem with my code
I have my code which return the smallest integer deletions required to make anagram : #include <bits/stdc++.h> using namespace std; int makeAnagram(string a, string b) { int count = 0; for(auto it=a.begin(); it!=a.end(); it++){ if(find(b.begin(), b.end(), *it) == b.end()){ a.erase(it); ...
Problem with your approach is you are deleting the element during the iteration but your not considering the change in the iterator i,e you should first increment iterator then delete the previous element here is simple approach int makeAnagram(string a, string b) { int A = a.size(); int B = b.size(); int c...
63,408,694
63,408,746
"Invalid operands to binary expression" error when comparing `char` with return value of `std::stack::pop()`
I'm solving a LeetCode problem and I'm getting the following error: > Line 15: Char 23: fatal error: invalid operands to binary expression ('char' and 'void') else if(c != st.pop()) 1 error generated. I set the stack to char type, but it seems to treat it as a void type? What could be goi...
std::stack::pop() doesn't have a return value. When you do c != st.pop(), compiler sees "compare char value with void value", what makes no sense. Possible solution would be to first get the value from top to temp variable, then pop() and at least compare them: else { if (st.empty()) ...
63,408,787
63,410,127
Texture object fetching in CUDA
I can find many examples online that use CUDA texture references, but not so many that rely on texture objects. I am trying to understand why my code below always fetches 0 rather than my input texture. Am I missing something, or using a wrong setting? I simplified it as much as I could: #include <stdio.h> __global__ ...
In your code you specify the texture description as texDesc.addressMode[0] = cudaAddressModeBorder; texDesc.addressMode[1] = cudaAddressModeBorder; texDesc.filterMode = cudaFilterModeLinear; texDesc.readMode = cudaReadModeElementType; texDesc.normalizedCoords = 1; and the array holding the texture da...
63,408,928
63,411,745
Class template explicit instantiation declaration
This is a bit of a complicated pattern that doesn't fit well with friendship. Maybe I have to reconsider the design, but for now I'm just interested whether it is possible to make this work. The problem is that I can't declare class A template explicit instantiation (with incomplete class B as a template argument) that...
You seems to confound explicit instantiation and template specialization. With template class ElemTempl<el::Comp>; (explicit instantiation), you instantiate the full class, and CompT comp; requires a complete type, whereas el::Comp is just forward declared. using Elem = ElemTempl<el::Comp>; is just the definition of an...
63,408,962
63,408,997
Lambda function throwing error if return type is changed from auto to bool
I was practicing lambda functions in C++, following code works fine void insertionSort(int* a, int size, bool reverse=false) { auto comp = [](int a, int b, bool reverse) { return reverse ? a > b : b < a; }; for (int i = 0; i < size; i++) { int current = a[i]; cout << current <<...
In the 1st code snippet, comp's type is the type of the lambda, it's a unique unnamed class type, (that's why we use auto, we can't specify the type explicitly). Note that it's not the return type of the lambda (i.e. bool). If you want to specify the return type of the lambda explicitly you can auto comp = [](int a, in...
63,409,021
63,409,264
Valid std::search use to find all occurences of a subsequence (avoid infinite loop)
I am trying to find all occurences of a subsequence within a sequence. My idea is to use std::search and then advance the resulting iterator until I reach the end of the collection. This is the code that works: #include <algorithm> #include <vector> using namespace std; int main () { vector<int> MainSequence {2,3...
the condition is changed to it < MainSequence.end() or it != MainSequence.end() both are right, personally I prefer the second way but for sure (it < MainSequence.end() - 1) can be never true and yo have to use one of the two proposal above in the loop body, if it is incremented by 1 instead by 2? To decide it is n...
63,409,714
63,409,747
Sort Stack using vector
I'm new to stacks and vectors. I'm trying to sort a stack using vector but I am facing an error. Please suggest how to solve this error MY CODE /* The below method sorts the stack s you are required to complete the below method */ void SortedStack :: sort() { vector<int> st; while(!s.empty()){ st.push_back(s...
sort(st.begin(), st.end()); is an attempt to call your sort function and compilation fails as the parameters are incorrect. std::sort(st.begin(), st.end()); is a trivial fix. The moral of the story is to always use std:: explicitly, and drop using namespace std; &c.. Your code also becomes more readable as it's immedia...
63,409,897
63,410,032
Why doesn't std::abs() works with floats
The result of std::abs(0.5f) is 0 because there is no overload for floats. Why? I'm using G++.
You have to be very careful when using the overloads of std::abs as some standard library implementations litter the overloads across many files, some of which get implicitly included into others, like <iostream>. If you #include <cmath> or #include <cstdlib> (the second one from C++17) before your std::abs(0.5f) then ...
63,410,743
63,410,800
How to reverese a c-style string
I would like to reverse a c-style string and came up with the following code. Play with the code #include <iostream> void reverse_c_str(char *c) { char *new_c = c; for (; *new_c; ++new_c){} // find '\0' --new_c; // new_c is now at the actual last char, which is 'g' while (c < new...
"my string" is a string literal, it is const. It can be cast to a non-const char * for reasons of compatibility with C, but modifying a constant invokes undefined behavior. In some cases the OS will prevent it (as when it's stored in a read-only section), which is probably what you're observing. Make a copy of the stri...
63,411,813
63,411,986
Why am I getting segmentational fault with weak_ptr
I am doing an exercise to get to know the shared pointer and weak pointer. So the example is with cyclic dependence of shared_ptr and how could I solve the problem with weak_ptr. I want to initialize the root->left->parent to root and the same for right node but it is giving me segmentational fault. Does anybody know s...
// if (parent != nullptr) pStr = parent->name; pStr = parent.lock()->name; should be if (auto parentPtr = parent.lock()) pStr = parentPtr->name; parent.lock() might return null std::shared_ptr.
63,412,047
63,412,300
how to traverse in a unordered_map of unordered_map of unordered_map in c++
I wanted to traverse inside a data structure - unordered_map<int, unordered_map<int, unordered_map<int, int>>> myMap. To further specify I want to get the data elements like -> myMap[someVal1][someVal2] {all second elements of this unordered map} I am aware of the fact that the same could by done by a 3d array however ...
You could traverse the map with a foreach loop (it needs C++11, I think that won't be a problem), if you don't want to use iterators. myMap mapMapMap; for(auto& mapMap : mapMapMap){ for(auto& map : mapMap.second){ for(auto& key_value : map.second){ int key = key_value.first; int valu...
63,412,085
63,412,120
getch() returns 2 characters
Im trying to get a character from the user using getch. However it returns 2 same characters. #include <ncurses.h> int main() { initscr(); char input = getch(); printw("%c",input); getch(); endwin(); } does anyone know a fix to this?
When you type character in terminal it gets echoed back. What you see is echoed character and the result of printw(). As you are using ncurses, you can easly disable echoing, by calling function noecho(). Common practice is defining own function initializing curses, e.g.: void init_curses() if (!initscr()) { ...
63,412,180
63,412,655
How to create a limited number of threads?
I'm beginner in threads and I have one question. I have a vector with all .txt files in the current directory. How to count them in a given number of threads (by default - 4 threads). I heard about ThreadPool and found this code: ThreadPool.h #ifndef THREAD_POOL_H #define THREAD_POOL_H #include <vector> #include <queu...
The argument to enqueue is passed to the constructor of std::packaged_task, which has the following description: The class template std::packaged_task wraps any Callable target (function, lambda expression, bind expression, or another function object) so that it can be invoked asynchronously. Since you already have a...
63,412,215
63,412,333
pointer to const int using smart pointer
I am trying to create a smart pointer (unique_ptr) to a value returned as const int& but my issue can be summed up as easily as: const int value = 5; const int * ptr{nullptr}; ptr = &value; This works, and compile as expected. When trying to the same using smart pointer: const int value = 5; std::unique_ptr<const...
std::unique_ptr can't be assigned by raw pointer directly; you can use reset. But you shouldn't assign the address of value, (which is destroyed when get out of the scope automatically), std::unique_ptr will try to delete the pointer and that leads to UB. You might want int value = 5; // we'll constructor a new object,...
63,412,414
63,412,991
How to get round caps with QGraphicsPolygonItem?
I have code like this: #include <QApplication> #include <QGraphicsPolygonItem> #include <QGraphicsScene> #include <QGraphicsView> int main(int argc, char ** argv) { QApplication app(argc, argv); QGraphicsScene scene; QGraphicsView view; view.resize(640, 400); view.setScene(&scene); auto ...
Not entirely sure but to get the result you're looking for when using a polygon path I think it's actually the 'join' style that needs to be set rather than the cap style. So change... pen.setCapStyle(Qt::RoundCap); to... pen.setJoinStyle(Qt::RoundJoin);
63,412,795
63,413,198
OpenCV 4.3.0 compute integral image on GPU>
So I found the function to compute the GPU integral image here. The functions I need are gpu::integral and gpu::sqrIntegral (if there's a function that compute both the integral image and squared integral image at the same time, it would be best). However, in OpenCV 4.3.0, I cannot find these functions at all. I can on...
I found cv::gpu::integral in the namespace cv::cuda. There're many changed between OpenCV 2 and 4. I hope that you also refer to UMat which accelerates using OpenCL and easy to learn.
63,412,908
63,413,149
C++ dynamic memory allocation (char[] and int[])
 str is a pointer, why not use str for input and output? Not *str.  p is a pointer, why use *p for input and output? Not p. #include<iostream> using namespace std; int main() { char* str = new char[20]; cin>>str; cout<<str<<endl; delete []str; int* p = new int[3]; cin>>*p; cout<<*p<<en...
The operator overloads << and >> have special overloads for const char* and char* respectively, because those are null-terminated C-style strings. They are treated diifferently than other pointers/other arrays. Here's a little comparison of the semantics used: cin >> str; means "read a null terminated string into an a...
63,413,098
63,413,154
Why does map become empty outside the (switch) case?
I have the following code, where I initialize my map, inserts and view whether the data has been enter correctly in the first case. And then I view my data again in case 2, but it shows that it is empty in case 2, but is present in Case 1. I have never seen this kind of behavior. int main() { int t; cin>>t; ...
The line map<vector<int>, int> inserts; declares a variable that is local to the function in which it occurs. Each time that function is called, a new 'version' of the variable is created (and initialized as an empty map). When the function returns, the inserts object is destroyed. If you want the inserts object to ret...
63,413,320
63,413,668
c++, dealing with exceptions from constructors
I have a class which is loaded from an external file, so ideally I would want its constructor to load from a given path if the load fails, I will want to throw an error if the file is not found/not readable (Throwing errors from constructors is not a horrible idea, see ISO's FAQ). There is a problem with this though, I...
One possibility is to wrap the construction and error handling in a function, returning the constructed object. Example : #include <string> class my_class { public: my_class(std::string path); }; my_class make_my_object(std::string path) { try { return {std::move(path)}; } catch(...) { ...
63,413,418
63,413,760
free(): double free detected in tcache 2
I'm writing my own dynamic array class in C++ (similarly to std::vector), and I'm running into a problem when having a dynamic array containing dynamic arrays. Basically when having an array of all data types (int, double, float, std::string etc.) there is no problem and all the functionalities of the class works great...
You failed to write proper copy constructor and assignment operators: DynamicArray(DynamicArray const& rhs); // copy constructor DynamicArray& operator=(DynamicArray const& rhs); // copy assignment When you don't write these yourself, they are generated with shallow copy semantics. Since your class "owns" a pointer, ...
63,414,232
63,414,898
Passing ifstream created from embedded resource file to boost XML parser
I am trying to parse an embedded resource XML file: HRSRC hresinfo = FindResource(hInstance, MAKEINTRESOURCE(IDR_XML1), _T("XML")); if (hresinfo) { HGLOBAL hRes = LoadResource(hInstance, hresinfo); DWORD datasize = SizeofResource(hInstance, hresinfo); // this size is correct LPVOID data = LockResource(hRes)...
I think that pubsetbuf doesn't do what you need (however, I don't fully understand what it does exactly). To set std::ifstream content as it was loaded from the real file you can do the following: std::ifstream in; std::stringstream ss{std::string((char*)data, datasize)}; in.basic_ios<char>::rdbuf(ss.rdbuf(...
63,414,569
63,414,711
Where does Visual Studio 2019 CMake project Linux remote builder place sources and output files on target device?
I am building a C++ app for Linux and I'm using Visual Studio's CMake integration to remotely build the app. I have made some modifications to the project's directory structure, and now the output executable file has the same name as a folder that previously was part of the project. Now the program compiles well, but t...
I have never used that software before, but from the default config i'm guessing it is under ~/.vs/yourProjectName: { ..., "remoteMachineName": "${defaultRemoteMachineName}", "remoteCMakeListsRoot": "$HOME/.vs/${projectDirName}/${workspaceHash}/src", "remoteBuildRoot": "$HOME/.vs/${projectDirNam...
63,414,770
63,414,889
c++ - capturing perfectly forwarded vars in a lambda
I'm pretty new with c++ and am currently writing an inversion of control container for my first project, expanding on this blog post by adding registering on base classes and forwarding additional arguments to the constructor. It works pretty good for now but when I instantiate a lambda multiple times the captured valu...
Don't try to avoid a copy when you actually need one. In your case, you try to preserve the value categories of the arguments by std::forward them. But when you return a factory function std::function<T*()>, this closure must own the data it uses to perform the delayed construction. Otherwise, you end up with dangling ...
63,414,826
63,444,164
How to use Visual Studio to debug across a C# program calling a C++ dll?
I'm writing a C# application in Visual Studio 2019 that calls a C++ dll (to handle some CUDA programming) and I am not able to debug both sections of the code. The debugger works fine in the C# project but is not loading symbols in the C++ project even though they are all running in the same solution and are all set to...
How to use Visual Studio to debug across a C# program calling a C++ dll? Just add an answer for you and thanks to all the community members for their help. To debug native C++ code in a managed project, it actually can be done on Visual Studio so far. You can check this official document--Debug C# and C++ in the same...
63,415,084
63,415,119
Map when sorted in c++ produces huge error
I am new to using maps, and when I try to sort it using the code below #include <iostream> #include<map> #include<algorithm> using namespace std; int main() { map<int,int> mp; mp[2]++; mp[5]++; mp[1]++; sort(mp.begin(), mp.end()); } An error is thrown: In file included from /usr/include/c++/6/alg...
What might be the problem? You don't need to sort a std::map, it's already sorted. The error message (admittedly not terribly helpful) indicates that you are passing the wrong kind of iterator to std::sort. It needs random access iterators (see "Type requirements" here), but std::map doesn't offer these (it uses bidi...
63,415,534
63,420,975
WinUsb with C++ Builder 10.3 community edition
Has anyone successfully used winusb.h with Embarcadero's C++Builder 10.3 Community Edition? I recently downloaded 10.3 this with a view to updating a PC desktop/laptop application I wrote some years ago for Windows XP (using Borland C++Builder 6), which uses WinUSB functions to drive (one at a time) three machines. Att...
It is not enough to simply point the IDE to the folder containing Winusb.lib, you have to actually add that .lib file to your C++ project, or reference it explicitly in your C++ code using a #pragma comment(lib, "Winusb.lib") statement, otherwise the .lib file won't be passed to the linker to resolve your calls to the ...
63,415,624
63,417,808
Normalising a 2D histogram
I have a 2D histogram h1 with var1 on the x axis and var2 on the y axis, which I've plotted from a dataframe. I have normalised it as I want in c++ but now need to do the same in python and am struggling with how to get and set bin content. The idea is to remove the effect of having more events in one part of the distr...
To manipulate the contents of the bins, you could first calculate them, change them and only then draw the plot. plt.hist2d() returns the bin contents (a 2D matrix) together with the bin edges in both directions. To get the same information without plotting, np.histogram2d() returns exactly the same values. Afterwards,...
63,415,651
63,416,062
Variadic template parameter inference with nested maps
Working in C++, there's some times I'm working with nested maps. For instance, hypothetically: enum Color { RED, GREEN, BLUE}; enum Shape { CIRCLE, SQUARE, TRIANGLE }; std::unordered_map<Color, std::unordered_map<Shape, int>> shapeColorCount; For these situations, it would be useful to use variadic templates to write ...
Yes, you can write the following functions: template<typename Map, typename Value, typename FirstKey, typename ...RestKeys> void nestedSet(Map& map, Value const& value, FirstKey const& key, RestKeys const&... rest_keys) { if constexpr(sizeof...(RestKeys) == 0) map[key] = value; else nestedSet(ma...
63,415,675
63,415,884
C++ Read from stdin if within size
I want to read from stdin if that is within a size. How do I restrict that in this code? std::cout << "Enter a string till end of line: " << std::endl; std::isstreambuf_iterator<char> begin(std::cin), end; std::string str(begin, end); What I want is to restrict the read from stdin to maximum length of 10. If it is, th...
I'd suggest you to read char-by-char from cin. Use functions: cin.get(...) or char c; cin >> c; By this way you would control length and end-of-line.
63,415,706
63,415,770
Passing object from virtual class as argument in a function
I'm currently learning Object Oriented Programming and I came with this doubt: Let's say I have an abstract class Animal. To simplify, it will have only one virtual method, talk: class Animal { public: virtual string talk() = 0; } And the classes Cat and Dog, both derived from the abstract class Animal: class Cat ...
Use references, as follows. But note that the objects of Pet will have myPet itself not a copy from it. class Pet { public: Pet(Animal& myPet):myPet{myPet}{ } Animal& myPet; } Or use smart pointers (like std::unique_ptr<Animal>), as follows. And now you can have your unique Animal class Pet { public: ...
63,415,756
63,416,699
Do Windows apps support SIGINT for user-defined signal handlers?
The specs say: SIGINT is not supported for any Win32 application. When a CTRL+C interrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application, such as one in UNIX, to become multithreaded and cause unexpected behavior. I think it mean...
Actually Win32 does fire SIGINT on Ctrl-C, with a couple of caveats: it is fired from another thread, it needs to be re-armed after each hit. The second bullet introduces a race condition, and so it might be better to use the Win32 native SetConsoleCtrlHandler instead.
63,415,839
63,416,151
C++ How to know when an object has been destroyed
I don't understand how I can prevent accessing a dead object when it was created from a different scope and placed into some kind of container in another scope. Example #include <iostream> #include <string> #include <vector> class Foo { public: void Speak(){ std::cout << "ruff"; } }...
If you want an object's lifetime to extend beyond the scope in which it's created, then that object has to be created with dynamic lifetime. You use new to do this: std::vector<Foo*> foos; { Foo* foo = new Foo; foos.push_back(foo); } The Foo object that new returns a pointer to will live until it is explicit...
63,415,966
63,416,294
How to use std::shared_ptr and std::map correctly
I'm trying to implement some sort of simulation game on a 2D grid. I have 8 different basic graphics for tiles and want to hold pointer to the image data in a map, so I can later access them by the type of the tile (Land, Water ...) which is defined as enum (key for the map). I have an image class which holds the heade...
QPixmap has no constructor taking a pointer to (unsigned) char. std::shared_ptr<QPixmap> pixmap_deep_water = std::make_shared<QPixmap>(m_tga_terrain_images[0]->pixel_data().data()); // pixel_data() gets the vector of bytes You should declare QPixmap and invoke loadFromData(). QPixmap pixmap; // or std::shared_ptr<QPi...
63,416,688
63,416,798
std::async/std::future timeout with partial results
I would like to run a function with a timeout. And if the timeout is reached I would like to have access to the partial result generated by the thread before the timeout happened. As an example, I would like to do something similar to this in c++17: std::vector<int> my_result; auto future = std::async(std::launch::asy...
It is absolutely not safe. A timeout occurs when the process being waited on has not completed. future is purely binary synchronization; either the process is complete and the result object (and any side effects) are available to the receiving thread, or the process is not complete and nothing is synchronized to the re...
63,416,759
63,416,807
Adding a non-empty string to a vector using push_back, the vector contents are empty. Why is the string not added to the vector?
#include <bits/stdc++.h> #include <string> using namespace std; vector<string> func(string mag) { vector<string> s1; string temp1; string temp2; temp1[0] = 'a'; temp1[1] = 'b'; temp1[2] = 'c'; temp2 += "xyz"; s1.push_back(temp1); s1.push_back(temp2); return s1; } int main() { string st; ve...
string temp1; creates an empty string. Accessing any of its elements is an out-of-bounds-access causing undefined behaviour. If you want to access a string's contents like this, resize it before using it: string temp1; // VVVVVV temp1.resize(3); // now it contains 3 elements temp1[0]='a'; // set first element, ok t...
63,416,793
63,419,720
How can I make the std::vector class a Sequence so that it can be passed to boost::hana::group?
I want the following code to compile and work: #include <boost/hana/group.hpp> #include <functional> #include <vector> int main() { std::vector<int> x = {1,1,3,4}; auto groups = boost::hana::group(x, std::equal_to<>{}); } An attempt to compile errors like this: $ g++ -std=c++2a deleteme.cpp && ./a.out In file ...
While it is possible to implement some of the concepts in Boost.Hana with types that involve different dimensions known only at run-time, Boost.Hana.Sequence and some of the concepts that are a part of its "Minimal Complete Definition" require length and elements to be known at compile-time. Foldable requires that the...
63,417,181
63,417,298
C++ Passing an array of objects followed by an integer
I'm hoping this will turn out to be a simple question. I'm looking at some C++ code where it's passing an array of structs to a method, example: dosomething(arrayOfStructs + n); The array was initialized at 256 items, and prior to calling the example method, it performs some work which populates the array with some it...
I suppose that n has an integer type. In the expression used as an argument of this call dosomething(arrayOfStructs + n); the array designator arrayOfStructs is implicitly converted to pointer to its first element. Adding the integer value n the pointer to the first element of the array is moved to the n + 1 element o...
63,417,312
63,417,406
I have to put an alphanumeric password in a text file
Here's the code: #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <ctime> #include <windows.h> using namespace std; const char alphanum[] = "0123456789!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int string_length = sizeof(alphanum)-1; int main() { sys...
You need to move the password writing code inside the loop ofstream fout("password.txt"); for(int i=0; i<n; i++) { char password_char = alphanum[rand() % string_length]; cout << password_char; fout << password_char; } fout << endl; fout.close(); Exactly the same as your code that writes to cout.
63,417,415
63,417,719
Can someone explain the following snippet of linked list
I am getting confused with the last three lines of the code in the while loop. We basically have to return the sum of the linked list. ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int sum=0; ListNode *l3 = NULL; ListNode **node = &l3; while(l1 != NULL || l2 != NULL || s...
The function is creating a new linked list containing values calculated from 2 other linked lists. The head of the new list is pointed at by the l3 variable. Before the loop is entered, the node variable is set to point at the memory address of the l3 variable. On the 1st loop iteration, the statement (*node) = new L...
63,417,657
63,418,159
Confusion about return type of a function when it is a pointer
I wrote the following code: #include <iostream> using namespace std; const int * myFunction() { int * p = new int(5); return p; } int main() { int * q = myFunction(); cout << "*q=" << *q; cout << endl; return 0; } I purposely wrote the above code to receive an error. The mistake I made is th...
The return type of myFunction must match exactly to the type of variable which is going the receive it's return value. (Am I correct here? This is what I have understood.) No, the return type must not match exactly to the type of the variable. But it must be possible to implicitly convert the return type to the type ...
63,417,810
63,417,904
unordered_map with custom hash function and comparison predicate gives compilation error
I have a struct as key for std::unordered_map. I have written custom hash function and comparison predicate. When I try to compile the code I am getting the following error- error: static assertion failed: key equality predicate must be invocable with two arguments of key type 1831 | static_assert(__is_invocable...
bool operator()(struct keys const& k1, struct keys const& k2) must be const // VVVVV bool operator()(struct keys const& k1, struct keys const& k2) const You can also see it in the error message that the function must be callable on a const reference of the ob...
63,418,035
63,423,002
How can I Create single vim regular expression map to compile and run c++ program in windows
in linux i used something like autocmd FileType cpp nmap <buffer> <F5> :w<bar>!g++ -o %:r % && ./%:r<CR> but since windows uses back slashes i thought i should try something like autocmd FileType cpp nmap <buffer> <F5> :w<bar>!g++ -o %:r % && .\\%:r<CR> or autocmd FileType cpp nmap <buffer> <F5> :w<bar>!g++ -o %:r % ...
so the solution i ended up going with, was to not put any preceding backslashes . See the idea was to run a command terminal command like .\hello for program called hello i assumed its the linux equivalent of ./hello for any executable. turns out a hello.exe file gets created when one compiles so the solution is just ...
63,418,241
63,424,476
OpenGL weird rotation result with mouse
So I'm working on a 3d painting application. I managed to make a basic renderer and model loader. I created a camera system where I can use it to navigate around the scene(mouse/keyboard) but that's not what I want, so I made that camera static and now I'm trying to rotate/pan/zoom the model itself. I managed to implem...
I fixed it. After some research and asking i was told that u can only do one rotation at a time and i was trying to do both x/y-axis in the same time. Once i seperate the two rotations. object will now rotate on x-axis first then y-axis the problem was solved. The code should be like this: shader.use(); glm::ma...
63,418,418
63,418,614
Array type 'char [n]' and 'uint8 [n]' is not assignable
I'm trying to convert two types of values: char and uint8. I have a function someFunction(TLabel *label, TEdit *edit). Inside of this function, I have a variable char var[6+1]. What I'm trying to do: Get an Alphanumeric text (input of TEdit *edit), convert this text and put it inside of the var. I know that if I call t...
The Text of a TLabel or TEdit is a System::String, which is an alias for System::AnsiString in C++Builder 2007 and earlier, and for System::UnicodeString in C++Builder 2009 and later. You did not say which version you are using, but it makes a big difference in your example. You can't assign anything directly to a fix...
63,418,673
63,418,766
C++17 call static method of a template class without angle brackets
In C++17, you can omit angle brackets <> when declaring an instance. But why are they still needed when calling a static method from a template class ? #include <iostream> using namespace std; template<typename T = void> struct A { static const int i = 10; }; int main() { A a; // compile int i = A::i; //...
Because the language feature (Class template argument deduction) only dealt with constructing objects. It's based on overload resolution with constructors and deduction guides. With static data members, it would be an extremely limited feature - it could only possibly work if all the template parameters were defaulted,...
63,418,744
63,472,881
Peculiar Virual Function Fixes Unresolved External Symbol
I just inherited some legacy code. Where a problem method is being called. I have two solutions at the bottom, but why does making problemMethod virtual work... OtherClass::someOtherMethod() { // problemMethod(Manager* manager, const ConfigClass* config) obj->problemMethod(man, conf); // conf is not const in th...
Resolved: The problem was that in OtherClass.h the Config was forward declared as a struct when it is a class. It does not complain about this in vs2010 but does for vs2017
63,418,927
63,419,119
Prevent unnecessary copying between large structs
I have huge structs DataFrom and Data (which have different members in reality). Data is Created from DataFrom. struct DataFrom{ int a = 1; int b = 2; }; static DataFrom dataFrom; struct Data{ int a; int b; }; class DataHandler{ public: static Data getData(const DataFrom& data2){ ...
There are two potential "copy hazards" to address here: Copy hazard 1: The construction outside getData() On the first line of main(), where you commented "copy of whole Data structure" - as commenters noted, the structure won't actually be copied, due to the Named Return Value Optimization, or NRVO for short. You can...
63,419,012
63,421,027
Tracking z3::optimize unsat_core
How to properly track z3::optimize unsat core? The Z3 C++ z3::optimize does not find the expected solution when I add unsat_core tracking (based on these examples) (gcc 10.1.0). Take the following problem: There are three consecutive points A, B, and C, where A and C are fixed to 0 and 200, respectively. Determine B's ...
z3 doesn't support unsat-cores in the optimization mode. See this thread for a detailed discussion of this issue: https://github.com/Z3Prover/z3/issues/1577 The recommended solution (in pseudo-code) is: 1. Assert all constraints except optimization objectives 2. Issue `check-sat` 2.1 If `unsat`, get the unsat...
63,419,500
63,420,907
Longest palindromic substring missing an edge case
This is code I have written using dynamic programming concepts. bool ispalin(string s) { string s1=s; reverse(s.begin(),s.end()); if(s1.compare(s)==0) return true; return false; } string longestPalindrome(string s) { int n = s.length(); if(n==1) ...
The way you are using substr function is not correct. First argument should be the starting index and the second argument is the length of string. Your code must be failing for this string as well "abccbdf". Change if(ispalin(s.substr(i,j))) to this if(ispalin(s.substr(i,2))) And, in last return statement, your "coor...
63,419,576
63,419,602
Does push_back change the structure of type stored in its vector?
I have following 2 classes: class Core { public: Core() : mid(0), fin(0) {} Core(std::istream &in) { read(in); } virtual ~Core() {} Str name() const { return n; } virtual double grade() const { return vec_grade(mid, fin, hws); } virtual std::istre...
It uses the copy-constructor you wrote. This one: Student2(const Student2 &s) : cp(0) { if (s.cp) s.cp->clone(); } which sets cp to null (0). That is why the copy's cp is null.
63,419,637
63,420,229
images not found in response with libmicrohttpd
I have made a simple application utilizing microhttpd that displays a page on request. The page has some text on it which is correctly displayed but the images are not found how do I provide these images? from what I understand, I should provide them at the same time with the response page but i don't understand how. I...
The images are requested by the browser in separate requests. The server has to send a response for each image. The first request is for the HTML file, e.g. index.html. A later request is for the image file, e.g. image.png. You have to implement a routing for this.
63,419,684
63,420,242
Convert Epoch Milliseconds to UTC Date and Time using c++
I can get the current epoch time in milliseconds: #include <chrono> #include <cstdint> #include <iostream> #include <ctime> uint64_t timeSinceEpochMillisec() { using namespace std::chrono; return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count(); } int main() { std::cout << timeSinceEp...
Unfortunately, the chrono library only deals with time, and not dates. It seems things will change in C++20, but for now we have to work with functions and types from the ctime library. That is, once you get the current time with SomeClock::now() you can use to_time_t to convert it to a std::time_t, from the ctime libr...
63,419,695
63,420,981
C++ GeoClue g_object_unref: assertion 'G_IS_OBJECT (object)' failed
So I recently tried to try out GeoClue for one of my Raspberry Pi projects, but I got stuck on using gclue-simple(). Running gclue_simple_new seemed to be fine, but when I was trying to pick up the pointer with gclue_simple_new_finish(), the program gives me a runtime error: (process:37607): GLib-GIO-CRITICAL **: 16:26...
The callback is not to tell you that some results are ready, it’s to tell you that your GClueSimple* object has been created. You need to call gclue_simple_new_finish() from inside callback, not before. And you need to pass the GAsyncResult *result into it, plus a pointer to a GError *error = NULL initialised error. gc...
63,419,708
63,420,550
Determine type of template parameter in template
I am trying to implement a generic linked list and linked list iterator in C++. I have a node struct as follows template <typename T> struct Node { T m_data; Node<T>* m_next; }; I also have a linked list iterator that is a template so it can generate both regular and const iterators. template <typename NodeTy...
Using a typedef like this is the canonical way to do it and frequently done in the standard library. In fact, all LegacyIterators should define value_type, difference_type, reference, pointer, and iterator_category. Only then can their traits be accessed universally using std::iterator_traits. For example: // a simple ...
63,419,754
63,419,957
How to set the size of a vector member of a struct upon intialization?
I would like to set the size of a member vector when I construct a struct. The reason for this is that I have found that resize() can be very slow. Here is some minimal code trying to do what I want, but broken. #include <iostream> #include <vector> using namespace std; struct Struct_w_Vector { ~Struct_w_Vector()...
This will achieve what you need: Struct_w_Vector(int n) : n(n), h(n) {} This one is close, but the use of parentheses isn't allowed in standard C++, and furthermore, n isn't initialized at that point: vector<double> h(n, 0.0); So better drop it. Note that you probably don't need to store n, because you can always get...
63,419,808
63,420,060
Is Logical && a good replacement of if statement in a branchless POV
So, i saw sometimes code like this: some_conditions && something(); used instead of if(some_conditions) something(); Now, i was wondering which of the following versions is the most efficient / better to use: std::vector<int> v{}; v.size() < 10 && (v.push_back(2), 1); // using the comma operator since push_back does ...
The code segments you have are not branchless, since it still performs conditional logic based on the result of the first comparison. The code generated between the two will generally be the same. Any optimizing compiler worth their salt should produce identical assemblies. If you compare the output of GCC on godbolt, ...
63,419,890
63,419,945
Why is my char array not the correct length?
I have a program that will take in a key. This key shifts the plain text that many number of characters wrapping around z and preserving capitalization. Problems only arise when the ciphertext has the incorrect sized container. Why is the ciphertext array bigger then my planetext string? #import <cs50.h> #import <stdio...
char ciphertext[strlen(plaintext)]; is a variable-length array, which is non-standard in C++, see Why aren't variable-length arrays part of the C++ standard?. In any case, that declaration does not provide space for a null terminator. You need to add +1 for that: char ciphertext[strlen(plaintext)+1]; And then, make s...
63,419,983
63,420,005
Will reference to member variable get corrupted after object deletion?
Can I use ref after object deletion like shown in this example or is it unsafe? struct Object { int value; }; void function() { Object* object = new Object(); int& ref = object->value; delete object; ref = 50; }
It is unsafe. Any use of a pointer or reference to a member of a destroyed object is undefined behavior.
63,420,219
63,420,338
Why does my try catch exception stop working after the catch?
I have a segment of code here that runs partially. I am able to input both the characters (c, a, r) and numbers initially, but after entering a character input, the code no long accepts integer inputs. Why does this happen? I think it has something to do with my try catch exception. code: #include <iostream> #include <...
Once you've set flag to -1, it's never changed back to 0. The initialization you perform at the top of the file happens just once, before main is even called. So, after that, when you set it to -1 in the catch block, it never went to a part of the code that set it back to 0. As you saw, setting flag = 0 at the beginnin...
63,420,317
63,420,518
qt app crash on start after adding a library
I'm currently working on a QT application, targeting windows platform. After compiling and installing ITPP (it++ library) on my system, I've tried to add it to this project, but after linking .lib and adding header files, when I try to include and use it, application crashes on start without any output! What I get in a...
Cause The error code you get, -1073741515, is in hex 0xc0000135. According to the Microsoft documentation for status codes, there is a missing dll: STATUS_DLL_NOT_FOUND {Unable To Locate Component} This application has failed to start because %hs was not found. Reinstalling the application might fix this problem. Sol...
63,420,400
63,420,483
Does memory get freed when reassigning std::unique_ptr?
Given the following: { std::unique_ptr<char[]> foo; foo = std::make_unique<char[]>(100); foo = std::make_unique<char[]>(200); } Does the memory allocated in the first call to make_unique get freed when reassigning foo with the second call?
There is no leak in this code. operator= for std::unique_ptr will call the Deleter (in this example, delete[]) for the existing memory when transferring ownership from another unique_ptr that is being assigned to it. Per cppreference: std::unique_ptr<T,Deleter>::operator= Transfers ownership from r to *this as if by ...
63,420,533
63,420,984
Setting up ONNX Runtime on Ubuntu 20.04 (C++ API)
I am currently in the midst of trying to get my image processing programs to work on Ubuntu (coming from windows). I have successfully built and linked the OpenCV and Boost libraries to work with my cpp programs but I have yet to find any instructions as to setting up Onnx Runtime C++ on Ubuntu 20.04 other than using t...
For the default CPU version, you can download the tgz file here. For other flavors of ONNX runtime that are not available as tgz or NuGet (e.g. TensorRT), you can build them locally: ./build.sh --cudnn_home <path to cuDNN e.g. /usr/lib/x86_64-linux-gnu/> --cuda_home <path to folder for CUDA e.g. /usr/local/cuda> --use_...
63,420,827
63,503,242
Building TF micro hello world: make: *** [tensorflow/lite/micro/examples/hello_world/Makefile.inc:34: test_hello_world_test] Error 1
I am following the TinyML book by Pete Warden and Daniel Situnayake on how to deploy neural networks to microcontrollers with TFLite for microcontrollers. They closely follow the instructions at the end of this git repo. To try and check for errors, they propose testing the code on the development machine(i.e my PC), b...
I still have to open an issue on github as I don't think this is the expected behavior but here is a workaround that allows you to test your TF micro code on your development machine. First step is heading to the root of the git repo you just cloned. Then, instead of adding the test_ prefix to the target on make, just ...
63,421,060
63,421,117
How to use the Enter key in a modeless dialog?
I've been working on a WinAPI Project for university and we are asked to implement the full program in a dialog box. At first, I used a modal dialog box and everything worked fine, except that there was no icon in the taskbar for the dialog box because I created it directly on WM_CREATE and didn't make the main window ...
Your message loop needs to include a call to IsDialogMessage(): Determines whether a message is intended for the specified dialog box and, if it is, processes the message. ... When IsDialogMessage processes a message, it checks for keyboard messages and converts them into selections for the corresponding dialog box. F...
63,421,215
63,421,249
Second variable in for loop not incrementing
I'm trying to use two variables k and counter in a for loop. To be sure that they're actually working, I've made the program print the value of counter. However, it just repeatedly prints 0. Does anyone know how to fix this? Any help would be greatly appreciated :) for (int j : normal_day_in_months) { for (int k = ...
the reason this for (int j : normal_day_in_months) { for (int k = 0, counter = 2; k < j; k++, counter++) { if (counter == 7) { counter = 0; <<<=========== set counter 0 cout << counter << endl; <<<========== print counter } if (k == 12) { ...
63,421,288
63,421,363
Confused with chars in C++, issue memsetting
I am confused with characters and their respective pointers in C++. I have originally made a shell in C and I am trying to do it in C++. For some reason, I am getting a memory (coredump) when calling memset() and I am not sure why. I am confused on pointers. For example, in C the following runs fine: int main() { c...
char *valid[1024]; This is an array of 1024 char* -- it's not itself a buffer of characters. This can point to other buffers but it is not itself a buffer. It's perfectly legal, but very unlikely to actually be what was intended. Your first memset actually only erases one quarter of this array (or less, dependin...
63,421,306
63,422,182
Use of delete in union(x, y) in a BinomialHeap implementation
I'd like to get some advice on best practises for deallocating memory for data structures, using the BinomialHeap as an example. According to the 'Union' section in this link, as well as many other sources, http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/chap20.htm the method union(Heap x, Heap y) will destroy...
First of all, I'd say always use RAII for resource cleanup -- preferably through a std::unique_ptr rather than using manual delete invocation. From the way the Union operation is described, I don't think it has to actually destroy the object in the delete sense, but rather "destructively mutate" by stealing the content...
63,421,321
63,421,454
C++ Address of this is different when passed to function
I have a very interesting observation that may or may not be expected. I have two very complicated classes that each extend many other unrelated classes. For reference, one is a socket and one is a virtual device. During construction of the virtual device, I want to pass the address of the device to the a socket object...
Yes. Device has several base classes. When converting a Device* pointer to a OtherOtherClass* pointer, the value will be different since the new pointer will be pointing at the instance of OtherOtherClass within the instance of Device.
63,421,345
63,421,376
C++ std::reduce with array
int arr1[5] = { 1,2,3,4,5 }; int sum = reduce(arr1[0], arr1[5]); I wrote this code to use the std::reduce function with an integer array. How am I supposed to define the beginning and end of the array?
Use std::cbegin() and std::cend() on the array: #include <iostream> #include <numeric> int main(){ int arr1[5] = { 1,2,3,4,5 }; int sum = std::reduce(std::cbegin(arr1), std::cend(arr1)); std::cout << sum; } Demo