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
64,286,836
64,287,510
Do branch likelihood hints carry through function calls?
I've come across a few scenarios where I want to say a function's return value is likely inside the body of a function, not the if statement that will call it. For example, say I want to port code from using a LIKELY macro to using the new [[likely]] annotation. But these go in syntactically different places: #define L...
The story appears to be mixed for different compilers. On GCC, I think your inline likely function works, or at least has some effect. Using Compiler Explorer to test differences on this code: inline bool likely(bool x) { if(x) [[likely]] return true; else return false; } //#define LIKELY(x) likely(x) #define LIK...
64,287,464
64,287,802
I've noticed I have a problem with NOT passing arguments
I'm a self taught C++ programmer. I mainly learned off of UE4 and I still have a ways to go. I'm taking computer science in school and I'm in CSC 211 (thats the second phase I guess? if class numbers arent universal). I noticed though in class that my teachers, and other students often pass arguments a lot. By a lot, I...
There are two ways that I can think of to "not pass arguments": edit a class member variable edit a global variable (or at least a variable that is "global" to your function, meaning the function knows about it implicitly) If you want to know about the first bullet point (member vs reference parameter), that will be ...
64,287,476
64,287,611
C++20 concept for complex floating point types
I am trying to learn concepts in C++20 and I have a class that represents a data sample. I want to restrict this class to accept only floating point types, or complex floating point types but I can't seem to figure out how to handle complex values with concepts. Without concepts this is simple, but it allows way too ma...
Here's one solution that uses a partial specialization to check if T is a specialization of std::complex for floating point types: template <typename T> struct is_complex : std::false_type {}; template <std::floating_point T> struct is_complex<std::complex<T>> : std::true_type {}; With this, you can write the concept...
64,288,167
64,288,219
Cout works but ofstream doesnt
Okay so I am trying to return pairs of coordinates whos values are being read from an input file and displayed on an output file outFile. However, nothing is placed on to the outFile stream. ignore the area and distance values for now I'm not done fixing those The distance between and is 6.9 The distance between and...
The declarations ofstream outFile; in the functions main and getPoint are shadowing (hiding) the global ofstream outFile; and preventing it from printing things to output file. You should remove them to have the functions use the global outFile if you hate using reference parameter for some reason.
64,288,172
64,432,426
Emscripten await operator in C++. Returns undefined instead of string value
I have this function "IsBrave" in my main.cpp. If browser contains navigator.brave it calls the navigator.brave.isBrave() function with await. But when call from browser's console the exported function, it prints undefined value instead of "Brave" on Brave browser. In other browsers result is "Unknown". Tested in Brave...
Solved with this example EmbindAsync
64,288,223
64,298,857
Accessing C++ template class in cython
I have a template class called List defined in a file called containers.h: #include <iostream> #include <vector> namespace containers { template <class T> class List { private: std::vector<T> vector; public: List() {}; ~List() {}; void append(T* item...
It was just a silly mistake in compiling: in setup.py I passed "main.cpp" into the cythonize function instead of "main.pyx", and it didn't cause errors while compiling because I had another file called main.cpp.
64,288,246
64,292,398
Manual lifetime management, alternative to placement new
I have a piece of low-level code with callbacks: Init and Cleanup, and others. I don't control the arguments of the callbacks. I chose to use a global variable for managing the state, say class state. Here's a simple construct I can use: std::unique_ptr<state> s; void Init() { s = make_unique<state>(); } void Clean...
Expanding the comment into an answer: C++17 has the perfect tool for this: std::optional. It does exactly what you are doing, except it also tracks whether it currently has an object within the storage or not. Unless you are doing embedded and the additional size for the flag matters, it should be good: #include <optio...
64,288,386
64,291,457
How to rotate an object in certain range in OpenGL?
I have built a hammer, and I want to rotate the hammer quickly to strike a blow when I press a specific keyboard. I have used a timer function to achieve this. Right now my hammer can rotate 360 degrees when I press a specific keyboard, my goal is to rotate the hammer between 90 and -90 degrees. My code: bool stopRotat...
if zr is the rotation of your hammer then I see it like this: int zr=0,dzr=+1; // might be a float I do not know as you did not share bool stopRotation = false; void weaponController(int val) { if (stopRotation != false) { zr+=dzr; //the default angle is 0 if (zr>+90){ dzr=-1; zr=+90+dzr; }...
64,288,991
64,347,720
How to wait for thread to retire in C++?
Scenario: 2 Threads executing a function foo called from inside function bar but only one at a time executes foo. Like call it T1 and T2. T1 starts at some unknown time. It can be before OR after T2 starts. T2 is called with force restart parameter. If this parameter is set, it should induce retire of existing task(T1...
Answer: Predicate parameter in C++11 condition variable. https://en.cppreference.com/w/cpp/thread/condition_variable/wait
64,289,185
64,289,222
How can classes with `std::variant` members be copied safely?
The following sample builds and runs properly with the line Container container2(container1); removed. It appears the copy constructor for std::variant itself is deleted, which makes my Container's copy constructor implicitly deleted. Effectively, I'm asking: What is the proper way to store a std::variant as a member?...
cppreference has this to say about std::variant's copy constructor: Copy constructor. [...] This constructor is defined as deleted unless std::is_copy_constructible_v<T_i> is true for all T_i in Types. [...] In other words, it is not deleted unless one or more of the types that the std::variant can contain is not cop...
64,289,679
64,289,714
C++: basic questions on methods & "already has a body" errors
I'm working on a program that takes a very large block of seconds and attempts to break them up into days, hours, minutes, and seconds. Being new to C++, I'm attempting to split this problem up into 3 methods: main (intakes seconds from user, and passes findings onto 'calculation'), calculation (attempts to divide val...
Remove the {} from your declaration. Definition void results(int days, int hours, int mins, int secs) {}; This is called a function definition. A c++ function definition tells the compiler the actual body of the function. A function definition is also a declaration. Consider this to be the same as void results(int d...
64,289,766
64,289,787
How to write an generic object pool in c++
I want to write an generic object pool class and the object pool should be singleton, it is easy to access that object pool everywhere. template <class T> class Pool { T* _freeObjs; public: Pool<T>& getInstance() { static Pool<T> instance; return instance; } T* acquire() { ... ...
Your Pool<T>& getInstance() is not static. It needs to be a static function if you want to access getInstance without an object being created: static Pool<T>& getInstance() { static Pool<T> instance; return instance; }
64,290,713
65,065,737
Translating wrapped function like struct of C/C++.bt (Binary Template) to Java 8
Sorry, I have almost 20 years without touching C/C++. I Would like translate this code to Java 8, I found this Reference Manual. I was reading that in this link. You can read... Binary Templates are easy to write and look similar to C/C++ structs except they may contain if, for, or while statements as well as functions...
This code doesn’t quite translate to Java because it’s code-generating code, ie. code that some tool uses to generate the actual C-like code (in a nutshell), or code for a bespoke virtual machine that then implements the data extraction and data packing. The idiomatic way to do this in Java without writing a stand-alon...
64,290,732
64,290,830
What is the role of the @ symbol in c++?
I saw some code in glog like below: #if @ac_cv_have_libgflags@ #include <gflags/gflags.h> #endif @ac_google_start_namespace@ #if @ac_cv_have_uint16_t@ // the C99 format typedef int32_t int32; typedef uint32_t uint32; typedef int64_t int64; typedef uint64_t uint64; #elif @ac_cv_have_u_int16_t@ // the BSD format...
Those "@ac...@" tokens are for autoconf aka ./configure. They are replaced before the file is compiled, by the preprocessor called m4. After the m4 preprocessing is done on your example, but before the C preprocessing is done, it might look like this: #if 1 #include <gflags/gflags.h> #endif namespace google { #if 1 ...
64,290,799
64,290,860
c++ switch statement - jump between cases
In C++, can I do something like the code below? In a specific case, if some conditions are meet, can I jump to another case? switch (tag) { case 1: { // do something break; } case 2: { if(){ //can I somehow jump to case 1? } break; } }
No, not really. The closest thing you can get is a conditional fall-through. switch (tag) { case 2: { // Do things that need to be done for case 2 if(someCondition){ // if the condition was met, we stop here // and don't execute case 1! break; ...
64,291,020
64,291,052
Why am I getting wrong answer while counting number of lines in a file using getline()?
I want to count number of lines in a file.But here I am getting the number of lines in file+1 as answer. For example, if my file has 2 lines then my code will give 3 as answer. Here is my code- int c=0; void number() { cout<<"NO. OF LINES :"<<c<<endl; } int main() { string line; ifstream file("text1.txt");...
Explicitly checking .eof() is usually the wrong thing to do. Instead, check the result of getline(): int main() { string line; ifstream file("text1.txt"); if(file) { while(getline(file,line)) { cout<<line<< endl; c++; } } number(); } .eof() o...
64,291,082
64,291,103
C++| using lambda function to check if instream is opened successfully
I want to use lambda function to return a boolean value if the captured filestream returns a failbit (fs.fail() == nullptr). I tested with the normal controlflow and the stream does open successfully for extraction. However, the similar code with lambda function doesn't seem to work. How come? const std::string RATE = ...
Suppose the opening failed. Then if (fs.fail()) return false; will be false. The lambda will return false, and your condition won't be true, and won't print that the opening failed. You can change the lambda to [&]() { return fs.fail()); }
64,291,833
64,291,938
Built in mod operator vs arithmetic while loop in C++
I am relatively new to programming, and after going through some of the questions asked on this subject, I still could not find an answer. As I understand it, the % operator in C++ can be rewritten in a number of ways, some of which seem to perform better as indicated by some users here: Built-in mod ('%') vs custom mo...
Moulo usually is implemented through one or a couple CPU operations, so in general it's single operation: not counting auxilary instructions. But by definition it should be quite simple: int mult = a / b; return a - mult * b; E.g. on x86-64 clang compiles int mod(int a, int b) { return a % b; } into following cod...
64,292,232
64,292,594
How to replace std::is_same_v with std::is_same
I have this code containing std::is_same_v available with C++17. But I've stuck with C++14 due to toolchain limitation. template<class T, class O = T> using IteratorOnly = std::enable_if_t< !std::is_same_v<typename std::iterator_traits<T>::value_type, void>, O >; How can I replace std::is_same_v with std::is_same?...
The error got resolved by @Someprogrammerdude comment about a is_same_v helper variable template defined here. My final code is #ifdef My_OLD_TOOL_CHAIN template< class T, class U > inline constexpr bool is_same_v = std::is_same<T, U>::value; template<class T, class O = T> using IteratorOnly = std::enable_if_t< !...
64,292,783
64,293,406
C++ pointers and table
i'm learning C++ and i wanted to write a program that allocates 2D table using pointers. Here's my code: bool b_alloc_table_2_dim(int ***piTable, int iSizeX, int iSizeY) { if ((iSizeX && iSizeY) > 0) { *piTable = new int* [iSizeX]; for (int i = 0; i < iSizeX; i++) (*piTable)[i] = ne...
this example is good for you: int **dynamicArray = 0; dynamicArray = new int *[ROWS]; // memory allocated for elements of each column. for( int i = 0 ; i < ROWS ; i++ ) { dynamicArray[i] = new int[COLUMNS]; } // free the allocated memory for( int i = 0 ; i < ROWS ; i++ ) { delete [] dynamicArray[i]; } del...
64,293,092
64,293,927
error: request for member is ambiguous c++;
I've already reviewed several similar questions at StackOverflow, but nothing helps. I can't understand why the keyword using in my class NetflixCanada does not resolve the ambiguity. What I want to achieve: to access 2nd time a private method from NetflixUkraine class. Anyway, this is the code: #include <iostream> usi...
Your compiler can not distinguish between: NetflixCanada::NetflixUkraine::setBrowser and NetflixCanada::NetflixPoland::NetflixUkraine::setBrowser As mention in the comments, read about "The deadly diamond of death"
64,293,465
64,293,567
piecewise construction of a map with initializer list
trying to piecewise construct a map(in a map of maps) with initializer list, getting syntax error: std::unordered_map<int, std::unordered_map<int, int>> map; map.emplace(std::piecewise_construct, std::forward_as_tuple(1), std::forward_as_tuple(std::initializer_list<std::pair<int, int>>{{1,1}}));...
The key type in initializer_list needs to be const: std::unordered_map<int, std::unordered_map<int, int>> map; map.emplace(std::piecewise_construct, std::forward_as_tuple(1), std::forward_as_tuple(std::initializer_list<std::pair<const int, int>>{{1,1}}));
64,293,554
64,293,657
OpenGL glfw unable to draw a point using shader
I'm using GLFW for window context creation. I have a procs.hpp file that just loads the required opengl functions (like glCreateShader, glCreateProgram etc) using glxGetProcAddress. The program compiles successfully but there is no point on screen when I run it. Just pink background. Can someone point out the mistake? ...
The point size (glPointSize) of 10.0 is not guaranteed to be provided by the OpenGL Context. Get the point size range by retrieving the parameter GL_POINT_SIZE_RANGE: GLfloat pointSizeRange[2]; glGetFloatv(GL_POINT_SIZE_RANGE, pointSizeRange);
64,293,587
64,293,711
Getting memory address in c++ without ampersand (&) operator
I am implementing a default allocator for a simple containers library I'm writing, and I want to add an addressing-method that gets the memory address of the variable x that it works on, and that is also safe to use when x has overloaded the &-operator. Looking into the MSVC STL source code I see that the function __bu...
There is std::addressof for exactly this purpose
64,293,595
64,298,415
C++ Template Specialization / Partial and Full
I was trying to understand Template Partial and Full Specialization and have this below code: #include <iostream> using namespace std; //Template in C++is a feature. We write code once and use it for any data type including user defined data types. //What if we want a different code for a particular data type - Templa...
The comments cover the general principles, but there are specific questions here worth answering. First, a lemma: the template parameters of a function template need not be related to its parameter types: template<class T> T make_1() {return T(1);} auto v=make_1<std::vector<std::string>>(); // {""} template<class T,cl...
64,293,698
64,293,869
Manage/Delete cookies of working WebView2
I am running Edge WebView2 with some login page loaded there. I want to make an automatic login. To do that I need to remove current cookies. I can’t do that via js because they are httponly. For Edge beta browser I wrote simple Chrome extension for deleting cookies, but I can’t run an extension in WebView2 (or can?). ...
Update: There is now an official ICoreWebView2CookieManager that can be used for managing cookies. Microsoft documents this API extremely well -- so its best to check their documentation. With this new API, its just a matter of calling either DeleteCookie to delete a single cookie, DeleteCookies to remove all cookies f...
64,293,866
64,920,247
How to break in c++ code called from c# interop
Working with Visual Studio 2019. Calling c functions from c# is common but when there is a runtime error, I get a popup window as such: I would like however to actually break into the c++ code so I can debug it,in particular review the call stack, watch the local variables, add break points etc. How to achieve this ? ...
As suggested by Kevin Gosse, and detailed in MSFT documentation, just enable mixed-mode debugging: Enable mixed-mode debugging for a managed calling app Select the C# or Visual Basic project in Solution Explorer and select the Properties icon, press Alt+Enter, or right-click and choose Properties. Select the Debug t...
64,294,455
64,294,514
Why is my code doesn't print the invalid value to inform the user?
In this program I'm trying to print the single value which is identified as invalid by the program. For example the any non-digit value is invalid and the program must print it along an error message which is defined. My code: #include <iostream> using namespace std; void Welcome(); void botVerification(); bool isNumbe...
Your program exits before it reaches the "cout" in your "bool". bool isNumber(string botV) { int badIndex = 0; for (int bcounter = 0; bcounter < botV.length(); bcounter++) if (!(botV[bcounter] >=48 && botV[bcounter] <= 57)) { return false; badIndex = bcounter; ...
64,294,574
64,298,438
Remove Move and Close commands from Windows' system menu without losing functionality
I want to remove the Move and Close commands from the system menu in a Windows dialog-based application without losing the functionality of those commands or removing the system menu. (I'm using MFC, but open to a pure c++ solution.) The following will remove the Move command from the system menu: CMenu* pSysMenu = Get...
You can remove those items from the system menu in the WM_INITMENUPOPUP handler. This, as you noticed, will disable related functionality in your window. However, you can restore those items in the handler of lesser-known WM_UNINITMENUPOPUP message. Add this to your dialog's class definition: afx_msg void OnInitMenuPop...
64,294,983
64,323,197
WIC HEIF HEIC image decoding C++
Windows Imaging Component is used for decoding heif images. However extra apps from the microsoft store (heif image extension, hevc video extensions) are required for a successful decoding of the images. Without them the WIC api returns blank image. Now I want to be able to programatically determine whether the heif fi...
Since the HEIF decoders are still recognized on Windows that can't decode them this is the best hack imo: In order to decode HEIF images HEVC video extension should be installed on the machine. So the right check is to see if there is any decoding type matching the HEVC input MFStartup(MF_VERSION); IMFActivate** activa...
64,295,191
64,295,396
cudaMemcpyAsync() not synchronizing after second kernel call
My goal is to set a host variable passed by reference into a cuda kernel: // nvcc test_cudaMemcpyAsync.cu -rdc=true #include <iostream> __global__ void setHostVar(double& host_var) { double const var = 2.0; cudaMemcpyAsync(&host_var, &var, sizeof(double), cudaMemcpyDeviceToHost); // identifier "cudaMemcpy" is un...
What is incorrect about my expectations? If we ignore managed memory and host-pinned memory (i.e. if we focus on typical host memory, such as what you are using here), it's a fundamental principle in CUDA that device code cannot touch/modify/access host memory (except on Power9 processor platforms). A direct extensi...
64,295,404
64,295,533
How can I delete first and last characters of strings using member functions of std::string, without using remove_if, erase, etc?
EDIT: This question had been solved as of 1 PM on October 10, 2020. Thank you! I was wondering how to remove the first and last special characters of a string variable "words", without touching the special characters in the middle and using remove, and erase-remove_if idioms. For example, the string @*Case-closed!! sho...
You can combine find_first_of with find_first_not_of to delete the first special characters, and combines find_last_of with find_last_not_of to delete the last special characters. Or if you want to delete until alphabet characters you can do one loop to search for the first and last alphabet characters, and substr that...
64,295,805
64,297,064
locked into a circular reference with templated class
I have this kind of architecture : Bar.h #ifndef _testCircularInclusion_bar_h_ #define _testCircularInclusion_bar_h_ #include "foo.h" #include <string.h> class Bar{ public: Foo foo; Bar() : foo(*this){} std::string SayHello(){ return "Hello";} }; #endif And now Foo.h: #i...
This sort of interdependency is best solved by using just one header file: #ifndef INCLUDED_FOO_BAR_H_ #define INCLUDED_FOO_BAR_H_ #include <iostream> #include <string> class Bar; class Foo{ private: Bar& bar; public: Foo(Bar& _bar) : bar(_bar){} template<class T> T Add(T t , T a...
64,296,558
64,296,750
Force static method in class based on interface in C++
I am making a vector-class which has the option to take an allocator as a template parameter. To ensure a user-defined allocator works with the vector, I provide an interface which sets the minimum requirements for a given allocator. Since the allocator is just used to allocate and deallocate, it has no member variable...
It's possible to require a class with certain methods defined as static using SFINAE. The following example uses C++20's concepts, but with a little bit of work can be adapted to use pure SFINAE, since that's the only thing that's required here. This example defines a concept has_static_methods that requires a class to...
64,296,702
64,296,730
Problems with multiply defined symbols found (LNK 1169)
I'm struggling with breaking up working code that exists in 2 files (A main.cpp and header.h -> A main.cpp, functions.cpp, and header.h) My problem seems to completely revolve around this struct and my use of the *root pointer: struct avl_node { int data; struct avl_node* left; struct avl_node* right; }*roo...
In the header: struct avl_node { int data; avl_node* left; avl_node* right; }; extern avl_node* root; In exactly one source file: #include "ThatHeader.h" avl_node* root; Currently, you put the definition of root into the header. Which means that every source file that includes this header ends up contain...
64,297,365
64,297,498
Making a Boolean trying to print out uppercase letters
The objective is to make it so that all uppercase letters are printed out in a string, however, I must keep the bool function and use it within my code. I have resolved some issues from the past but ran up with a issue that is preventing me from fixing it. Test cases are "HEllO" -> "HEO" "my" -> "" "NAME" -> "NAME" "Is...
I updated your program so that it works: #include <iostream> using namespace std; bool isUpperCase(char ch){ if(ch >= 'A' and ch <= 'Z'){ return true; } return false; } int main() { string a = ""; cin >> a; string c = ""; for(int i = 0; i < a.length(); i++) { ...
64,297,393
64,330,309
How does the erase-remove idiom work with ranges/constrained algorithms?
I'm trying to use a c++20 constrained algorithm for the erase-remove idiom: std::vector<int> v; v.erase(std::unique(std::begin(v), std::end(v)), std::end(v)); but when I do a simple transformation: v.erase(std::ranges::unique(v), std::end(v)); I get an error that the arguments to erase don't match: error: no matching...
Another option would be decomposing the subrange returned by std::ranges::remove/unique, and use those iterators: auto [Beg, End] = std::ranges::remove(v, 42); v.erase(Beg, End);
64,298,166
64,343,992
When requesting WebGL2, any browser gives me a WebGL1 context (emscripten)
I am trying to receive a WebGL 2.0 context. I am using -s USE_WEBGL2=1 -s MIN_WEBGL_VERSION=2 and have tried adding -s FULL_ES3=1. Compiling gives neither warnings nor errors. I use the GLES3/ headers. Furthermore: EmscriptenWebGLContextAttributes atrs; emscripten_webgl_init_context_attributes(&atrs); atrs.alpha = true...
So finally I have tried everything, and found the solution. My problem was, that I had been compiling with a makefile, and that my .cpp turned to .o files with all the appropriate flags, but in the linker step, you also need to specify those flags, or WebGL2.0 won't be available.
64,298,264
64,298,362
C++ - std::list.erase() not removing element
I am having a small issue with a bit of code for a school assignment (I know that's shunned upon here, but I locked myself into using the std::list library and am paying for it). I have a function that has a list of pointers to classes passed into it along with a particular ID belonging to one of those classes that I w...
kill_doco(std::list < DOCO* > docolist this creates a copy of the list. This copy is a list of pointers. You proceed to modify the copy of the list, and delete an element in it. The original list (which you copied) still has the original pointer, which is now pointing to a deleted object. The easy fix is: kill_doco(s...
64,298,405
64,298,476
Efficient Kullback–Leibler calculation
I am looking to implement KL Divergence in C++ efficiently. (CPU Only for now). Much like AES or FTT (Fast Fourier transform) whereby use of a common function has lead to hardware level optimizations (Intel AES and Intel FTT). Is there anything similar for natural log, or slightly higher level efficiencies (ASM/C) that...
You can use SSE instructions to calculate the logarithm of many values in parallel. But whether you can actually make use of those instructions depends heavily on how the rest of the calculations you are going to do depend on the logarithms you calculate, so it is not possible to give a more specific answer.
64,298,466
64,308,963
How to emit QTextTexid::textChanged signal only in certain cases selectively?
Can you trigger the textChanged signal only for certain cases? for example triggering it for inserted text, inserted space characters but not backspace? I am running checks for typed characters inside a QTextEdit every time the text changes and based on the results highlighting text inside a read-only QTextEdit in the ...
As per OP's request, I am posting a solution that is a class called CustomTextEdit which is subclassing QTextEdit. It is hooking to keyPressEvent() and checking the key that was pressed. If it was other than Backspace then the custom signal keyPressed() will get emitted. class CustomTextEdit : public QTextEdit { Q_OB...
64,298,802
64,305,037
Memcpy data directly into std::vector
Is it legal to directly copy data into a std::vector using memcpy? Something like this: char buf[255]; FillBuff(buf); std::vector<char> vbuf; vbuf.resize(255) memcpy(vbuf.data(), &buf, 255);
To answer your question yes, it does work but that is due to the implementation of std::vector<char>. For non-POD types and types for which std::vector has a particular template specialisation that affects the memory layout (std::vector<bool>), it will not work. This is why you should use std::copy, it will behave corr...
64,298,986
64,299,026
Count capital letters from file c++
// C++ program to count the uppercase #include<iostream> #include<fstream> #include <string> using namespace std; // Function to count uppercase int Count ( string str ) { int upper = 0; for (int i = 0; i < str.length(); i++) { if (str[i] >= 'A' && str[i] <= 'Z') upper++; } return upper;...
You are overwriting the value of uppercase variable on the next iteration: uppercase = Count(str[i]);. Just use += instead and remove those if (Count(str[i]) == X) uppercase++; Additionally, that array of 1001 strings, of which you only use the first entry, isn't needed at all. You can just declare string str and repla...
64,299,071
64,318,472
lazy-evaluation in Xtensor
In the following function using xtensor, I was expecting the compiler to express the computation graph to auto z = 3.0 * u + 100 * xt::cos(u); and evaluate the result at xt::xtensor_fixed<T, xt::xshape<nn>> out = z; when assigning the expression to an exact tensor. template<typename T, size_t nn> T func_cos(xt::xtensor...
When you write auto z = 3.0 * u The type of z encodes the operation, it is something like xfunction<multiplies, scalar<double>, xtensor_fixed> This class does not hold any value, so it is not possible to assign it anything (even if it is a computed assignment). Now even if iw was possible, consider the following expr...
64,299,656
64,299,736
How to return an aggregate initializer as templated struct?
I want to return an aggregate initializer when the return value is templated: Msg { std::string msgId; std::string data; }; template <typename T> struct RetVal { int code; std::optional<T> msg; }; RetVal<Msg> fn1() { Msg msg{.msgId = "123", .data = "my data"}; // C99 Designator initialization return {...
Your code is valid in c++20, and should be compiled by a conformant compiler. Yes, you can return a Retval<Msg> with some of the fields missing, like this: return { .code = 200 }; // or return { .msg = msg }; Here's a demo that compiles with /std:c++latest.
64,299,670
64,299,692
Definition of a function outside of a generic class is producing a compilation error
The context I've written the following minimal working example #include <iostream> template <typename T> struct A { enum myenum {faa, fee, fii}; myenum m_m; A(const myenum& m = faa): m_m(m) {} }; int main() { A<int> a1; A<int> a2(A<int>::fii); std::cout << a1.m_m << std::endl << a2.m_m << std...
You have to specify the default argument in declaration, and remove it from the definition. For member functions of class templates, all defaults must be provided in the initial declaration of the member function. template <typename T> struct A { enum myenum {faa, fee, fii}; myenum m_m; A(const myenum& m = faa)...
64,300,349
64,300,389
How can I change malloc to new notation in c++
I have this portion of c++ code, below there are two lines using malloc and I want to change it to new notation. struct CodingTree* createCodingTree(unsigned int capacity){ struct CodingTree* cTree = (struct CodingTree*)malloc(sizeof(struct cTree)); cTree->size = 0; cTree->capacity = capacity; ...
And seems like it's working, but for the second one, I have no idea on what would be the equivalent new for reference adding the CodingTree and BinaryNode structures. It seems like what you want is: cTree->array = new BinaryNode*[cTree->capacity]; Now this requires you to also change free into delete (and delete[] f...
64,300,432
64,308,688
Where does the get_input_port method reside in drake?
I'm trying to find the template function that this call is referring to https://github.com/RobotLocomotion/drake/blob/master/examples/pendulum/pendulum_geometry.cc#L102 const auto& input = get_input_port(0).Eval<PendulumState<double>>(context); I've been trying to find the import that contains this call but I'm at...
That's at https://github.com/RobotLocomotion/drake/blob/master/systems/framework/system.h#L927 (Because PendulumGeometry derives from LeafSystem.)
64,300,495
64,301,377
How to use Sphinx in a Python project that depends on being built in place?
I have a large mostly Python project that I am trying to document. Part of this project is dependent on C++ source code which is made accessible via Cython. When running the code like normal it runs fine, but in trying to do auto documenting with Sphinx I have run into issues. I think this guy had the right idea, but...
You would want to add the step from the answer you linked as part of the Makefile generated from sphinx to before any sphinx specific command was executed. # Minimal makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ...
64,300,636
64,301,075
C Raw Sockets HTTP Request Always Returning Status 400
I normally write a bunch of Typescript/Javascript code, and I took the HTTP protocol for granted. I decided to write a C++ program that can make GET requests to a given URL with sockets to learn more about how HTTP works. I've coded up what I think is the basic structure of what I should be doing: Create a socket Conn...
>>>> Request sent: GET /links HTTP/1.1 This is not a valid HTTP request. It is missing the Host header with the target domain name, i.e. it should be at least something like this GET /links HTTP/1.1 Host: www.example.com Apart from that your code simply tries to read data until the server closes the connection or the...
64,300,753
64,300,921
C++ Function full specialization giving error
I have the below code to understand function full specialization concept: //Function Full specialization is legal but not partial class Wrapper { public: void setValue(int x) { } }; template <typename R, typename T> R* create(T t) { return new R(t); } template <> Wrapper* create<Wrapper, int>(int n) // fully s...
template <> char* create<char, char>(int n) { return (char*)"HI"; } And template <> const char* create<const char*, int>(int n) { return "Hi"; } Are not template specializations: the former doesn't have a conforming argument and the later a conforming return type. template<> char* create<char, char>(char n) /...
64,300,831
64,320,847
Get Gtk::DrawingArea size, before signaling draw
I want to draw some frames, one by one in a Gtk::DrawingArea. At the beginning of application, I need to get the size of DrawingArea, to allocate a RGB buffer, hewever, DrawingArea::get_width() and DrawingArea::get_height() return 1. My code is based on https://developer.gnome.org/gtkmm-tutorial/stable/sec-drawing-cloc...
I was able to trace size changes based on Scheff's comments: #include "clock.h" #include <gtkmm/application.h> #include <gtkmm/window.h> int width_ = 0; int height_ = 0; bool resized_ = false; void check_size() { if (resized_) { resized_ = false; // Apply size changes to resources using width_ and h...
64,300,946
64,301,249
My code is right but not accepted by Leetcode platoform. (ZigZag Conversion)
It is a leet code problem under the subcategory of string, medium problem. Query: My program is returning right result for all the test cases at the run time and but when I submit, same test cases are not passing. I also made a video, click here to watch. My Code is: string convert(string s, int numRows) { ...
I believe the issue might be your un-initialised arrays / variables. Try setting initialising your array: int arr[1000][1000] = {0}; live example failing: https://godbolt.org/z/dxf13P live example passing: https://godbolt.org/z/8vYEv6 You can't rely on the data that is in these arrays so initialising the values is qu...
64,301,390
64,301,514
getting error Exception thrown: read access violation
I am currently working with an array of Node pointers. I want to make a node at that index (aBet[]) if that index of that Node array is pointing to null. However I get an **error on the if statement that says: "Exception thrown: read access violation. Node was 0x1110112." I also made a default constructor to make the v...
you do not initialize currNode so currNode->aBet has an undefined behavior [edit after remarks] Your definitions are strange, for me aBet must be an attribute of Dict rather than of Node, also currently Node is quite useless because only memorize pointers to Node If you just want to memorize words you just need to defi...
64,301,458
64,304,626
Numbers of common distinct difference
Given two array A and B. Task to find the number of common distinct (difference of elements in two arrays). Example : A=[3,6,8] B=[1,6,10] so we get differenceSet for A differenceSetA=[abs(3-6),abs(6-8),abs(8-3)]=[3,5,2] similiarly differenceSetB=[abs(1-6),abs(1-10),abs(6-10)]=[5,9,4] Number of common elements=Inters...
If n is the maximum range of a input array, then the set of all differences of a given array can be obtained in O(n logn), as explained in this SO post: find all differences in a array Here is a brief recall of the method, with a few additional practical implementation details: Create an array Posi of length 2*n = 2*...
64,301,561
64,301,615
What exactly is decltype(std::get<0>(tup))?
I am currently learning metaprograming in C++, and I'm trying to see whether an element of a tuple is a pointer. I tried this approach: int a = 3, b = 4; auto tup = std::make_tuple(&a, b); std::cout << std::is_pointer<decltype(std::get<0>(tup))>::value; //prints 0 I thought this was strange, so I examined the type cla...
std::is_same/std::is_same_v can be very helpful in TMP and, when looking for types being equal to other types, it's invaluable when used in conjunction with static_assert. With the following code you can see that std::get gives you a reference to the element of the tuple (as confirmed by cppreference's page on std::get...
64,301,677
64,304,429
How to Render a Bitmap from BITMAPINFOHEADER and BYTE using Direct2D
I am trying to create a C++ application which actually captures the bitmap from magnifier and render it using Direct 2d. I am currently having the code to save the bitmap from magnifier to a file. but what I need is to do is to draw that bitmap to my window using direct 2d instead of saving it to file. The magnifier re...
Here is how you can use mag's bitmap with Direct2D. You don't need BITMAPINFOHEADER since mag format is the same as DXGI_FORMAT_B8G8R8A8_UNORM: BOOL MagImageScaling(HWND hwnd, void* srcdata, MAGIMAGEHEADER srcheader, void* destdata, MAGIMAGEHEADER destheader, RECT unclipped, RECT clipped, HRGN dirty) { // note: all...
64,301,914
64,302,266
OpenGL output of simple vertex shader OK but results in a black screen
Yes, this is another "Black screen in OpenGL, help!" post. I have done my due diligence, here is what I have tried so far to diagnose: Checking for any and all errors during my window initialization with GLAD/GLFW Checking for any shader errors during compilation and program linking Checking for GL errors after every ...
You need to write the gl_Position in the vertex shader. gl_Position cannot be replaced with a custom output variable (like gl_FragColor in the fragment shader): #version 330 core layout(location = 0) in vec3 inPos; void main() { gl_Position.xyz = vec4(inPos, 1.0); } See OpenGL Shading Language 4.60 Specification ...
64,301,946
64,315,422
How many numbers that you can print in 1 second
I want to print n numbers to stdout with a maximum time limit of 1 second and n can be up to 100000. I tried to concatenate the output as a string and then stream this to cout but it did not work. My code: #include <iostream> using namespace std; int main() { int n = 100000; for(int i=1;i<=n;i++) cout<<i<...
Based on your screenshot, it appears to me that you are using ideone.com to compile and run your code. Per the FAQ: What is the size limit for the source code, input and output? 64 kB. Your output exceeds the size limit when it reaches the 5th digit of the number 12774. Try compiling and running it on your local mach...
64,302,195
64,406,529
'Unable to open cygwin.S' shows up at a certain value for a variable
My program runs a finite element method on a 2D grid. The code works fine for grids smaller than 195x195, but whenever I try to make it bigger the following is shown: Unable to open 'cygwin.S': Unable to read file 'c:\mingw810\src\gcc-8.1.0\libgcc\config\i386\cygwin.S' (Error: Unable to resolve non-existing file 'c:\mi...
I think it's a "stack overflow" issue. It is related to memory allocation in C++. For variables inside a function (main(), for example), their size cannot exceed the "stack" size. The "stack" size is probably determined by the compiler or the OS. Typically the stack size is just 1 MB, 2 MB or so. I run into the same is...
64,302,514
64,304,785
How to printf std::vector<>::size_type?
std::vector has a member type size_type. What is its printf format specifier? Note that size_type is not identical to size_t. https://en.cppreference.com/w/cpp/container/vector https://en.cppreference.com/w/cpp/types/size_t https://en.cppreference.com/w/cpp/io/c/fprintf
What is its printf format specifier? No one knows. It's not specified what std::vector<?>::size_type exactly is, except that it is a "unsigned integer type" int C++ Container Library, General container requirements. Because printf format specifier depends on the type, it all depends on particular implementation. It m...
64,302,998
64,303,065
random() and randomize() not working in vs code(cstdlib & ctime is included)
#include<iostream> #include<cstdlib> #include<ctime> using namespace std; int main(){ system("cls"); cout<<randomize(); cout<<random(); return 0; } It is giving an error: identifier "random() is undefined","randomize() is undefined". I have just installed VS code and mingw and have set the path of min...
You are probably looking for: std::srand() to set the seed (randomize)- but you'll have to provide an argument to make it more random std::rand() to get a random number (random) But if you want to do more elaborate work with random numbers in C++, it'll be worth to have a look at the real C++ <random> library and at ...
64,303,697
64,303,810
Unable to access a protected variable from a friend fonction
When I try to access a protected variable in two classes that have this function as a friend, it says that they are inaccessible: class Item { private: friend void Block::getMined(Mob& m); protected: std::string Name; double As; double Ad; double MineWood; double MineStone; ...
A first look, there are some syntax errors, at the end of each class you have to add semicolon. That's said, you're calling the function getMined from Bloc class which is (the class) declared and defined later, at this point you need a forward declaration at the top of your Item class class Block; and also your class M...
64,303,701
64,304,134
Instantiate member from class inside library inside current class?
I feel like I'm missing something obvious here and need it pointed out. I'm trying to create an instance of a struct that's a member of a class contained within a library that's been included in the current file, but inside a class I've defined myself. If I do this outside of the class, it works, but inside the class i...
Yes it is possible to default initialize members, although in the C++ standard in-class initialization can only use = or {}. This is better answered here. Using parentheses is confusing since it looks like a function declaration. IntelliSense is most likely complaining about error types since it thinks you are declarin...
64,303,868
64,306,245
accessing the pixel of an image going wrong in Mat
I am implementing a simple demosaicing algorithm. I think I am accessing a pixel in the right way, but the output is showing that I am accessing it in the wrong way. I was supposed to get this as an output but instead, I am getting this It is zooming in on the left top corner. My code is pasted below pixel demosiac_i...
The problem was with the usage of imread(), even though, the image was single channel one, imread by default read it as an RGB image. when I used the flag -1, which suggests the data should be read as specified by the image, it worked perfectly. imread("path_to_image",-1); thanks to @Micka for suggesting the solution....
64,304,078
64,304,079
How to access Debug and Launch Settings if greyed out?
I'm trying to edit my launch settings for a CMake project in Visual Studio, but the option is greyed out. I can manually open launch.vs.json file, but the settings there won't behave. Probably the greying out and the fact that the settings won't behave are linked. I am running the x64-Debug configuration. This is how l...
The Configure CMake debugging sessions documentation says that If you don't have a debug target selected, this option is grayed out. Running the x64-debug configuration sounds like the option shouldn't be greyed out, but it still is because you're debugging the Current Document as a target, which Visual Studio doesn'...
64,304,254
64,304,424
In tight context: Safe to use pointer to container-element?
In below code I am filling a map m with elements from another container vv. I am using a pointer to the current element in the map and that element/object is being further manipulated. struct obj_t { vector<int> w1, w2, w3, ... }; map<int, obj_t> m; vector<vector<int> vv; for (vector<int> &v : vv) { obj_t *p = &...
I understand that you should normally not use pointers to elements in containers, since these may be moved around by other parts of the "program" / "runtime". ... The suspicion that it might not be like that would come from something like this where some_large_allocation() may cause memory objects to be relocated by t...
64,304,348
64,304,504
Why is this merge sort implementation not working properly?
The following is my merge sort implementation, what it does is it takes an array of pairs of integers and sorts them according to second element in the pair (ties are broken by first element in pair and all elements are distinct) void mer(vector<pair<int, int>> a, int l, int m, int r, vector<pair<int, int>> res) { ...
There are multiple problems in your code: the vector objects should be passed by reference. res is not the destination of the solve() function, but rather an auxiliary vector to act as temporary storage for mer. Calling it tmp would be less confusing. the r index in solve() is excluded, so the test fo a slice with l...
64,304,437
64,304,477
Bug casting from bool* to void* to int*
Often in C++, one has a parameter void* user_data that one can use to pass an arbitrary type. I used this to pass an array of booleans. However, I had a bug where I cast from bool* --> void* --> int* and I got weird results. Here is an example. #include <iostream> int main() { bool test[2] = { }; void *ptr = s...
static_cast<int*>(ptr)[0] casts ptr to int* and reads the first element. Since the original array is only 2 bytes, you're reading outside it (because you're reading a 4-byte int) and invokes undefined behavior, unless int is a 2-byte type on your system. You're also violating the strict aliasing rule by accessing a typ...
64,304,519
64,304,895
static function in template struct not using default template argument
I have this code which I wasn't able to compile and I was wondering if there's a way around it. Error is - Argument list for class template "a" is missing. //not compiling one template <typename T = int> struct a { static T x; static T function(T number) { return x = number; } }; template <typename...
is there a way to do without a<>, just a? In case your class template a is only intended to provide utility static functions and not act as an object (with state), you could use delegation via a function template, which returns a (dummy) a object, followed by using the fact that an object of a given type, say A, can ...
64,304,721
64,305,752
Binary String Question to find maximum power of 2
We have given a binary String of length n,we can cyclically shift this string any number of times.Let X be the decimal representation of string s. Find the greatest power of 2 with which X can be divisible with, if it can be divisible with arbitrarily large power print "-1".For the result, you are required to print ...
I have some difficulty to understand the logic of your code. In practice, it failed on about all cases I have tested. Moreover, it seems quite over-complicated. It is enough to count the number of consecutive zeros. We just have to pay attention that this calculation must be performed in a cyclic way. For example, if s...
64,305,249
64,305,353
Accessibility of inner class
#include<iostream> using namespace std; template <class T, class U> class Enclosing { private: int x; public: class Nested; Nested setnested (int x){ Enclosing::Nested* temp; temp->A->x=5; return *temp; } class Nested { Enclosing *A ; ...
This code runs well but if I eliminate template sign of class Enclosing, errors appear. Actually, the same error applies to the template version, it's just that the access specifier of A is not checked until setnested is instantiated. If you add these lines to main: Enclosing<int,int> e; e.setnested(42); you get the...
64,305,510
64,305,727
How to properly declare a method that only takes a lambda?
In the following example, I would like a traverse method that receives a callback. This example works perfectly as soon as I don't capture anything [] because the lambda can be reduced into a function pointer. However, in this particular case, I would like to access sum. struct Collection { int array[10]; void...
Lambda types are unspecified; there is no way to name them. So you have two options: Make traverse a template (or have it take auto, which is effectively the same thing) Fortunately this is a completely normal and commonplace thing to do. Have traverse take a std::function<void(int)>. This incurs some overhead, but d...
64,305,897
64,311,447
Using fmtlib, zero padded numerical value are shorter when the value is negative, can I adapt this behaviour?
I am using fmtlib to format strings and numeric values but I have problem with negative integers. When I pad the value with zeroes, I expect a consistent number of zero no matter the sign of the value. For instance, using a padding of 4, I would like the following: 2 to be returned as "0002" -2 to be returned as "-000...
There's certainly nothing in the documentation for either fmt or Python's str.format (which fmt's syntax is based on). Both only state that padding is "sign-aware". This question asks for the same functionality for Python's str.format. The accepted answer there is to move the length to an argument, and make it one larg...
64,306,021
64,306,154
Parsing string input separated over several lines fails
I am trying to parse a string input and my way of parsing it is not behaving the way I want it to. I fail to see where I am going wrong, and hopefully you can guide me a bit. The input is a sequence of triple string inputs like the following 1 4 1 2 1 2 2 4 1 2 4 2 The input is provided by a service which I have no co...
getline operates on an istream. It reads the istream until it encounters the delimiter character or end of file. It populates the string with all characters up to the delimiter, not including the delimiter, and advances the stream to one past the delimiter. You're already being given the input line-by-line, but then re...
64,306,338
64,306,442
How can I test if my method is returning the right vector?
I'm new to C++ and I created am creating a game for my class. The game has a player who has territories, and I need to create a method that that returns the vector list of the player's territories. Player::Player(std::vector<Territory> territories) { _territories = territories; } std::vector<Territory> Player::t...
Presuming Territory has a toString() method (if not create one that returns the territory name) std::string Territory::toString() { return name; } Just iterate through the std::vector and display each Territory #include <iostream> int main() { std::vector<Territory> myTerritories; // populate with Territo...
64,306,452
64,306,552
Why is a non-template class used as a nested member an incomplete type?
#include<iostream> using namespace std; template <class T> class Enclosing { private: int x; public: class Nested { Enclosing A ; public: void NestedFun() { cout<<this->A.x; } }; }; int main() { Enclosing<int>::...
When Enclosing is a template, the definition of the type of A in Nested is not needed until Enclosing is instantiated, e.g. when you do: Enclosing<int>::Nested temp; At this point, since the instantiation is happening outside the definition of Enclosing, the definition of Enclosing is already complete, and so this com...
64,307,222
64,307,248
Why is the value being added in do-while loop meanwhile it should get out of the loop?
I have a simple program which asks the user about the age and based on that, it generates a total price at the end, but once the user inputs -1 - it should get out of the loop and display the result. The problem I'm having is that it counts the -1 entry into peopleCounter and the price too, how do I avoid that? #includ...
You can rewrite the do-while as a while, and then prompt the user, get an input, and check the input's validity, all inside the while condition itself. This way, you never enter the loop if the age is -1: while (cout << "Enter the age " << endl && cin >> age && age != -1) { if (age < 16) { to...
64,307,280
64,308,391
LNK2019: unresolved extrenal symbol when using std::ifstream
I have a problem with using std::ifstream in c++. I'm using Visual Studio 2019. Every time I want to initialize the std::ifstream object it gives me these errors: file: Shader.obj LNK2019 unresolved external symbol __imp___invalid_parameter referenced in function "void * __cdecl std::_Allocate_manually_vector_aligne...
The problem was that I have linked some realease libraries(glew32.lib and glfw32.lib) mixed with debug libraries. So in Project Properties->Linker->General I have changed Additional Library Directories to the debug libraries and in Linker->Input changed the file names. Thanks @drescherjm and @1201ProgramAlarm for advic...
64,307,770
64,309,934
Hashing the arrangement of an array
I am trying to write a function which takes an array of integers, and outputs a hash value to signify their arrangement order. The hash key should be as small as possible (we're dealing with embedded and space/execution optimization is critical) template<size_t N> int CalculateHashOfSortOrder(int* itemsBegin) { // ...
An equivalent hash goes something like this for [ 40, 20, 10, 30 ] 40 is greater than 3 of the subsequent values 20 is greater than 1 of the subsequent values 10 is greater than 0 of the subsequent values 30 has nothing after it, so ignore it. That is a pair nested loop of time Order(N^2). (Actually about 4*4/2, whe...
64,307,772
64,308,684
Accidentally edited a windows header, now nothing compiles
I was writing a program that used the windows midi interface, and at some point I was following the definition of a symbol and ended up in one of the windows headers. I must have accidentally edited it before closing it because now when I try to compile my code, I get literally hundreds of errors like: Severity Code...
I found the issue after digging some more. I had #include "windows.h" #include "mmsyscom.h" In a header file, and after my code formatter ran it swapped their order so that they were alphabetical. Turns out mmsyscom.h relies on a bunch of definitions in windows.h which was the source of the issue. I'm not sure why I s...
64,307,817
64,311,148
StretchBlt draw a blank bitmap
Im using the default Windows.h functions to draw. I use StretchBlt to draw a bitmap. but it(StretchBlt) draws a blank bitmap (i.e its total blackness if I dont use WHITENESS in rop). I have a struct to draw the components The section of the VM_PAINT PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); SetStretchBltMode(hdc...
As @IgorTandetnik pointed out, SelectObject expects HBITMAP instead of PBITMAP. Additionally, make sure the bitmap is a valid bitmap. For example, if you load the bitmap using LoadImage, make sure the return value is a valid handle instead of NULL. The following is working example you can refer to: HBITMAP HBit...
64,307,876
64,308,273
Would calling the default parameter with `new` cause memory leak?
I am trying to write a function that returns the center point of biggest detected object. No problem here. The issue is that I also want to return the foreground mask from parameters, if the user wants to use it. In order to handle this situation, my solution is as following: cv::Point detect(const cv::Mat &img, cv::Ma...
Yes, that introduces a memory leak. You might instead consider using a tuple return value: std::tuple<cv::Point, cv::Mat> detect(const cv::Mat &img); or making mask a pointer: cv::Point detect(const cv::Mat &img, cv::Mat *mask = nullptr); You could also try to keep the same signature with a cast. This is ugly but it ...
64,308,060
64,308,143
Assigning unsinged int (with .size()) to 1D float vector
I am a complete newbie in programming and my question might be completely trivial to you. I tried a lot but just could not figure out why this program is not giving me an error. This code is part of one of the exercise I have been doing. Part of the code here is to assign number of rows in vector vec1 to variable rows ...
std::vector::size_type is the type of the variable that stores the size of the container. What you want is std::vector::value_type. Even then it will compile because an unsigned int can be assigned to a float.
64,308,089
64,309,028
Use concepts to check if a global function exists
I can create a concept that checks the existence of a member function called to_string() that returns a std::string in a struct/class. template<typename T> concept method_to_string = requires(T v) { { v.to_string() } -> std::same_as<std::string>; }; I would like create a concept that checks the existence of a glob...
This appears to work: template<typename T> concept method_to_string = requires(T v) { { to_string(v) } -> std::same_as<std::string>; }; https://gcc.godbolt.org/z/7WdTjf
64,308,172
64,309,352
If condition evaluates to true in debugger/runtime but if block is not executed
I am running this simple code to calculate the median of an array obtained from merging two sorted arrays. Weirdly, in Visual Studio 2019, the value in the first if block inside the loop is evaluating to true, but execution does not enter the if block. vector<int> nums1 = { 1,3 }; vector<int> nums2 = { 2 }; int collSiz...
I found the problem. nums1.size() returns an unsigned integer which you compare to a signed integer, but signed integer -1 is the highest value for unsigned integer. So your term idx1 < (nums1.size() - 1) is in real 4294967295 < 1, which always becomes false.
64,308,321
64,329,427
ffmpeg only posting playlist but not segments for HLS
I am launching an ffmpeg process that is supposed to send the HLS "encoded" data to a webserver that will distribute it to the clients requesting it. I am using the following command line: "ffmpeg", "-hide_banner", "-f", "rawvideo", "-pixel_format", "rgb32...
The hls_segment_filename isn't just for the basename, but accepts fully qualified path including protocol. IF only a basename is supplied, then file protocol is assumed and working directory is used for output location.
64,308,512
64,308,682
C++ Trying to implement a Matrix
Firstly, I'm new to C++. I'm trying to implement a Matrix in C++. I saw this: https://www.quantstart.com/articles/Matrix-Classes-in-C-The-Source-File/ And i was trying to implement a construtor that would allow the user to create a matrix by using, as arguments, the vector of vectors. (IDK if that is possible). templat...
you could just assign a to Matrix.content, if you want it in a constructor it would be: template <typename T> class Matrix { private: vector<vector<T>> content; unsigned _rows; unsigned _columns; public: Matrix(vector<vector<T>> a) { this->content = a; } };
64,308,591
64,308,714
Ambiguous compiling of string array with non-constant size?
My gcc compiler from mingw64 8.1.0 doesn't allow the following to be compiled because var has to be a constant value: int var=3; string str[var]; int main(){ However, doing the same within main() doesn't show any errors: int main(){ int var; cin >> var; string str[var]; Why is there an ambiguity?...
Depending on your compile flags, they're both "wrong": Code: #include <string> int i = 3; std::string s1[i]; int main () { int j = 3; std::string s2[j]; return 0; } g++ -o tmp3 -g -pedantic -Wall tmp3.cpp tmp3.cpp:4:17: error: array bound is not an integer constant before ‘]’ token std::string s1[i]; ...
64,309,541
64,309,613
c++ program printing out address instead of value
I have a program that takes in information through a struct and puts it into a vector, and I'm trying to print that information out but instead get an address. The structure should hold the values correctly so I think it's either my pointers or the way I'm printing it out. #include <iostream> #include <cstring> #includ...
You need to add an operator overload for your struct, to define how the struct should appear when printed. You also need to dereference the pointer as well as the iterator. // Define how the struct should look when printed. // This function makes it appear like: // Name: John Smith, ID: 1235, GPA: 4.0 std::ostream &ope...
64,309,870
64,309,948
Can you have typedefs for a single function?
I'm just wondering, in the following function I'm trying to get the return type of "Getter" into the function arguments. The default arguments is so that you don't need to pass the final arguments, especially if you don't provide a setter. Is there a cleaner way? template <typename Getter, typename Setter> void...
Using a defaulted template parameter: template <typename Getter, typename Setter, typename R = std::invoke_result_t<Getter>> void makeSpinnerBox(Getter getter, Setter setter, float sensitivity = 0.f, R minValue = R(), R maxVal = R(), R incrementStep = R())
64,310,150
64,362,024
Unable To Change Menu Bitmap
I have a custom-drawn skin for an app, that eliminates the caption/title bar. All of the menu items and system buttons are owner-drawn. Everything works as it should, except one little bug. When the Maximize button is pressed, and the window maximizes, the code should also change the button bitmap, from the "Maximize...
My Bad! I forgot to declare hMenu as a static variable. Because of that, I was losing my menu handle. That's why SetMenuItemInfo() would not work later, in the command code blocks. I knew that it had to be something simple. Anyway, here are the final bits of code. First, the creation of the Max/Restore buttons: WI...
64,310,286
64,310,718
C++ - using strcmp to compare which name comes first in alphabetical order
I'm new to C++ and trying to implement the lessThan() member function that compares the Person on the left-hand side (the this person) with the Person passed in as the parameter; a person is considered “less than” another if their name comes first in alphabetical order. I made my function below but when I run it I get ...
All you need to do is return name < per->name; and be done with it since <std::string> allows for that comparison and it is the preferred method. For completeness you could fix your code: bool Person::lessThan(const Person* per) const { return strcmp(this->name.c_str(), per->name.c_str()) < 0; } @Retired Ninja
64,310,323
64,310,362
Why is my function getting variables value on wrong order?
I'm new at programming. This is part of my code: double logic(double a,double b) { (Code Here...) } double inputDouble(double x) { std::cout << "Please, input a floating number: "; std::cin >> x; std::cout << std::endl; return x; } int main() { double a,b; std::cout << logic(inputDouble(a...
The expression: logic(inputDouble(a),inputDouble(b)) does not guarantee the order in which those calls to inputDouble() are made, just that they're both complete before the call to logic(). So it may call the a one first, or it may call the b one first(a). To guarantee order, you can use something like: double inputD...
64,310,539
64,356,263
How to build a stand-alone clang executable?
Is there a way to build a clang tool as a standalone executable? Something like this AST printer from 5 years ago, but it no longer matches current LLVM specs, so I'm wondering how I should modify my directories and includes so everything works properly.
The CoARCT project demonstrates example tools built on Clang libtooling; all builds are done out of the LLVM tree. Perhaps it can help? https://github.com/lanl/coarct
64,310,779
64,310,823
Why can't the compiler use the std::string conversion function of the class when perform operator<<?
Consider the following struct with a user-defined conversion function that can convert itself to const char*; struct S { operator const char*() { return "hello"; } }; This work with <iostream>, we can print the struct S with no error message: std::cout << S{} << '\n'; But if I change the return type to std::string:...
Because operator<< for std::basic_string is a template taking 3 template parameters: template <class CharT, class Traits, class Allocator> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::basic_string<CharT, Traits, Allocator>& str); And implicit conv...
64,310,793
64,312,180
C++, Using iostream library to output an uninitialized variable \ Visual Basic
How can I make Visual Studio (2019) print an uninitialized variable? #include <iostream> int main() { int x; std::cout << x; return 0; } I understand this is relatively useless and uninitialized variables should not normally be used, but I would imagine there should be a way to make it print the value in the ra...
There is a method to do it. int main() { int num[1]; for (int i = 0; i < 1; i++) { std::cout << num[i]; } } In my opinion, outputting uninitialized variables does not make much sense. Maybe you want to get the address. int x; std::cout << &x;
64,310,796
64,311,015
Set a pointer to pointer in c++/cli
I have a managed class and would like to set the native class in the create() method. ref class ManagedClass { private: NativeClass* ptr = nullptr; public: void create() { NativeClass nativeClass; nativeClass.set(0); this->ptr = &nativeClass; } }; However, the nativeClass ...
Local variables cease to exist when the function in which they are defined returns, and any remembered pointer to such a local variable becomes invalid. This is no different in C++/CLI vs. unmanaged C++. To create an object that persists beyond the create call, allocate it dynamically and save a pointer to it with ptr ...
64,310,813
64,310,999
C++: Char pointer to char pointer array to char array
I'll do my best to be brief: So I have an assignment where I am creating a 'Wordlist' class. In which I will store a list of words. These are the member variables class WordList { //... unsigned int m_count; // Number of words currently in list unsigned int m_max; // The total size of the list. ch...
I don't see anything wrong with your use of double-pointers. There are other issues, though: in your WordList::add you should check for empty word or empty list first, and fail fast. Besides, in your code if the word was empty - you would already added it and returned form that function. in if (m_count < m_max) block,...
64,310,856
64,311,060
Why add a version number with CMake when it can be done with git?
In CMake's Tutorial, under the section "Adding a Version Number and Configured Header File", it explains how to add a version number to a project. Why do this with CMake when version-control tools (such as git) already allow you to specify a version number? What, if anything, is to be gained from specifying a project's...
Nevermind, that same section of the tutorial has the answer. This is embarrassing! Basically, CMake lets you substitute your version number into your code at build-time (essentially a macro), which git doesn't.