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
66,294,597
66,301,474
Antlr4 allocate ParseTree on heap
I have a function like this to get the the AST from a file. antlr4::tree::ParseTree *get_ast(std::string &filename) { std::ifstream stream; stream.open(filename); antlr4::ANTLRInputStream input(stream); Lexer lexer(&input); antlr4::CommonTokenStream tokens(&lexer); Parser parser(&tokens); an...
You not only have to keep the parser alive but also the token stream, because the parse tree uses token references. I recommend to create a wrapper class holding all the parser related objects and keep that alive. This way all the references stay valid. You can always re-use the object for new parse runs. For MySQL Wor...
66,294,705
66,295,170
How to write a c++ concept for class with member function template that takes a template argument?
How can I write a C++ 20 concept requiring a member function template that takes a template argument that must be provided? The goal of the following concept is to check that a type is tuple-like, except rather than checking std::get<I>(t) I want to check t.get<I>(). The following does not compile with g++ 10.1 using s...
This: template <typename E> concept Tpl = requires(E const e, int idx) { { e.template get<idx>() } -> std::convertible_to<float>; }; does not work because idx is not a constant expression, and you need it to be one in the context of calling get. In order to do that, you need to pick a speci...
66,294,817
66,300,194
Is it okay to call SDL_RenderCopy() for each sprite?
This is a followup to my question here: Is it okay to have a SDL_Surface and SDL_Texture for each sprite? I made an class called entity each having a SDL_Texture, which is set in the constructor and then a member function render() is called for every onscreen entity in a vector, which uses SDL_RenderCopy() to draw to t...
Prefer frame time over FPS You want to measure and judge your performance based on the frame time not FPS. Because the relation between the two is not linear. Going from 20 FPS to 30 FPS needs about 16.7 ms worth of optimization. That is the same amount of performance gain in optimization it takes to get from 30 FPS to...
66,295,093
66,295,194
Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>' and 'void')
I'm trying to write a function to solve a quadratic equation, and I get this error on line 26: Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>' and 'void') But I don't quite understand why the compiler swears and what it wants from me. I connected the library <ostream>, but it didn't w...
Look at the prototype of your function: void Kva(float a, float b, float c) You are telling the compiler to pass nothing. You may want to ask the function to return the float type. Uncomment the return statement. For x1 in Kva(), remember to initialize it so that it guarantees to return some value to the function (at ...
66,295,158
66,295,426
Custom type range/value check compile-time, real-time
When we define a variable of a built-in type too large to parse, Compiler/IDE (I'm using Visual Studio 2019) warns right away that the range has been violated, even before compiling the project - "integer constant is too large" if we're defining an integer. int sum = 100000000000000000000; // E0023, "integer constant i...
You can add a check to your constructor for the argument being inside a range, and then assert on that: struct MonthDay { constexpr MonthDay (int data) : data(data) { if (data > 31) { assert(false); // months can't have more than 31 days } } private: int data; }; So long as the construc...
66,295,374
66,295,478
Given intergers n,d,i is [ n*d + (i-d) ]%n equivalent to [n + (i-d)]%n? (% c++ modulo)
Given range of n :[0, 10^5] ..........range of d :[1,n] ..........range of i :[0,n] With the parameters above and their given ranges. I assumed that (n*d + i-d )%n is equivalent to (n + i-d )%n. Considering a function that performs d left rotations on an n element(s) array/vector and returns an array/vector containing...
With n*d you overflow INT_MAX. Maximum value for a variable of type int. 2147483647 So your n*d value becomes negative as a result of overflow and then you try to access a negative index of the array that cause the segfault. Solution: I dont see the point to have n*d if you use modulo n right after so you can avoid t...
66,295,452
66,295,567
Print template parameters
I am trying to create a template vector of arbitrary number of int parameters and create a function to print those parameters: namespace ex { template <int I, class... Ts> constexpr decltype(auto) get(Ts&& ... ts) { return std::get<I>(std::forward_as_tuple(ts...)); } template<int... N> str...
If you have access to C++17, you can benefit from fold expressions: template<int... N> struct vec { void print() { ((std::cout << N << std::endl), ...); } }; Before C++17, you can use dummy array initialization trick: template<int... N> struct vec { void print() { int dummy[]{0, ((std::cout...
66,295,561
66,296,040
Why do printf and isnan disagree whether a long double value is a NaN?
Consider the following code: #include <math.h> #include <stdio.h> #include <string.h> int main() { __uint128_t n = (__uint128_t(0x00007ffff7dd6e65ULL) << 64) | 0x63696c400a2d2d21ULL; long double d = 0; memcpy(&d, &n, sizeof(long double)); printf("%d\n", isnan(d)); printf("%Le\n...
The object formed by the initialization from the 128-bit integer is invalid because its explicit significand bit does not match the other bits. Apple Clang is using Intel’s 80-bit floating-point format. According to Intel 64 and IA-32 Architectures Software Developer’s Manual (December 2017) 4.2.2, the “Integer” bit is...
66,295,630
66,295,764
Finding partial sum without using loops
The question is as follow : Write a program that prompts the user to enter a positive integer m that represents the sum of all page numbers in a book. The program prints whether the number is a valid sum or not. For example, the integer 21 is a valid sum of page numbers because 1 + 2 + 3 + 4 + 5 + 6 = 21. The integer 2...
Rearrange the equation slightly: n(n+1)/2 = m n(n+1) = 2m Now, for this equation to be true, sqrt(2m) has to be between n and n+1, meaning n = floor(sqrt(2m)) and n+1 = ceil(sqrt(2m)). Then you can just check that the calculated values for n and n+1 multiply to 2m. This is simple to check using code: #include <iostrea...
66,295,777
66,295,913
Any reason why 0.0/0.0 makes negative nan in C++?
I found the following from SoloLearn: I found that 0.0/0.0 makes negative nan(-nan). It makes sense to me that such a mathematical result is undefined, or "not a number". [...] Furthermore, why is -nan+2^nan=nan? For example: #include <iostream> using namespace std; int main() { cout<<0.0/0.0<<endl; cout<<"i...
As far as the C++ language is concerned, the behaviour of the program is undefined. So, from C++ perspective there is no "reason" for anything about the behaviour of the program. According to the IEEE-754 floating point standard, assuming your hardware and language implementation conform to it (they probably do), resul...
66,295,882
66,296,033
Unexpected variable values reading from file (ESP32)
I am still learning Cpp, so please advise if I am misunderstanding here. Using an ESP32, I am trying to read / write files to Flash / FFat. This is the method I have created which should read a file from flash and load it into PSRAM: unsigned char* storage_read(char* path) { File file = FFat.open(path); if(!fi...
Why would sizeof not be returning the proper size? That's because sizeof() has a very specific function (not very intuitive). It is used - compile time - to query the size of the data type passed to it. Calling sizeof(buffer) returns the size, in bytes, of the type of variable buffer. It's an unsigned char*, so a 4-b...
66,295,943
66,296,857
Pointer to incomplete class type is not allowed Unreal Engine 4.26
I try to implement the pawn navigation to the player in my game. When I tried that in BP site, it worked perfectly, but I try to transform that in C++ code. And I got a kind of wird error. Befor this I faced another error but I find the NavigationSystem was changed a bit in my ue version, but I figured out problem by c...
You may also need to add the NavigationSystem module to your Project.Build.cs file in the PublicDependencyModuleNames array.
66,296,177
66,296,207
Using std::bind with a lambda function
The following code does not compile: auto greater_than = [](const int a, const int b) { return a > b; }; auto is_adult = bind(&greater_than, placeholders::_1, 17); cout << "Age 19 is adult = " << is_adult(19) << endl; The is_adult call is giving a vague error: error: no matching function for call to object of type 'st...
Remove the &. Even though pointers-to-functions are callable, pointers to objects with overloaded operator() are not.
66,296,249
66,296,375
Xor encryption in C++ with warning "Use of a signed integer operand with a binary bitwise operator"
I'm learning the simple XOR encryption algorithm in c++. The next code works fine: void test(int8_t* data, const int data_length) { const uint8_t key = 123; for (int index = 0; index < data_length; index++) data[index] = data[index] ^ key; } The data that I am given is signed, therefore has a type of ...
The compiler is giving the warning because bitwise operations are not supposed to be performed on signed integers. In C++ before C++20, there were allowed different representations of signed integers, meaning that the same number could be represented by different bit patterns on different machines and compilers. This m...
66,296,601
66,308,602
cmake generated header causes double build
A very simple scenario - I need to generate header, include it and if generated header is updated while cmake build, all dependent cpp units also must be rebuilt. A simplified example: add_custom_command( OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/test.h COMMAND ... DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/test.in" ad...
Posting as an answer to be able to show full example CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(example) add_custom_command( OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/test.h COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/test.in" ${CMAKE_CURRENT_SOURCE_DIR}/test.h DEPENDS "${CMAKE...
66,296,634
66,308,063
SWIG Wrap C++ into Python
I wrote a C++ module to compute the forward and inverse kinematics for my SCARA robot arm, and I want to wrap this module into Python so that I can use it in another application. For the conversion, I chose SWIG, but it is pretty hard to write the interface file correctly. In my header of C++ module, I have namespace A...
The easiest way using SWIG is to use numpy.i Change your C++ interface to this namespace ARM_KINEMATICS{ /* Forward kinematics [in] const double *q: joints' value [out] double *T: placeholder to put homogeneous transformation matrix, with length 16 */ void forward(const double *q, const int nq, double...
66,296,643
66,296,774
C++ Sending vector<uchar> with socket loosing data
Im trying to send an Image with sockets from the server to the client, but for some reason im losing a lot of data. this is my server: #include <opencv2/imgcodecs.hpp> #include <iostream> #include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #incl...
You have two major flaws, one which could lead to an infinite loop, and one which leads to the problem you experience: The infinite loop problem will happen if read fails in the client and it returns -1. -1 != 0, and then read will continue to read -1 forever. The second and main problem is that you treat the data yo...
66,296,652
66,296,814
How to write a function that takes a "nested" template type as a parameter
I would like to write a generic function that takes some map-like type, and returns all the keys in the map. I would also like the API of the function to be extremely simple, like this: std::unordered_map<int, std::string> stringTable; auto stringTableKeys = keys(stringTable); // should return a std::vector<int> std::...
Sorry for the confusion, it turns out my code actually does work. https://onlinegdb.com/By6hgZkMd This is just a bug in Visual Studio 2019, I wasn't sure if it was going to work because it said it was a syntax error:
66,296,752
66,296,805
c++: variable to pointer, unexpected segmentation fault
For the following code, everything is normal. However, if I define the variable as pointer, then the segmentation error comes out. #include <iostream> #include <cmath> using namespace std; struct foo { double x; double y; }; void func(const foo * pxy, foo * pda); int main() { foo a; foo b; cout << ...
This version with pointers will work int main() { foo aa, bb; foo* a = &aa; foo* b = &bb; ... } The difference is that in this version the pointers are actually pointing at something. But I'm sure you'll agree there's no purpose to this code, it's better without the pointers. Pointer variables are no d...
66,296,966
66,297,099
Can one instance of a class (not the class itself) be the parent of many instances of another class?
Root Problem I am trying to build a render engine with Vulkan in C++. I am trying to remove the asset meshes, textures, and similar from within the engine structure where I had it for testing purposes to its own separate class. I need to access some of the objects stored in the render engine class because each asset ne...
Is there a method of going about inheritance that allows for many instances of one object to inherit from one instance of another object in C++? No, you are mixing apples and oranges here. Inheritance is a way to build one class off of one or more base classes. It has nothing to do with instances of those classes, an...
66,297,288
66,297,354
operator overloading Error: cannot bind non-const lvalue reference of type ‘some-type’ to an rvalue of type ‘some-type’
#include <iostream> #include <string> using namespace std; namespace ComplexNumberNamespace { typedef struct _Data { double real; double imag; }Data; class ComplexNumber { private: Data data{}; public: ComplexNumber(); ComplexNumber(float real, floa...
Your constructors and operator overloads taking ComplexNumber& as argument need to take const ComplexNumber& instead. This line ComplexNumber sum = c1 + c2 actually calls your ComplexNumber copy constructor and gives it the c1 + c2 expression result, which is a temporary ComplexNumber. Since you can't make a non-const ...
66,297,335
66,298,151
How to make a form in c++ from scratch without winforms?
I want to make desktop application with cpp and make a completely new form and I don't want to use winforms or any external addons just cpp.
When presenting output to screen you almost always have to call some kind of system call at some point. So the next closest thing to winforms is probably the winapi, but you could try some kind of graphical library for example sdl2 or sfml which encapsulates these calls with their own api. But you wouldn't have all the...
66,297,355
66,298,696
Viewing Doxygen results
I have tried running doxygen from my Linux terminal using the commands: doxygen -g, followed by doxygen Doxyfile I then get the corresponding html sub-directory produced in the directory that my original code is stored in. However, when I open the index.html file in Google Chrome, I do not get any results being display...
Have you actually edited the Doxyfile that gets produced? There are a few lines in there that you want to look at: PROJECT_NAME = "My Project Name" INPUT += src Also, when I ran it, I don't specify the Doxyfile, but that's just because Doxyfile is used by default.
66,297,364
66,297,785
How can I use `ListS` instead of `VecS` as underlying container and be able to do the same thing?
I usually work with vecS as container for boost::adjacency_list: struct myVertexType { std::vector<Stuff> vec; /* and more */ }; struct myEdgeType { /* some data too */ }; using Graph = boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, myVertexType, myEdgeType ...
Background "when I created another vertex, that seemed to make my reference invalid (1)." Yes, that's possible. You have to realize that there's are much bigger performance trade-offs underlying your choice of container selectors. Many algorithms can get very different efficiency characteristics. Also, some semantics...
66,297,416
66,297,580
Failing to accumulate compile time constants
I am trying to create a variadic int argument vectors and perform + operators on them. For example: vec<1,2,3> v1; vec<4,5> v2; auto res = v1+v2; res.print(); // should print 5 7 3 vec<5,7,3> is the result. And now I want to create struct vecSum, which will sum up the vectors given to it; namespace ex { templat...
I see some little problems in your code... expand Ts In vecSum you define res as follows static constexpr auto res = all(Ts); You have to expand Ts as follows // ...............................VVVVV static constexpr auto res = all(Ts{}...); std::index_sequence contains std::size_t, not int, values Your add() is...
66,298,546
66,298,598
How to get the element type of each container passed to variadic template function
I have a variadic template function and I'm passing a sequence of std::vectors to it. For each std::vector object I need to get the type of its elements, in order to do some operations on it, like retrieving compile time constants ex T::SIZE, or check its size sizeof(T). Here is the two approaches I tried: template<typ...
You'd have to do something like: template<typename ...T> void foo(T...args) { auto f = [](auto x){ using U = typename decltype(x)::value_type; int size = sizeof(U); int var = sizeof(U); }; (f(args),...);; } If later on you'd like to change the lambda to accept references, s...
66,298,550
66,412,784
Adding Padding to Win32 ListView
I have a ListView in LVS_REPORT mode that contains rows of strings. Everything draws properly; however, I noticed that all of the rows are very densely packed. Is there anyway to simply add padding to the ListView items? I imagine that you could do BS_OWNERDRAW; however, I don't really want to go so extreme if there is...
so what I ended up doing in order to add some space between each element is essentially create a blank ListView item between each real one. I don't know if this is the best way to go about it, but it seems to work so far.
66,298,608
66,298,622
Overwriting a file when compiling g++
If I have a c++ file and compile it but then have to make changes, I have to remove the file and recompile. It is not a huge inconvenience but I would rather not have to do that every time I test a program. Do any of you know how to overwrite a file when compiling to it?
you shouldn't have to delete it, just recompiling will replace the old executable with the new one.
66,299,230
66,299,292
Can I read and write to the same file in Android, using mutexes, without having undefined behaviour?
I'm designing a musical Looper, which is something that, once a first recording is made with x seconds, repeats playing these x seconds and on each iteration, adds new content to the loop. Since the size of the first recording can vary, I cannot do this with RAM allocated memory, I must place it to disk. Long story sho...
Since the size of the first recording can vary, I cannot do this with RAM allocated memory, I must place it to disk. Your assumption is simply wrong. Just because size of the recording can vary does not mean you have to put it on disk. For example you could store your recording in a std::vector<unsigned char>. This i...
66,299,415
66,299,887
where's the relevant rule for phase two name lookup of template instantiation in the current standard
template<typename T> void fun(T t){ foo(t); //#1 foo is a dependent name } void foo(int){ } int main(){ fun(0); // #2 ill-formed } Since the unqualified-id foo is a dependent name as per temp.dep#2, So, the lookup name rule for this name should obey the following rule, which is mentioned in the note of [temp.de...
In other words, these rules mean that only ADL is used to perform in phase two lookup. This is the wrong conclusion to draw from the given specification quotes. You seem to be confusing two different concepts. The first concept is what is commonly called "two-phase lookup": the fact that when a template gets parsed, ...
66,299,442
66,299,979
Frequency histogram in c++
I'm new to C++. I am trying to read the frequency histogram of cards. When I execute the program with the input 3D3D3S, it shows 3D occurs 3 times. Could anybody help me explain what did I do wrong? It only reads the number and ignores the suit of the card. #include <algorithm> #include <iterator> #include <vector> #in...
std::map doesn't need == operator to distinguish uniqueness (your code will actually compile if your remove the == definition). It solely relies on the < operator, this means: bool operator <(card const& a, card const& b) { return a.num_ < b.num_; } ...when used with 3S and 3D, it will only compare the num_ values o...
66,300,079
66,300,370
Kahan algorithm in c++
I have written follwoing kahan algorithm; it reasonably work for n to be from 1 million up to 10 million, but it produces very large error when n is 100 million. I tested it multiple times but I cannot figure out why this is happening. #include <iostream> #include <vector> #include <random> #include <cfloat> #include <...
I did a quick test, using an implementation of Kahan summation I wrote some time ago, and compared it to yours: #include <cfloat> #include <iomanip> #include <iostream> #include <iterator> #include <numeric> #include <random> #include <vector> namespace Kahan { template <class InIt> typename std::iterator_traits<InIt>...
66,300,267
66,300,486
return struct value in C++
When I studied const reference type in C++, I learned returning reference type make use local variable in main function, so I tested how returned normal struct type work in lvalue. so I expected this source won't compile, but it compiled well... :( so I have two question "Is returned struct variable?, why this code co...
Is returned struct variable?, why this code compiled well? This doesn't make much sense. travel_time sum; is a variable. When you call sumTime, you return a copy of this variable, and that copy itself isn't a variable. So the answer is no, the result of calling the function isn't a variable. I have a feeling what you...
66,300,447
66,300,457
std::vector<unsigned char> remains empty after reading binary file using std::ifstream
This is my first question on StackOverflow so I apologize in advance if there is anything I am missing in my question or some rule I didn't follow. Please edit my question or tell me in the comments how I should improve my question, thank you. I am trying to read a binary file into a std::vector<unsigned char> in C++ u...
reserve() allocates memory, but it doesn't register the allocated region as valid elements. You should use resize() to add elements and size() to count the elements. // reserve capacity in.seekg(0, std::ios::end); //fileContent.reserve(in.tellg()); fileContent.resize(in.tellg()); in.clear(); in....
66,300,587
66,301,890
How to ensure that a template parameter has a value_type and is iterable?
I would like to generalize a function using templates. And, the template parameter should be checked somehow. As a minimum reproducable example I have written a function that will return the top frequent element of a container. For better understanding, please see the below simple code: #include <iostream> #include <ut...
Since the range-for is required, you need to test if begin() and end() are supported. Here top_frequent_support re-uses this trick. Moreover, expecting the value type to be named as Container::value_type (by the way, your code misses typename) might be an unnecessary constraint. You can simply deduce this type from *be...
66,300,917
66,300,943
C++ ADL: Call a function from the namespace which a particular type belongs to
Imagine there is an existing type Inner in its own namespace. In this namespace there is a function/operator (myfunc) taking in the Inner type. Suppose, this function doesn't work properly, but we can't change it. Next, the type Inner is aliased within another class (G). That class belongs to a different namespace and ...
Is it possible to tell the compiler that it should call myfunc from the namespace of G? No. Generally speaking, is there any way in C++ to access the namespace of a particular entity? E.g. namespace_of(SomeClass)::function_in_that_namespace(). No. You'll have to find a different approach, such as wrapping myfunc i...
66,301,035
66,309,232
static_cast to enum class from underlying type value and switch for compiler assistance
Suppose I have an enum: enum class Thing : std::uint8_t { Foo = 21, Bar = 42, Baz = 1 }; I want to convert a "raw" value (of the underlying type) to a value of that enum, with error handling catching values which are not "a thing". I could use checks like if (raw_value == static_cast<std::uint8_t>(Thing::Foo)) ...
It is legal C++. The drawback is the DRY violation, but avoiding it is difficult. In c++23 we'll have reflection and be able to generate equivalent code (without having to rely on compiler warnings to make sure we didn't miss any). Reflection syntax is still a bit in flux, but every version I have read over was able t...
66,301,127
66,301,208
counting comparisons in a binary search function
I'm running this binary search function and I'm struggling to run an incrementer that counts the amount of comparisons that have been made. I'd like for the number of comparisons to output at the last cout statement (which is empty). Can someone point me in the right direction? void binarySearch( int nums[], int size) ...
void binarySearch( int nums[], int size) { int first = 0; //first array elements int last = size - 1; //last array int middle; //midpoint of search int position = -1; //position of search value bool found = false; //flag for (int j = 1; j < 4; j++) { int comp = 0; int randVal...
66,301,264
66,301,749
With C++17 only, Is it possible to create a macro which accepts class and method name and returns true if such a method exists in the class?
With C++ 20 concepts we can write smth like: #define has_method(CLASS_NAME, METHOD_NAME) \ // Can be generalized of course, but it's just to illustrate the idea []<typename TEMPLATE_ARG>() \ { \ return requires{ std::declval<TEMPLATE_ARG>().METHOD_NAME()...
Yes, this is possible, though it does require a macro AFAIK, but you seem to not mind that. We of course need some SFINAE context because that is the only place where we are allowed to write syntax errors. But creating in-place templates is tricky because local classes cannot contain them, so even if(class { /* templat...
66,301,649
66,303,199
C++ Compilation Standard for “&” vs “&&” Expressions?
I have a core function evaluating 4+ simple arithmetic comparisons to return a bool. This will be called O(N^2) times in a very large loop, with a single conditional branch based on the return. If the function is written as: return x < y && g < h && m < n && q < r; will it generate 3 conditional branches compared ...
I've put up 4 example of your code, with certain caveats on Godbolt. no side effects trivial types #include <stdint.h> #include <xmmintrin.h> bool Test1(int x, int y, int g, int h, int m, int n, int q, int r) { return x < y && g < h && m < n && q < r; } bool Test2(int x, int y, int g, int h, int m, int n, int q, i...
66,301,790
66,301,903
Enable "Hide extensions for known file types" with C++
I want to know how to enable/disable the Hide extensions for known file types under windows 10 (Older versions should work aswell) in C++. How to enable it in Windows Explorer How to enable it in File Explorer Options If it's not possible to do in c++ I would be okay with cmd/powershell aswell! Thanks in advance!
PowerShell To Enable the option (i.e. to hide known extensions), use: $regPath = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced' if (!(Test-Path -LiteralPath $regPath)) { $null = New-Item -Path $regPath -Force } Set-ItemProperty -LiteralPath $regPath -Name 'HideFileExt' -Value 1 -Type DWord -Force ...
66,301,825
66,302,441
Array won't be passed to function C++
The program is stuck in a loop. I checked it with the debugger, and found out, that my array isn't being passed from my main function to the "binarysearch" function, and from there, it won't be passed to the "check" function. smallestwrh = binarysearch(h, n, contentmax); won't pass to long long binarysearch(long long ...
Your code is correctly passing the complete array to binarysearch (or at least the start address and the length), you only have a debugging display issue. In main you have h, an array of 100001 long long, so the debugger displays h as an array. When calling binarysearch you do an array to pointer decay, you are only pa...
66,301,850
66,302,093
How to compare two vectors for equality?
I have the following program: std::vector<int> nums = {1, 2, 3, 4, 5}; std::vector<int> nums2 = {5, 4, 3, 2, 1}; bool equal = std::equal(nums.begin(), nums.end(), nums2.begin()); if (equal) { cout << "Both vectors are equal" << endl; } There are two vectors that have equal elements. std::equal function does not w...
You can construct a std::unordered_set from each vector, then compare those, as shown in the code snippet below: #include <iostream> #include <vector> #include <unordered_set> using namespace std; int main() { std::vector<int> nums = { 1, 2, 3, 4, 5 }; std::vector<int> nums2 = { 5, 4, 3, 2, 1 }; std:...
66,301,917
66,301,939
C++ merge sort problem while using dynamic array
I am trying to implement a merge sort function but I have a problem with the merge part. Since initially, I don't know the array size, I created a temp dynamic array to store the final merged array. When I run this method, I get a Heap Corruption error. When I change the dynamic array size to (last + 1), the method run...
Initializing i, which is used as the index for temp to first1, is bad because temp has only elements for the range between first and last. i should be initialized to zero and the loop for (int k = first; k <= last; k++) { arr[k] = temp[k]; } should be for (int k = first; k <= last; k++) { a...
66,302,151
66,302,206
c++ string clear() after declaration
I am a beginner learning strings. #include<iostream> #include<string> using namespace std; int main(){ string st1, st2; st1.clear(); .. I have seen in several examples the use of clear() after a string declaration. Is it necessary? Does this provide any benefit or is just a good practice, isn't the string null by defa...
A default-constructed string has zero size and unspecified capacity, so semantically, there is no point in calling clear(). The string was empty and cannot be made more empty. However, it is not guaranteed that clear() does not change the string's capacity, so it's possible that some implementations free up some memory...
66,302,983
66,303,291
UNIX sockets::recv, std::byte, and strict aliasing
I'm writing a function that basically wraps recv: ssize_t recv(int sockfd, void *buf, size_t len, int flags); In particular, I want to write to receive some bytes; and sometimes these bytes will be part of an ASCII string, other times they will be integers, or maybe just plain "bytes" that are part of some higher-leve...
There is no difference between a char and a byte, in this instance. In fact, originally these network functions were defined in terms of the char data type. A very long time ago the second parameter to recv was a char *, instead of a void * as it is now. This would make converting the std::vector<char> into a std::stri...
66,303,275
66,527,370
How to convert ISO week number to US week number in C++
I am using boost gregorian library for date calculation in c++ boost gregorian returns week number in ISO format but I want week number in US format. how I can get week number in US format. please see link https://planetcalc.com/1252/ e.g. #include <boost/date_time/gregorian/gregorian.hpp> int main(int argc, char* arg...
I find no direct way in C++ or any library which support US method for week number, So I have to use CLR dll and call it from native C++. //Header file #pragma once __declspec(dllexport) int GetWeekNumber(int year, int month, int day); C++/CLI File #include "pch.h" #include "CLRDll.h" using namespace System; using na...
66,303,287
66,303,395
Calling an async function inside a class
I have this class with a few methods. One of them needs to compute and render something over a wide range of data (coordinates). To make the program run faster and smoother, I thought of using async methods. I created a private function that does the computation and rendering. My class: #include <future> class MyClass...
std::async requires a function to call, a method is not a function because it must be called on an object. How is std::async going to know which object to use to call compute_and_render? Try this which uses a lambda function to capture the object std::async([this](int ii, int jj) { compute_and_render(ii, jj); }, i, j)...
66,303,386
66,303,431
How to load a database to struct in c++?
I have database in books.txt. The data is separated by semicolons in this way: id;year;author 1;2012;John Snow 2;2011;Rihanna 3;1902;Shawn Mendes 4;2000;Boleslaw Chrobry 5;2001;Papa Loui 6;1905;Spongebob My code doesn't work. How can I implement this correctly? code: struct Books { std::string id; std::s...
Make the function loading static because it won't require access to member variables. Return the whole array (you should use std::vector instead of arrays) instead of the out-of-range thing a[7] Assign the returned thing in the caller. #include <iostream> #include <fstream> #include <vector> struct Books { std::...
66,303,451
66,303,476
I keep getting an error when I try to pass the head pointer of the linked list
I keep getting an error saying undefined symbol insert(*Friend). Can anyone identif and explain the error please? I know it refers to the fact that it cannot find it but I can't identify what is wrong please helppp. I am working on a program that keeps a database of friends' information using a linked-list. Therefore, ...
You declared void insert(struct Friend* head); (there is only one star), but only defined void insert(struct Friend** head) (there are two stars). They are different functions. It seems the declaration should be corrected to two stars (match to the definition) and &head should be passed instead of head on calling that....
66,303,480
66,303,502
Why i am getting error not declared in this scope?
#include<iostream> #include<vector> using namespace std; int sol(int i,int j,vector<vector<char>>v,int h,int w,int dp[][w]){ if(i>h || j>w){ return 0; } if(i==h && j==w){ return 1; } if(v[i][j]=='#'){ return 0; } if(dp[i][j]!=-1){ return dp[i][j]; } d...
In C++ array bounds must be compile time constants. In your code int dp[][w] w is a variable, not a constant. Since you are already using vectors I suggest you use a vector for dp as well. In main vector<vector<int>> dp(h, vector<int>(w)); and in sol int sol(int i,int j,vector<vector<char>>v,int h,int w,vector<vector<...
66,303,635
66,304,498
Performance drops when running Eigen dense matrix multiplications over multiple cores on ARM / Raspberry PI
I have found a significant drop of performance when running Eigen dense matrix multiplication on 2 or 3 threads in parallel on ARM 32 or 64 bits on Raspberry PI 4. I can't understand this issue because RPI 4 has 4 cores and theoretically can deal with up to 4 threads in real parallelism. Furthermore, I cannot reproduce...
Basically your PI has a much smaller cache than your desktop PC CPU, which means your program on PI has cache collisions much oftener than your PC. 512*512*4 (sizeof(float)) or 1 MB per instance. On your PC with perhaps 12 MB L3 cache you will never to to RAM (maybe on allocation) while the tiny cache on the PI will ...
66,303,650
66,303,719
ERROR: Cannot synthesize a Constructor for A
Hi i am trying to understand how constructors work in C++. For this i am using the following example: class NoDefault { public: NoDefault (const std::string &){} }; struct A { NoDefault my_mem; }; struct B { B () { } // error: no initializer for b_member NoDefault b_member; }; ...
As described on cppreference the default constructor for A is declared. 3 Implicitly-declared default constructor If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class. But in...
66,304,084
66,374,468
Direct3D11 shaders compile flags problems
I am reading a book from Frank Luna 3D Game Programming with DirectX 11. I was using D3DX11CompileFromFileW() function to compile shaders with flag (D3D10_SHADER_DEBUG | D3D10_SHADER_SKIP_OPTIMIZATION) and it was working ,but in new projects and some more advanced programs although the project is compiled without error...
The first thing you should try is to use the D3DCompiler API directly rather than using the deprecated D3DX11 'wrapper' for it. Currently you are using the "#43" June 2010 release of the HLSL compiler, and there's been many bug-fixes since. The Windows 10 SDK provides the "#47" version of the HLSL compiler. Note that w...
66,304,128
66,360,644
Should I cache this object in c++ (SFML)
(I'm completely new to c++, but I have expierence in c# and java) Hi, I'm creating a chess game in c++ (SFML) and I have a Piece class which has draw method. Right now I'm doing it like this: void Piece::draw(sf::RenderWindow& p_window, bool p_selected) { if (p_selected) { sf::RectangleShape shape; ...
Realistically, the performance impact of caching vs not caching an sf::RectangleShape is tiny, especially for a relatively simple program such as a chess game. Generally though, it is a good idea to cache variables that are used repeatedly each frame rather than creating them over and over again. I decided to write a s...
66,304,287
66,304,345
How to Resolve Circular Reference in Header File
I have the following header file (simplified for illustration here): #include <vector> class Box; class Item { int row; int column; Box *box; public: Item(Box *b) : box(b) {} void thiswontcompile() { box->dosomething(); } void foo(); }; class Box { std::vector<Item*> items; public: Box() {} void addsq...
You can move the definition of thiswontcompile to the end of the header file, you just need to make the function inline. #include <vector> class Box; class Item { int row; int column; Box *box; public: Item(Box *b) : box(b) {} void thiswontcompile(); void foo(); }; class Box { std::vector<Item*> items; pu...
66,304,382
66,304,513
extern "C" 'initializing': cannot convert from 'const char [1]' to 'char *'
I have strange error when compiling open source lib I using visual studio 2019 and I created a solution to the lib cmake -G "Visual Studio 16 2019" ../" but I keep getting erros when compiling : starting with this line : CFUNC char *optarg = ""; C:\Dev\my\cpp\libs\libunistd-master\unistd\getopt.cpp(16,24): er...
"" is a constant string. You can't just assign that to a non-constant char *, because then it could be mutated through the pointer. According to the source code of libunistd, the implementation was taken from NetBSD, but a quick check¹ shows that NetBSD doesn't initialize optarg at all: char *optarg; /* argum...
66,304,476
66,305,450
VideoWrite not writing
I have a lot of videos. I want to turn these videos 90 degrees counterclockwise and rewrite them. I'm trying to do it for just one video for now. I got video as output but the content of the video is blank(0 sec). I could not understand the reason. Here is my code ; int main() { std::string videoPath = "/home/fifty/ec...
Just try to resize your frame before writing. cv::resize(img, img, cv::Size(frameWidth, frameHeight)); video.write(img);
66,304,984
66,305,040
simple way to convert parameter pack to array at compile time
is there a simple way to create an std::array from a parameter pack at compile time? constexpr auto array = to_array<int>(1, 2, 3, 'a', 5.5f); there are existing solutions: helper functions & classes with recursion: not intuitive, difficult to read and not very modern C++20's std::to_array({...}): sadly it only works...
What about simply template <typename T, typename... Args> constexpr std::array<T, sizeof...(Args)> to_array (Args && ... args) { return {{ std::forward<Args>(args)... }}; } ? Or, maybe, if you want to add the static_cast template <typename T, typename... Args> constexpr std::array<T, sizeof...(Args)> to_array (Args &...
66,305,683
66,306,534
Is it a good idea to cache a raw pointer along with its owning shared_ptr for better access performance?
Consider this scenario: class A { std::shared_ptr<B> _b; B* _raw; A(std::shared_ptr<B> b) { _b = b; _raw = b.get(); } void foo() { // Use _raw instead of _b // avoid one extra indirection / memory jump // and also avoid polluting cache } }; ...
This answer proves your test is invalid (correct performance measurements in C++ are quite hard since there are lots of pitfalls) and as a result you come to invalid conclusions. Take a look on this godbolt. for loop for first version: .L39: mov rdx, rax and edx, 2097151 mov QWORD PT...
66,305,878
66,305,946
How to specialize variadic template class for one type?
I am trying to specialize variadic template class for specific type. I am trying to achieve this: template<typename... Ts> class myclass { ///... }; template<> class myclass<int... N> { ///... }; And I get this errord: error C2760: syntax error: unexpected token 'int', expected 'expression' error C2187: syntax ...
Your myclass is declared for a variadic list of template parameter template<typename... Ts> class myclass You can specialize if for specific types, not for specific values, as in your question (corrected for syntax, but remain wrong for the types/values problem) template <int N> class myclass<N...> Different if you h...
66,306,783
66,307,124
Why is UnrealHeaderTool failing when building RPCs
In my header file for a pawn I'm attempting to declare an RPC. The following compiles properly: UFUNCTION( ) void ClientSetPosition(FTransform position); Yet this does not compile: UFUNCTION( Client ) void ClientSetPosition(FTransform position); I Get the following error: UnrealHeaderTool failed for target 'MultiEditor...
The following resolved the issue: UFUNCTION( Client, Reliable) They must have updated unreal to require this variable.
66,306,812
66,307,077
try_emplace doesn't work (as desired) when you have an inheritance structure for the value type?
// A couple of simple structs that inherit AND have different ctor arguments struct A { A(int) {} }; // Note that "B" is a subclass of "A", which is important below struct B : A { B(int, char) : A(0) // The 0 doesn't matter {} // Note that B has no data members that "will be chopped" }; // A simple map......
You cannot put a B into an A. You can slice a B into an A. Slicing refers to copying the A part of B into an A object, In C++ variables are their type. They are not a different type, even if that other type would fit in the storage. Pointers and references can refer to the base class component of a class. But values...
66,307,049
66,307,535
Restricting an enum class template to a labeled type
I want to use enum class <NAME> as a bitmask. I've written the following concept restricting the use of the templates for only Enum classes: template <class E> concept Enumeration = std::is_enum_v<E> && !std::convertible_to<E, std::underlying_type<E>>; Now using this concept to make an add template: template <...
You can tag arbitrary types with arbitrary tags in many ways. Here is one that is visually pleasing: using Conceptually = void; enum class MyBitmask : ...; Conceptually IsBitmask(MyBitmask); // no need to define the function enum class NotABitmask : ...; // nothing Then use it in templates: template <typename T>...
66,307,109
66,307,157
How to correctly swap void pointers?
I have a task: I need to swap an elements in array, by "void pointers based" swap function. Its a simple bubble sort algorithm. But my void SwapInt(void *x, void *y) function doesnt work! I mean it called correctly, but did nothing. My pre-sorting array doesnt change. What could be wrong here and how it fix? void SwapI...
You can't swap integers by swapping pointers, you have to dereference the pointers. And to do that you have to cast them to the int pointers that they really are. void SwapInt(void *x, void *y) { int temp = *static_cast<int*>(x); *static_cast<int*>(x) = *static_cast<int*>(y); *static_cast<int*>(y) = temp; }...
66,307,235
66,307,791
Minimising the MPI broadcast for massive data
I am making a large block of data in each process and I need to share these data between the processes by MPI broad casting, How can I minimise the cost or is there any algorithm for broadcasting the massive data between processes by MPI?
How can I minimise the cost or is there any algorithm for broadcasting the massive data between processes by MPI? Bear in mind that MPI_Bcast: During a broadcast, one process sends the same data to all processes in a communicator. If that is what you want you will have to rely on the underling hardware and on that ...
66,307,459
66,309,471
How to resolve error: invalid use of incomplete type ‘GdkSurface {aka struct _GdkSurface}’?
Questions about incomplete type errors have already been asked here often, but all of the solutions provided there do not help in my case. Adding a forward declaration makes no sense, as GdkSurface has been forward declared already in the Gdk headers. Including the appropriate headers has already been done. Following t...
It seems this type is private to GDK by design (only a forward declaration is provided). From the GDK4 documentation: The GdkSurface struct contains only private fields and should not be accessed directly. See here for the header in which it is defined (which is not distributed). This is why you get these errors, all...
66,307,659
66,307,940
Iterating over vectors in C++ and erasing certain elements
Just to provide background, I'm trying to write a function in C++ that takes a vector of ints and a particular int, and removes all of the elements of the vector in place that match the particular int, while returning the number of times it appears. I'm not asking for help solving the problem. I am stuck trying to figu...
Besides the problems suggested in the comments that you just fixed, your code works fine. You are also not updating output anywhere so the function always returns 0 instead of the number of times the int appears in the passed vector. I edited your function a little and it's good to go: int removeElement(vector<int>& nu...
66,307,834
66,308,610
Why does overload resolution prefer a move constructor over a non-special constructor when equally good conversion functions are available?
The following program: #include <iostream> struct A { A() { std::cout << "A()\n"; } A(int) { std::cout << "A(int)\n"; } }; struct C { operator int() { std::cout << "operator int\n"; return 42; } operator A() { std::cout << "operator A\n"; return A(); } }; int main() { auto a = A{C{}...
It appears that both GCC and Clang implemented a fix for CWG2327 by directly considering conversion functions to cv T as candidates when initializing an object of type cv2 T, in addition to constructors. When C::operator A() is considered as a candidate itself, it is an exact match, and therefore prevails over the cons...
66,308,313
66,329,006
2D AABBTree in CGAL with custom property map
I am trying to create an AABBTree for checking in which triangle of a 2D mesh some points are. To do that, I am using CGAL, in particular, the Polygon_mesh_processing package and the location functions. However, this feels an impossible task to me. Since I want to check several points and I care about performance, I wa...
Try the following: #include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/AABB_tree.h> #include <CGAL/AABB_traits.h> #include <CGAL/AABB_face_graph_triangle_primitive.h> #include <CGAL/Polygon_mesh_processing/locate.h> namespace { using K = CGAL::Simple_cartesian<double>; using Point2 = K::Po...
66,308,329
66,308,351
c++ std::sort function with customized comparator endless loop
The following code is endless in https://www.onlinegdb.com/online_c++_compiler int size = 17; vector<vector<int>> p = vector<vector<int>>(size,vector<int>(1,0)); sort(p.begin(), p.end(), [](vector<int> const& lhs, vector<int> const& rhs){ return true; }); However, if you replace size from 17 to 14, it work...
The comparator must induce a strict weak ordering, which yours does not. So your code has Undefined Behavior.
66,308,403
66,621,224
Off-by-one errors when reading a file one chunk at a time
ifstream::readsome is notoriously bad for reading chunks of a file due to implementation-defined issues. In my case, MSVC returns 0 on a freshly opened file. I looked at their implementation and realized they're just calling ifstream::read under the hood: MSVC Implementation streamsize __CLR_OR_THIS_CALL readsome(_Elem...
I don't use get very often so I forgot it existed. Using this answer as a guide I came up with a solution: (I double-checked, the other answer that uses FormattedInput as (ifs >> std::noskipws >> ch) gives the same results even though the get spec says it treats it as UnformattedInput) [[nodiscard]] std::optional<std::...
66,308,463
66,308,505
memcpy array of classes revisit
Reference: Can I use memcpy in C++ to copy classes that have no pointers or virtual functions The above thread caused a storm surrounding the viability of straight memcpying non std::is_pod (plain old data) structs/classes, however, isn't std::is_trivially_copyable sufficient to allow the memcpy of an array of classes?...
isn't std::is_trivially_copyable sufficient to allow the memcpy of an array of classes? Yes, it is sufficient. Your example has no UB. That said, you don't necessarily need to restrict yourself to using std::memcpy because you can use std::copy_n (or std::copy) instead, and that will work with all copyable types, not...
66,308,726
66,308,775
Multiple definition of a variable in C++ classes
Assume these two cpp files: 0.cc #include <iostream> class test{ public: int num = 5; }; int main(){ test t; return t.num; } 1.cc class test{ public: int num = 6; // <-- note this has a different value. }; We compile it with g++ 0.cc 1.cc. Initializing a member variable inside the class works since C++11. My ...
Yes, it's a violation of One Definition Rule and it's Undefined Behavior.
66,309,276
66,309,629
Why does C++20 std::condition_variable not support std::stop_token?
In C++20 Standard library std::condition_variable_any::wait() family support std::stop_token for generalized thread cancellation, but std::condition_variable does not. P0660R10 Stop Token and Joining Thread, Rev 10 says: New in R6 User condition_variable_any instead of consition_variable to avoid all possible races, ...
Yes, there is a race condition. In general with a condition variable, you must hold the mutex for some period between modifying the guarded state (usually a variable) and signaling the condition variable. If you do not, you can miss a signal. Making your state an atomic variable does not avoid that problem. The wait c...
66,309,777
66,309,794
why does AND in parenthesis evaluate differently than without?
In C++, 4&1 == 0, and 1&1 == 1. However, 4&1 != 1&1 evaluates to 0, instead of 1, yet (4&1) != (1&1) evaluates to 1 as expected. Why is this?
The relational operator != has a higher precedence than bitwise AND &. Thus the expression 4 & 1 != 1 & 1 will be parsed as 4 & (1 != 1) & 1
66,309,858
66,403,643
How to split OpenCV matrix while retaining continuity?
I am trying to make a visual odometry algorithm work in real time (using my stereo camera). The camera feed gets returned as a single image (i420 pixel format), where I have to manually split the image into a left and right frame. One of the problems that I am running into is when I call cv::triangulatePoints. The func...
The solution to this problem is actually quite simple: if (!frame_right.isContinuous()) { frame_right = frame_right.clone(); if (!frame_left.isContinuous()) { frame_left = frame_left.clone(); By using the clone() function, you can copy the image and OpenCV will consider it to be a new i...
66,309,921
66,309,934
Function that receives iterators and returns vector
I was given a task to create a function identical to the following template <typename It> auto MakeSet(It range_begin, It range_end) { return set(range_begin, range_end); } But it must be a template that receives iterators (begin() and end()) and returns a vector with the element's from the range. I tried templat...
You can get the element's type from iterator, and specify it as template argument for std::vector. template <typename It> auto MakeVector(It range_begin, It range_end) { return std::vector<typename std::iterator_traits<It>::value_type>(range_begin, range_end); } Since C++17, with the help of deduction guides you c...
66,310,054
66,310,145
Multiple same class instances in single parent class
I am trying to have multiple instances of the same class in a parent class. Each with their own constructor arguments. I have tried this, but not sure how to fix this. Any help would be greatly appreciated. Base.h class Base { public: Base(int a, int b); }; Parent.h #include "Base.h" class Base_A :Base{}; cla...
You don't have constructors for the Base_A class and Base_B class (which takes two integers as arguments). This is exactly what the compiler is showing us with an error. So all what we need to do is define the constructor. class Base_A : Base { public: Base_A(int a, int b) : Base(a, b) {} }; class Base_B : Base ...
66,310,183
66,310,222
const char* const array
I had a qestion, how can I update an array with more items, here let me show you what I mean. const char* const Foo[] = {"Foo", "Bar"}; const char* const Bar[] = {"Bar", "Foo", "Foo Bar"}; Foo = Bar; Basically updating "Foo" to "Bar"; How could I attempt this?
You cant, at lease like that. There are two reasons, You cant assign an array to another array in C++. What I understand by Basically updating "Foo" to "Bar"; is you trying to add {"Bar", "Foo", "Foo Bar"} to {"Foo", "Bar"}. If so, you don't have the capacity in the Foo array. What you need here is std::vector. This ...
66,310,201
66,311,637
Selection of istream from cin or file with ternary operator
I would like to have a member variable of a class which stores the input stream depending on a string entered by the user. eg. #include <string.h> #include <iostream> #include <fstream> class myInput { public: myInput(std::string file_name); myInput() = delete; protected: std::istream& in_data; }; myInp...
std::istream does not allow you to do something like in_data = std::cin or in_data = std::ifstream("file.txt") as the assignment operator is deleted. An alternate solution is to use a pointer to std::istream. class myInput { public: myInput(std::string file_name); virtual ~myInput() { if (bIsHeapAllocated) dele...
66,310,378
66,311,113
How to open C++ made exe files on a click?
I usually compile my code using MinGW and write C++ IN Notepad++. Whenever I compile my files using this command : cd "$(CURRENT_DIRECTORY)" g++ "$(FILE_NAME)" -o $(NAME_PART) -march=native -O3 NPP_RUN $(NAME_PART) It gives me the exe output , which is all fine. But....if I try to open the exe files it shows the CMD f...
add this before your return statement system("pause"); like this #include <iostream> using namespace std; int main() { cout << "hello world" << endl; system("pause"); return 0; } it will stop the window from terminating
66,310,581
66,310,763
Problem with count the decimal part by C++?
I'm a newbie in C++. I got trouble when count the decimal part by C++, here is the example and code: example: 3.01: count of decimal part is 2 103.939: count of decimal part is 3 code: int result = 0; double d = 4.01; while(true) { cout << "(int)d: " << (int)d << endl; if(d == (int)d) break; d *= 10...
Since your question has been answered in the comments, I am posting a different approach to count decimal digits ( by taking input as string and treating the entire thing as string operation ). #include <iostream> using namespace std; int main() { string d; cin>>d; int flag=0, count=0, pos; ...
66,312,383
66,314,063
Zero-dependency traits definition
I am experimenting and trying to make a template policy-based meta library. Example case is aggregating 2 classes for a device driver. The classes implement device_logic and connection_logic, they don't need to depend on each other's type: device logic depends only on a communication protocol (messages). connection_lo...
Is it a legit approach? Wouldn't it be confusing for a class provider? standard uses different approaches: presence of type such as transparent comparers which should have a "type" is_transparent (as using is_transparent = void;) specific tags as iterator_tags. or even just duck-typing (no check for template) Or ...
66,312,775
66,313,084
Is it legal in C++ to specialize std::minus for user-defined types?
Does the standard library permit users to specialize function objects like std::plus and std::minus for custom types? If the answer to my first question is yes, are users allowed to change the declaration of the call operator? For example, since C++14 std::minus::operator() is declared as follows: constexpr T operator(...
The rules for extending namespace std says: It is allowed to add template specializations for any standard library class template to the namespace std only if the declaration depends on at least one program-defined type and the specialization satisfies all requirements for the original template, except where such spec...
66,313,086
66,313,135
Change the array end
I have int arr[10] and I want the change the array size manually to be 5 I tried: int arr[10]; for (int i = 0; i < 10; i++) { arr[i] = i + 1; } arr[5] = nullptr; But this didn't work and the array size still 10.
Arrays have a fixed size. One of the many reasons you should be using a vector instead. It's easy to change the size of a vector. Like this #include <vector> std::vector<int> arr(10); // vector has size 10, note use (10) not [10] for (int i = 0; i < arr.size(); i++) // use size() to get the vector's size ...
66,313,407
66,341,364
link fortran and c++ using CMake - skipping incompatible ... Error
One colleague did send me a Fortran function to include in my C++ program. So far, everything in my program is coded in C++. To keep things simple (especially dependencies and installation) I thought I'll just re-code it in C++. Unfortunately, the code is very complex with many goto statements and other stuff I'm not v...
I think your C++ code is missing extern "C" and some additional corrections to the Fortran code. For example, the following would work: #include <iostream> extern "C" { double f_add(double, double); } int main() { double a = 1.; double b = 2.; double c; c = f_add(a, b); std::cout << c << std::en...
66,313,514
66,314,280
Stuck on recursion algorithm in arrays
I got stuck with the following task: "Write a recursive function that takes a one-dimensional array of 100 randomly set integers and finds the position at which a sequence of 10 numbers begins with the minimum sum". I've written 2 functions: int recursiveArrSum(int mass[], int dim = 10, int sum = 0) { if (dim == 0)...
This is how I would do it: A function that keeps in its arguments the current position, the current sum, the minimum sum and the starting position of this minimum sum. The function also transports as arguments the array (obviously), its size and the dimension of the sum (10 in your case). void compute(int mass[], int m...
66,313,527
66,313,674
c++ overriding exception::what()
I have a custom exception which is class RenterLimitException : public std::exception { public: const char* what(); }; What is the proper way to override what()? For now, I created this custom in a header file and want to override what() in my cpp file. My function is defined as following: const char* RenterLimitE...
That is not the correct signature for the what method, you should be using const char * what() const noexcept override as per the following complete program: #include <iostream> class RenterLimitException : public std::exception { public: const char * what() const noexcept override { return "No available c...
66,313,864
66,314,049
How to have a refernce type in a struct c++
So I am trying to make a neural network in c++ to help me learn the language, I have come across an issue in which inside a struct I would like to have a reference to an object. In my neuron class, I would like to have a vector of the struct Connection, this connection struct will store a neuron and a weight. The issue...
Whenever you write something like this: struct Connection { Neuron neuron; // not a reference nor a pointer double weight; }; the compiler needs to know already what Neuron is, because neuron is a "true" object of that class, blood, bones, and skin; so it needs a definition of it, e.g. struct Neuron { /* stu...
66,314,083
66,314,327
Question about the condition of a while loop regarding a particular example
This function is supposed to add one string to another: char* myStrCat(char* str1, const char* str2) { int i, j = 0; for (i = 0; str1[i]; i++); while(str1[i + j] = str2[j]) { j++; } return str1; } Which works perfectly fine however, I do not understand why this while condition gives us the wanted output. As far ...
Its because in C++ the assignment operator "returns" the assigned value, to enable statements such as i=j=1 Therefore str1[i + j] = str2[j] evaluates to the value of str2[j]. And because it written as the condition of the while loop it will be converted to bool (from char). The conversion rule is: zero becomes false, ...
66,314,174
66,314,262
Why will the following code display No output?
The following code was an MCQ question in a past university exam : Can you explain to me the logic behind these two if statements too. bool s=37%50<=0; int x=2; if(s) if(x>0) cout<<"Great"; else cout<<"News"; This code dispalys: a)Great News b)Great c)News d)No output
The above is the same as writing: bool s= 37%50 <= 0; int x=2; if(s) { if(x>0) { cout<<"great"; } else { cout<<"news"; } } Since s will be false (37%50 is not <= 0), nothing will be displayed.
66,314,502
66,314,585
what will happen is c++ discard friend keyword?
I am confused on friend function and friend class in c++. and in my coding experience, i never used friend. and even not found others's code contains friend. i know the basic usage and idea of friend. and typical demo is like: #include <iostream> using namespace std; class Box { double width; public: friend void ...
What you already seem to know... This: void Box::printWidth() { cout << "Width of box : " << width <<endl; } Is a definition for a member function. But this: friend void printWidth( Box box ); declares the free function printWidth as a friend of the class. Not everything must be / should be a member. If some other...
66,314,795
66,315,655
How do I chop up a string into parts and read them as a hexadecimal value?
So I want to build a simple calculator program with hexadecimals as their input. But the input would also contain both the operation and the numbers to operate. The first two hexadecimals would be the math operations which are 01 = addition, 02 = subtraction, 03 = multiplication, and 04 = division, and the following fo...
For the splitting, doing something like this should produce the result you want, so long as it's always a consistent 2 (or whatever) characters. std::string nums = "010306"; int splitLength = 2; std::vector<std::string> substrings; for (int i = 0; i < nums.length(); i += splitLength) { substrings.push_back(nums....
66,314,818
66,315,130
How to get global geometry of child widget
I have label inside custom frame. I try to movement of MainWindow (all aplication) on mouse event: void settingslogolabel::mouseMoveEvent(QMouseEvent *ev) { if ((ev->buttons() & Qt::LeftButton) && firstCIsNotNull){ window()->move( mapToGlobal(ev->pos() - m_dragPosition - this->geometry().topLeft())); ...
Not sure I fully understand the problem but, the global coordinates of the top left corner of a widget can be found -- from within that widget's member functions -- using... mapToGlobal(QPoint(0, 0)); Similarly, the global geometry would be... rect().translated(mapToGlobal(QPoint(0, 0))); Edit: If the aim is to allow...
66,315,119
66,315,220
Class member pointer's property returns a random value
I am implementing a LinkedList in C++. After initializing the LinkedList, the value of the head is returned correctly (0). However, after calling another function from the LinkedList, the value of the head suddenly changes (825533248 is outputted). This seems strange, considering that I did not make any modifications t...
Node headNodeObject = {v, true, NULL}; This object is stack-allocated, which means it's destroyed at the end of its scope: your constructor. Keeping a pointer on it and dereferencing that pointer after it's destroyed is Undefined Behavior (might display junk, might crash, ...). Make an heap-allocated object instead: h...
66,315,244
66,315,400
Why is this loop being endless?
I have been programming for a long time and stumbled across something very weird. Somewhere in my code I had the following code: for(int i = 0; i < 512; i++){ if((i * 12391823) % 5 == 1){ std::cout << i << std::endl; } } I have already tracked the problem down to this piece of code. I am using CLion. W...
I do wonder why this would lead to the loop not ending. It seems to overflow, yet it is not supposed to change i and therefor end the loop at some point, right? The answer is "Undefined Behaviour is undefined". It can do anything. But, the fact that you get a warning from aggressive-loop-optimizations may hint at the...
66,315,450
66,315,508
Why is my C++ code adding nonsense to the end of my ASCII string?
I'm quite new to C/C++, and I'm putting together a bad knuckle tattoo generator to get used to using strings and seeded random values. The programme should initialise a 9-character string to hold the final knuckle tattoo, generate 2 random sequences of 4 letters using their ASCII values, and then output this to the con...
You forgot the room of the null terminator/character (\0) to terminate the character string. So make your array bigger and set the last value to \0. Use std::string next time.
66,315,578
66,315,954
Explicitly serialize Slice object to string or ostream in C++
Is there a way to explicitly serialize a Slice object to a string using ice? The problem is that there is an object which must be sendable by json / xml / ice and since ice already has a platform independent object in the Specification Language for Ice(Slice), there is no need to include another library like protobuf. ...
You can serialize the object in the Ice binary format using the OutputStream API Ice::ByteSeq inParams, outParams; Ice::OutputStream out(communicator); out.startEncapsulation(); Demo::CPtr c = new Demo::C; c->s.name = "blue"; c->s.value = Demo::blue; out.write(c); out.writePendingValues(); out.endEncapsulation(); out.f...
66,315,641
66,315,827
How to access class member function in a namespace in C++
I've got a namespace. The class is in a namespace. namespace SALES { class Sales { ... I've created functions. void SALES::Sales::set() { ... Now I'm creating an object SALES::Sales interactive (); but I can't get to methods. Point my error out, please. interactive.set(); // doesn't work SALES::intera...
The way to access non-static members of a function is by using the member of object operator. For example, class SomeObject { public: SomeObject() {} void SayHello() { ... } int age = 10; }; // When calling members. SomeObject object; object.SayHello(); int age = object.age; And when instantiating, ...