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
69,663,059
69,666,073
C++/OpenGL/GLSL Blending two textures edges
Firstly here is the screenshot: I am trying to blend in multiple textures on the mesh based on the height of the point on mesh. Now what i want to achieve is a smooth blend at the borders(unlike what is currently a sharp line). Also i would like the border to be slightly random and have a factor to control the randomn...
Thanks to Frank's answer, I am able to finally have something i like, Here is the result: https://youtu.be/DSkJqPhdRYI The Code : #version 430 core out vec4 FragColor; #define NUM_TEXTURE_LAYERS 8 uniform vec3 _LightPosition; uniform vec3 _LightColor; in float height; in vec3 FragPos; in vec3 Normal; in vec2 TexCoo...
69,663,253
69,663,664
Segmentation Fault in dynamically array creation
I was making a cpp program in which it takes two input from the user which determine the size of the 2d array and pass the values to the mat class constructor and dynamically create an array of the user's defined size. But, I don't know why it is not working and showing segmentation fault #include<iostream> using names...
The class contains several errors. The variable a is never initialized. When we try to address the memory pointed to by a we get a segmentation fault. We can initialize it like this a = new int*[r] We should not change where a point's to, so don't use a++. Otherwise a[i][j] will not refer to the i'th row and the j'th ...
69,663,943
69,664,066
C++ template with condition for type
I have class with template. I want to add template condition for one of the class methods. The idea is for float types I want separate passed method to call this with some epsillon value. Is it possible? The example what I want: template<typename ValueType> class Comparator { public: ... bool passed(ValueType actualV...
You are most of the way there already. In order to overload SFINAE, you need to use a non-type template parameter with an assigned default value instead of using defaulted type template parameter. So, we change both functions to use a non-type paramere with a default value, and just negate the condition like: template...
69,663,947
69,664,034
Get the common value between 2 vectors from the reverse order
So I need the common value between the 2 vectors from the end or in the reverse order. AND once I find the common value, I don't care whether there exists more common values or not. Okay, It sounded pretty easy to me also at first, but now I've looked at more vector syntaxes than ever in a single day. So, finally I'm a...
With reverse iterators, iterating backwards is as simple as iterating forwards. You just need a loop that increments two iterators in parallel and check whether the elements are equal: #include <iostream> #include <vector> int main() { std::vector<int> v1{32, 64, 90}; std::vector<int> v2{32, 64, 78}; auto ...
69,664,192
69,664,290
Swapping elements efficiently in C++ vector
Basically, I have a vector vect. I want to move part of vect from the end, to the start, efficiently. Example: vect before = {1,2,3,4,5,6,7} Moving the last two elements from end to start: vect after = {6,7,1,2,3,4,5} Now, I have the following function: template <class ElementType> void endToStart(std::vector<ElementTy...
It looks like you need std::rotate: #include <algorithm> // std::rotate #include <iostream> int main() { std::vector<int> vect = {1,2,3,4,5,6,7}; std::rotate(vect.begin(), vect.begin() + 5, vect.end()); // ^^^^^^^^^^^^^^^^ // the new first position ...
69,664,215
69,664,789
Access child in nested vector of unknown depth using vector of indexes
My goal is to be able to have a vector of indexes and navigate to that in a class with a vector of variants of vectors and that class. Say I have an "index vector" of unknown size with {0, 4, 7, 2} I would want to somehow use that to access someVector[0][4][7][2]. someVector is of a class node defined as: class node { ...
With C++20 you can do it like this: node accessNode(node n, std::span<unsigned int> span) { return span.size() ? accessNode(n[span[0]], span.subspan(1)) : n; } example usage: std::vector<unsigned int> coordinates = {0, 4, 7, 2}; accessNode(someNode, coordinates); note: Handling exceptions from bad indices or chil...
69,664,337
69,665,821
Max value 2d array using pointer arithmetic
I'm trying to write a programm to find a maximum value in column in a initialized 5x5 matrix, and change it to -1. I found out the way to do it, but i want to find a better solution. Input: double array2d[5][5]; double *ptr; ptr = array2d[0]; // initializing matrix for (int i = 0; i <...
Below is the complete program that uses pointer arithmetic. This program replaces all the maximum values in each column of the 2D array -1 as you desire. #include <iostream> int main() { double array2d[5][5]; double *ptr; ptr = array2d[0]; // initializing matrix for (int i = 0; i < 5; ++i) {...
69,664,366
69,664,467
Change in temperature file not detected
I'm writing a C++ program to run on my raspberry pi 3b+ that monitors the temperature of the CPU in real-time.In order to avoid polling, I'm using the sys/inotify library to watch /sys/class/thermal/thermal_zone0/temp for file updates. However, this doesn't seem to pick up changes to the file. To test this: I polled t...
It's not a real file, whenever you read it, the driver is asked to produce the data in it. There is no way to get notified when its contents would change. Polling is the answer. https://www.kernel.org/doc/html/latest/filesystems/sysfs.html On read(2), the show() method should fill the entire buffer. Recall that an att...
69,664,392
69,664,427
How to Have Preprocessor Statements in Header File Depend on Which C++ File is Including It
How can I exclude certain #include statements in my .h file depending on which .cpp is including the .h file? Example: main.cpp file <tell the header.h file that main.cpp is including it> #include "header.h" other.cpp file <tell the header.h file that other.cpp is including it> #include "header.h" header.h file <if ...
The typical way to do this is to expect source files to #define a macro prior to including the header: // the_header.h #ifndef MY_HEADER_H_INCLUDED #define MY_HEADER_H_INCLUDED #ifdef MY_PROJECT_MAIN // ... #else // ... #endif #endif In files using the header's "default" behavior // some_code.cpp // Just use the h...
69,664,451
69,664,625
Explicit instantiation of template class with templated member functions
With a class defined as follows: template <typename T> class A { private: T a; public: A(T& a) : a_(a) { } template <typename D> void Eval(D& arg) { // ... } }; template A<int>; I want to explicitly instantiate one instance of the class, and I want this class to have one exp...
The ambiguity is not coming from anything to do with template instantiation of the class, it's caused by Eval also being a templated function. &A<int>::Eval does not point to a function, it points to a template. And there is just no such type as a "pointer to a template". If you want a pointer to A<int>::Eval, you need...
69,664,773
69,665,608
Illegal operand error on a function pointer iterator
I am getting the following errors: '<': illegal, left operand has type 'const_Ty' '>: illegal, right operand has type 'const_Ty' in the below code. It's a relative simple iterator on a function pointer map where the functions are of the form void (Game::*)(UINT). I check the value against a float, then run the functi...
Member function pointers don't implement operator<, which is the default sorting function std::map uses. Member function pointers only implement operator== and operator!= . An easy way to fix this woud be to have a separate key and put the function pointer into the value of the map, e.g.: std::map<int, std::pair<FuncPt...
69,664,848
69,665,023
How do this program but in reverse, pattern
so i want output like this 1 123 12345 123 1 i already make the program but it only output these, and im confused how to output the bottom triangle 1 123 12345 here's my program #include <iostream> using namespace std; int main() { int n = 3 ; int i, j, k; for (i = 1; i <= n; i++) { ...
I added another for loop exactly like yours with different order from n-1. I modified your code to this: int main() { int n = 3 ; int i, j, k; for (i = 1; i <= n; i++) { for (j = n; j > i; j--) { cout << " "; } for (k = 1; k <= (2 * i - 1); k++) { cout << k;...
69,664,907
69,664,988
using a shared_ptr object in constructor works but not in destructor
I have a class where the construction is like: class CLSS { public: CLSS(const std::shared_ptr<someType>& pobj) { std::shared_ptr<someType> obj = pobj; obj->somefunc("DDDD") } ~CLSS() { } }; which works with now problem. However when I put the same function of obj->info("DDDD")...
obj is a local variable in the constructor. It is destroyed when the constructor ends. You need to declare it as a member of your class.
69,664,927
69,665,260
how to write this function in C++ using meta programming
What are you trying to achieve I want to convert RetType ClassA::MemberFunc(Args...) to mem_fn(&ClassA::MemberFunc) but it is like a function in order to avoid write lambda or function for every member functions What did you get out (include error messages) no matching function for call to ‘regisAdd(std::_Mem_fn<in...
As I understand, you want something like: template <auto mem> // C++17, else <typename T, T mem> struct mem_to_func; template <typename C, typename Ret, typename ... Args, Ret (C::*m)(Args...)> struct mem_to_func<m> { static Ret func_ptr(C* c, Args... args) { return (c->*m)(std::forward<Args>...
69,665,119
69,669,576
How to define boost tokenizer to return boost::iterator_range<const char*>
I am trying to parse a file where each line is composed by attributes separated by ;. Each attribute is defined as key value or key=value, where key and value can be enclosed in double quotes " to allow for key and value containing special characters such as whitespace , equal sign = or semi-colon ;. To do so, I use f...
As I said, you want parsing, not splitting. Specifically, if you were to split the input into iterator ranges, you would have to repeat the effort of parsing e.g. quoted constructs to get the intended (unquoted) value. I'd go by your specifications with Boost Spirit: using Attribute = std::pair<std::string /*key*/, // ...
69,665,447
69,665,498
Read in arrays from a files and store them into struct members
Suppose I have a struct like this: struct Person { string fName; string lName; int age; }; And I want to read in a file(ppl.log) like this: Glenallen Mixon 14 Bobson Dugnutt 41 Tim Sandaele 11 How would I read in the file and store them? This is what I have int main() { Person p1, p2, p3; ifstream fin; f...
I recommend overloading operator>>: struct Person { string fName; string lName; int age; friend std::istream& operator>>(std::istream& input, Person& p); }; std::istream& operator>>(std::istream& input, Person& p) { input >> p.fName; input >> p.lName; input >> p.age; input.ignore(10000, '\n');...
69,665,485
69,695,741
Replace C++ class/static method with preprocessor?
I'd like to use the built-in compiler checks to verify format strings of a custom logging framework to catch the odd runtime crash due to mismatching format string <-> parameters in advance. Arguments of the custom C++ logging methods are identical to the printf() family so I was attempting to replace all calls to MyLo...
Elaborating on the approach suggested by @Someprogrammerdude I've extended the custom logging class to use the clang/gcc format attribute to enable compiler format checking. The declaration simply becomes static void Error(const char *format,...) __attribute__ ((format (printf, 1, 2))); It's even better than the o...
69,665,635
69,665,997
How to use std::ranges on a vector for a function that needs two arguments?
I have been trying to understand the new ranges library and try to convert some of the more traditional for loops into functional code. The example code given by cppreference is very straight forward and readable. However, I am unsure how to apply Ranges over a vector of Points that needs to have every x and y values l...
The algorithm you're looking for is combinations - but there's no range adaptor for that (neither in C++20 nor range-v3 nor will be in C++23). However, we can manually construct it in this case using an algorithm usually called flat-map: inline constexpr auto flat_map = [](auto f){ return std::views::transform(f) |...
69,665,736
69,665,869
How to dynamically allocate 2D array of pointer that's 64B aligned using posix_memalign
I have two arrays, y_train which is a 1D array, and x_train which is a 2D array. I need to dynamically allocate these two arrays using posix_memalign. I did that for y_train correctly. where I convert int y_train[4344] into the following code. int* Y_train; posix_memalign((void**)(&Y_train), 64, sizeof(int) * 4344);...
Get a memory block of the complete size and assign it to a pointer of the correct type: void *ptr; posix_memalign(&ptr, 64, sizeof(int) * 4344); int *Y_train = (int*)ptr; posix_memalign(&ptr, 64, sizeof(int) * 20 * 4344); int (*x_train)[20] = (int (*)[20])ptr; Now the whole 2D array is correct aligned, but not all inn...
69,666,181
69,667,132
c++ sort and quick sort algorithm and for loop question
Please could you help me to understand the below code from a book? I am wondering why " swap(words, start, current); " is not part of the for loop within the below code? The final effect of the "for loop - check words against chosen word" should be to position all the words less than the chosen word before all the word...
What's going on is that the middle value of the array is being chosen as the pivot value and move "out of the way" to the start of the array: swap(words, start, (start + end) / 2); The loop then process all values from start+1 to end inclusive so that once it is complete all values from start to current inclusive are ...
69,666,375
69,669,120
Clang compilation : "Cannot execute binary file"
I am new to the clang++ compiler flags. I have an issue regarding compilation. Here is my cmd: clang++ -I ../llvm-project/llvm/include -I ../llvm-project/clang/include -I ../llvm-project/build/tools/clang/include -I ../llvm-project/build/include -O3 -c $(llvm-config-7 --cxxflags) projectToTestHeadersBuilding.c...
In your initial command you use the -c flag which makes clang output an object file. This is part of a compiled program but not a complete executable, in order to get the final executable you must perform a linking step, usually with other object files. A simple compilation can be done as so: clang++ projectToTestHeade...
69,667,470
69,668,438
C# Program Can't Get Byte Array Back From A C++ COM Program
I can't seem to get a byte array in a C# program filled from a COM C++ program. The C# program includes a reference to the C++ DLL and is instantiated by: _wiCore = new WebInspectorCoreLib.WICore(); Actual call uint imageSize = *image byte count*; // set to size of image being retrieved var arr = new byte[imageSize];...
There are multiple ways to pass an array back from C++. For example, you can use a raw byte array like you were trying to do. It works but it's not very practical from .NET because it's not a COM automation type which .NET loves. So, let's say we have this .idl: interface IBlah : IUnknown { HRESULT GetBytes([out] i...
69,668,237
69,668,647
C++ primer template universal reference and argument deduction
Hello I have this example from C++ primer: template <typename T> void f(T&& x) // binds to nonconstant rvalues { std::cout << "f(T&&)\n"; } template <typename T> void f(T const& x) // lvalues and constant revalues { std::cout << "f(T const&)\n"; } And here is my attempt to test the output: int mai...
The comments in the book are, evidently, not entirely correct. When you have the two overloads available of template <typename T> void f(T&& x); template <typename T> void f(T const& x); both of them can always be called with any argument (with some exceptions that I'll omit here), but the second one will be preferred...
69,668,421
69,668,610
Is there any alternative to using if walls instead of something else in C++?
I'm doing some C++ and my app accepts subcommands, for example ./my_app test 123. I'm semi-new to C++ and I can't find anything on the internet so I don't know haha. For example in python I'd do: #!/usr/bin/env python3 import sys def test(num): print(f"Test {num}") subcommands = {"test": test} subcommands[sys.a...
Have a look at std::map/std::unordered_map, for example: #include <iostream> #include <map> #include <string> void test(const std::string &value) { std::cout << "Test " << value << std::endl; } using cmdFuncType = void(*)(const std::string &); const std::map<std::string, cmdFuncType> subcommands = { {"test":...
69,668,650
69,668,744
Prevent the application from crashing if one of the threads crashed
Is there any way to prevent main thread from crashing? I want the main thread to keep running after this memory access violation exception happens. std::thread { []() { for (auto i = 0; i < 10; ++i) { std::cout << "Hello World from detached thread!\n"; std::this_thread::sleep_for(std...
You could use sigaction to install a handler for SIGSEGV that kept that thread busy while main kept running. static void handler(int sig, siginfo_t* si, void* unused) { sleep(100000); // or something similar that's async-signal-safe // on your operating system } int main(int argc, char *argv[]) ...
69,668,851
69,668,876
Access every member of base template class
When you use template inheritence, you have to explicitly specify what members of base template class you intend to use: template <typename T> class base { protected: int x; }; template <typename T> class derived : public base<T> { public: int f() { return x; } protected: using base<T>::x; }; What if ba...
No. There's no such mechanism in the language.
69,669,173
69,692,403
How to create an algorithm to find all possible pairings (referring to the chinese postman problem)?
When trying to solve the chinese postman problem you will have to find minimum cost of all possible pairings of all odd vertexes in the graph and add found edges (pairings), which my question is almost about. How to implement an algorithm, which returns all possible pairings? or how to fix mine. I got a starting point,...
So I found a solution for the second algorithm I mentioned. The problem was I send the pair to the next recursion step to be then added in this step. So when you returned from a recursion step the pairing would still be in there. So I just deleted this pair, so the new one can be added. Instead of just returning an int...
69,669,265
69,669,390
Incorrect checksum for freed object - problem with allocation
I'm trying to write a class in c++ that creates a dynamic array and I'm encountering this problem malloc: Incorrect checksum for freed object 0x7f9ff3c05aa8: probably modified after being freed. Corrupt value: 0x2000000000000 I implemented three constructors (default, parametrized and copy) and I think this is the one...
The problem is that you deleted c_table in bSetNewSize() and didn't set a new value to it, but used it in a later call. I Think you meant to put a c_table = cTable; to the end of bSetNewSize() function, as 500 - Internal Server Erro commented. Also it is faster if you take the string parameter as a const string& to the...
69,669,438
69,669,510
meaning of inline const char * operator*(AnEnumClass aclassinstance)
What is the meaning of the following? inline const char * operator*(AnEnumClass aclassinstance) { ... } Is it a function call operator overloading of the '*' operator or of the '()' operator? What does it accomplish and what is it used for?
inline // function should be marked as inline. const char * // function returns this operator * // function is the multiplication operator (AnEnumClass aClassInstance) // RHS argument to operator The operator takes as LHS whatever the encapsulating class is. You invoke it with: const char * aString = aClass * aEnu...
69,669,468
69,669,494
Can't change the value of private member of a class using friend class
So I was trying to learn how to change the value of the private class member using friend class, but the friend class cannot change the value of the main class, here is the code I have done, I am new in the world of coding, please help me out :) #include <iostream> using namespace std; class A { private: int marks...
In the function: show_A_marks(A teacher, int num) You are passing teacher by value. You are making a copy of the value, and editing that copy. When the function returns, the copy is gone. You need to pass it by reference: show_A_marks(A& teacher, int num) // ^ reference to A see What's the difference betwe...
69,669,712
70,104,229
gem5: Use xbar stat in BaseCPU
I have created a new stat of type Formula in the xbar.cc/hh files. There I aggregate all the different transDist types. I'd like to use this newly created stat to compute another stat in the BaseCPU object. What is the best way to have access to it (i.e., allTransactions stat) from BaseCPU? Is there any way to make it ...
I ended up having a direct line of comminication between the xbar and the CPU objects. I implemented a function in the Xbar object that returns the statistic that I want, called getAllTrans(). From the CPU object, I call that function and get the value of the statistic. The communication is implemented using the code b...
69,670,234
69,670,254
Multiple constructors in a C++ LinkedList class: non-class type "ClassName"
I have a LinkedList constructor where I can pass in an array and it builds. Then I can add additional nodes to it by passing in integers. However, I also want the option to construct the LinkedList, without any arguments. In my LinkedList.h file I've tried to create a constructor that sets the first and last pointers. ...
The problem has nothing to do with your constructors themselves. LinkedList l(); is a declaration of a function named l that takes no arguments, and returns a LinkedList. That is why the compiler is complaining about l being a non-class type. To default-construct a variable named l of type LinkedList, drop the parenth...
69,670,273
69,670,363
My result is not truly random; How can I fix this?
float genData(int low, int high); int main(){ srand(time(0)); float num = genData(40, 100); cout << fixed << left << setprecision(2) << num << endl; return 0; } float genData(int low, int high) { low *= 100; high *= 100 + 1; int rnd = rand() % (high - low) + low; f...
Wrong range int rnd = rand() % (high - low) + low; does not generate the right range. float genData(int low, int high) { low *= 100; // high *= 100 + 1; high = high*100 + 1; expecting a random number between 40 and 100 inclusively with two decimal places. eg: 69.69, 42.00 That is [40.00 ... 100.00] or 10000-4...
69,670,395
69,677,306
Modern CMake: is there a way to build external projects using a CMakePresets.json?
Disclaimer: I'm rather new to C++ development and handling bigger projects, so this might be a wrong approach or tool, so I am very open to different ideas. I want to be able to provide a sort of package that is a collection of prebuilt libraries / binaries for different platforms, to be used with our other software. I...
You have just described the goal and approach of Conan. It interfaces well with CMake, and uses your "build recipe" approach. You, and Conan, recognize that C++ packages are inherently different from, say, Python or Javascript, in that they have endless variations due to compiler version, libc version, build configur...
69,670,432
69,670,555
IAR EW for ARM 8.50 and oddball char array literal behavior in C++
I'm having some strange constant/literal generation happening in IAR EW for ARM 8.50 when I declare a specific string: const char g_string[]="?????-??"; When I look at it in the debugger, it's actually generating the following in memory: ???~?? If I break the string up like so: const char g_string[]="?????""-??"; I ...
I found my issue, and it's pretty obscure to an american programmer. Trigraphs: https://stackoverflow.com/a/1995134/550235 I guess IAR has them enabled by default and the other compilers I'm using don't. And good luck searching on google for "string literals with ???"
69,670,850
69,671,012
c++ pushing pointer onto pointer priority queue causes immediate valgrind errors
I'm working on a Huffman code implementation in c++, however during the construction pushing a pointer onto a priority queue of class pointers is causing several of the type of valgrind error shown below: ==1158== at 0x40508E: void std::__push_heap<__gnu_cxx::__normal_iterator<Node**, std::vector<Node*, std::allocat...
shoud use pointer in nodeCompare struct nodeCompare{ bool operator()(Node* n1, Node* n2){ return n1->getFreq() > n2->getFreq(); } };
69,671,144
69,681,472
"exited with code 255" when trying to call __device__ function within __global__ function
I have the following test.hpp which declares test(): #pragma once #include "cuda_runtime.h" #include "device_launch_parameters.h" __host__ __device__ void test(); and test.cpp which defines test(): #include "test.hpp" __host__ __device__ void test() { } The following kernel.cu fails to compile (with exit code 255, ...
A comment by @Robert Crovella set me on the right track to solving this issue. I moved test.cpp into test.cu, and test.hpp to test.cuh. Then, I was able to enable separable compilation and device code linking by following these answers: https://stackoverflow.com/a/31006889/9816919 https://stackoverflow.com/a/63431536/9...
69,671,155
69,671,238
C++ understanding constructors in inheritance
I'm currently learning C++ and would like to understand how constructors work in the context of inheritance. Here's my parent and child classes: #include <iostream> #include <string> enum COLOR { Green, Blue, White, Black, Brown, }; class Animal { protected: std::string _name; COLOR _color; p...
There's a specific sequence used for constructing objects, and the inverse sequence is used for destroying them. For construction: Initialization order The order of member initializers in the list is irrelevant: the actual order of initialization is as follows: If the constructor is for the most-derived class, virtua...
69,671,381
69,671,478
Why do I need the extra pair of curly braces when defining an array of pairs?
I'm sorry if this is a common question, I don't know how I'd search for it so I figured it best to just ask. I'm wanting to define an std::array of std::pairs in C++ to store SFML sf::IntRects in. I messed with it for like 10 minutes and finally realized that this compiles: std::array<std::pair<sf::IntRect, sf::IntRect...
std::array is a wrapper template around built-in C-style array. You may think of it as something like template <typename T, std::size_t N> class array { T arr[N]; ... }; Both std::array and built-in C-style array are aggregate types. You initialize it using aggregate initialization syntax. It would be something li...
69,671,457
69,671,574
How does std::priority_queue accomplish O(log n) insertion?
The documentation for std::priority_queue states the complexity of the push operation as: Logarithmic number of comparisons plus the complexity of Container::push_back. And by default uses std::vector as the underlying container. However, push_back can only push elements to the end of the vector, while in a priority ...
while in a priority queue one might need to add elements somewhere in the middle of the vector, in which case all elements that follow have to be shifted to the right No. The right shift does not occur. The new element is added to the end, at index i: O(1) Then its priority is compared to its parent at index i/2 and...
69,671,465
69,672,202
Generating spheres with vertices and indices?
I'm currently working on an OpenGL project where I should currently generate spheres with vertices and indices. All vertices represent a point, and indices tells the graphic card to link 3 points as a triangle. Example : indices : {0,1,2} = it will make a triangle with the first, second and third point. I've managed to...
You have created a sphere of vertices by calculating horizontal circles in multiple vertical layers, a UV sphere. Good. You are just adding indexes once for each vertex for a total of one index per vertex, that is not according to the concept. What you need to repeatedy do is finding the three indexes in your array of ...
69,671,475
69,672,838
Initialise unique_ptr inside class
I want to initialise the unique pointer inside class after declaration and I tried few ways but unable to resolve the errors.. template <typename T> struct Destroy { void operator()(T *t) const { t->destroy(); } }; class Test { std::unique_ptr<IRuntime, Destroy<IRuntime>> runtime; public:...
runtime = std::make_unique<IRuntime, Destroy<IRuntime>> (createIRuntime()); Presumably IRuntime is an abstract class, which can't be constructed directly. But even if it could be constructed as-is, only the 1st template parameter specifies the type to create. The 2nd and subsequent template parameters specify the type...
69,671,647
69,671,676
QObject Child Class Not Detecting QGuiApplication Event Loop
When I try to start a QTimer in a class derived from QObject, I get the warning QObject::startTimer: Timers can only be used with threads started with QThread and the timer doesn't run. Based on answer here, it appears that my custom class is not detecting QEventLoop created by QGuiApplication. My main.cpp ... classA...
I was able to fix the problem by changing the order of declaration of my classA and QGuiApplication. It appears that for any QObject child class to detect QGuiApplication Eventloop, it must be declared after QGuiApplication. My main.cpp: ... QGuiApplication app(argc, argv); ... classA objA; ...
69,671,944
69,674,237
How to stop variable symbols from being exported macOS
So I've got my main program that uses dlsym to find the symbols of 2 functions and a variable from a dylib and I have a variable that I don't want exported. My problem is that whether or not I use extern "C" for the variable dlsym will always find the variable Im not exporting, if I remove extern "C" from the functions...
Hiding symbols using -fvisibility=hidden Exporting Code for the dylib : #define EXPORT extern "C" __attribute__((visibility("default"))) EXPORT char exported_var[2] = { 'a', '\0' }; EXPORT void dylib_quit() { ... } EXPORT void dylib_main() { ... } char hidden_var1[2] = { 'b', '\0' }; char hidden_var2[2] = {...
69,671,972
69,672,170
C++ How can I insert another loop or method to make 100 equivalent to 541?
My goal is to display the first list of prime numbers depending on user's input, when the user input 10, the program should display first 10 prime numbers which are 2 3 5 7 11 13 17 19 23 29. I'm thinking of having generated list from 2 which is the first prime number to 541 which is the 100th prime number then if the ...
Your current algorithm doesn't work, because N is never modified. If the user inputs 101 then nothing will be printed, because if (isPrime == 0 && N != 101) will always be false. If the user inputs anything else then it will always print the first 100 primes. The key idea will be to count how many primes were found and...
69,672,020
69,673,451
cmake equivalent for MakeFile
I followed this answer to create a CMakeLists.txt for a simple Makefile Makefile CC = g++ INCFLAGS = -I/usr/local/include/embree3 LDFLAGS = -L"/usr/local/lib/" -lembree3 RM = /bin/rm -f all: $(CC) -o main main.cpp $(INCFLAGS) $(LDFLAGS) clean: $(RM) *.o main CMakeLists.txt cmake_minimum_required(VERSION 3.1....
Ok, so following your answer to my comments, the problem is that since you starts your include instruction by embree3 (which make sense to avoid names conflict), cmake should have as include directory the directory containing the embree3 installation, not the embree3 folder itself. This is why include_directories(/usr...
69,672,051
69,672,211
wait() for thread made via clone?
I plan on rewriting this to assembly so I can't use c or c++ standard library. The code below runs perfectly. However I want a thread instead of a second process. If you uncomment /*CLONE_THREAD|*/ on line 25 waitpid will return -1. I would like to have a blocking function that will resume when my thread is complete. I...
If you want to call functions asynchronously with threads I recommend using std::async. Example here : #include <iostream> #include <future> #include <mutex> #include <condition_variable> int globalValue = 0; // could also have been std::atomic<int> but I choose a mutex (to also serialize output to std::cout) std::...
69,672,479
69,673,798
Generalizing binary left shift for octal representation without conversion
Currently I have a few lines of code for working with binary strings in their decimal representation, namely I have functions to rotate the binary string to the left, flip a specific bit, flip all bits and reverse order of the binary string all working on the decimal representation. They are defined as follows: inline ...
my understand of rotate_left, do not know my understand of question is correct, hope this will help you. // maxPower: 8 // n < maxPower: // 0001 -> 0010 // // n >= maxPower // n: 1011 // n - maxPower: 0011 // (n - maxPower) * 2: 0110 // (n - maxPower) * 2 + 1: 0111 inline u64 rotate_l...
69,672,489
69,673,601
Sort an array by increasing frequency
Can anyone please explain how to deal with run time error? Line 1034: Char 34: runtime error: addition of unsigned offset to 0x607000000020 overflowed to 0x607000000018 (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vecto...
There're 2 problems: nums[i] is between -100 and 100. The vector v can't handle this case. This could be fixed easily with an offset of 100. vector<pair<int,int>> v(n);. Remember, this is a vector of frequency. It can't handle case like, for example, n = 5 but num[i] reach 50 or 100. This can also be fixed with a dif...
69,673,623
69,677,131
malloc with C struct in C++
I am trying to write some tests in Catch2 (a C++ library) for a simple C library example and I am a little confused about how to initialize a C struct. My C header looks like this: struct node; And my C implementation cannot be simpler: struct node { int num; struct node* next; } Now, the problem is with the test...
Basically everything has already been said in the comments. You are just forward declaring the struct in the header. While it is best practice to use forward declarations to reduce include dependencies in headers that just need to know what something is (e.g. a struct) but not what it contains, it usually doesn't make ...
69,673,767
69,674,555
Template class with template method id
I am trying to create an identifier for my methods. This identifier is important for my work as it is in fact hardware synthesis. I have the following template class: template <int FF_COUNT, int FB_COUNT, int NEXT_COUNT> class Core{ public: ... template<int id> void consume_f...
What your looking for is a for loop at compile time. Because the template parameter must be a constexpr. I usually do it this way since you can't have for loops in constexpr functions: template<int i> struct MyFunc { MyFunc() { // do something with i core[i].consume_fb_events<i>(....); } }; ...
69,674,058
69,674,233
"increment" `std::variant` alternative
I want to increment / decrement a std::variant's type alternative, essentially like so: using var_t = std::variant</*...*/>; var_t var; var.emplace< (var.index()+1) % std::variant_size<var_t> >(); // "increment" case, wrapping for good measure The problem here is that while emplace expects what clang's error message c...
As usual, std::index_sequence might help: #include <variant> template <typename... Ts, std::size_t... Is> void next(std::variant<Ts...>& v, std::index_sequence<Is...>) { using Func = void (*)(std::variant<Ts...>&); Func funcs[] = { +[](std::variant<Ts...>& v){ v.template emplace<(Is + 1) % sizeof...(Is...
69,674,448
69,675,522
Choose n distinct elements from a vector with probability inverse-proportional to their index
Given a vector and a certain number of elements n, I'm looking for a way to choose n distinct elements from a vector with probability inverse-proportional to their index. Example: std::vector v = {0, 1, 2, ... 998, 999}; n = 10; A potential set of chosen indices may be: {50, 200, 350, 500, 600, 700, 800, 850, 900, 950...
This paper describes a weighted random sampling method. Below is a C++ implementation. This is assigning a weight of 1 / index for a 1-based indexing of your data namespace views = std::ranges::views; std::random_device rd; std::mt19937 gen(rd()); // or whichever URBG you want std::uniform_real_distribution<double> di...
69,675,716
69,675,780
What is a legal definition of a pointer to a pointer to a const object?
I know from this answer that a pointer const int** z is supposed to be read as Variable z is [a pointer to [a pointer to a const int object]]. In my humble opinion, this would mean if z=&y then y should be a pointer to a const int object. However, the following code also compiles: int x=0; int const* y=&x; const int*...
You are misunderstanding what the const refers to. A const always refers to the element to the left of it - unless it is the leftmost element itself, in which it refers to the element to the right. This means that int const * is a pointer to a const int, not a const pointer to int as you think. To get that, you would h...
69,675,810
69,675,945
Error when trying to access nativeLibraryDir
i'm trying to access getPackageManager.getApplicationInfo in jni. const char* getNativeLibPath(JNIEnv* env, jobject thiz, const char* libraryName, const char* packageName) { jclass contextClass = env->GetObjectClass(thiz); jmethodID getPackageManager = env->GetMethodID(contextClass, "getPackageManager", "()Land...
Your code has at least three problems: You call getApplicationInfo with a const char * which expects a Java string: jobject instantiateApplicationInfo = env->CallObjectMethod(instantiatePackageManager, getApplicationInfo, env->NewStringUTF(packageName), 0); You need to call env->ReleaseStringUTF(returnValue) to rel...
69,676,420
69,676,660
Detect when 2 buttons are being pushed simultaneously without reacting to when the first button is pushed
I'm programming a robot's controller logic. On the controller there is 2 buttons. There is 3 different actions tied to 2 buttons, one occurs when only the first button is being pushed, the second when only the second is pushed, and the third when both are being pushed. Normally when the user means to hit both buttons t...
You could use a short timer, which is restarted every time a button press is triggered. Every time the timer expires, you check all currently pressed buttons. Of course, you will need to select a good timer duration to make it possible to press two buttons "simultaneously" while keeping your application feel responsive...
69,676,566
69,676,977
Passing object to << overload in alters data in object in C++
I'm trying to write a list class in C++, and I want to overload the << operator. However, when I pass the list object to the operator function, changes the values within the object. Other questions on StackOverflow have not helped resolve this. Superfluous code has been removed from the following: LinkedList.h: #includ...
You need to allocate new nodes with the new operator. This is your corrected code: #include <iostream> class Node { public: int data; Node *next; Node *prev; Node(int data); }; Node::Node(int initdata) { data = initdata; next = nullptr; prev = nullptr; } class LinkedList { public: Node *head; ...
69,676,937
69,677,135
I can't assign the value of a geometry point to a variable
I was trying to assign the value of a geometry point (it has x,y,z. All of them are float64. If you want to check it: http://docs.ros.org/en/noetic/api/geometry_msgs/html/msg/Point.html ) to a float64 variable. But when I compile the code the next error appears: error: request for member ‘data’ in ‘msg.nav_msgs::Odome...
std_msgs::Float64 has a field "data" of type float64. Type of std_msgs::Float64 is not equal to field "y" of type float64 in geometry_msgs::Point. void controlMensajeRecibido(const geometry_msgs::Point& msg) { y.data = msg.y; }
69,677,048
69,677,231
Pointer to portions of array
I have an object of std::vector<std::array<double, 16>> vector entry Data [0] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [1] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [2] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [...] - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 This is intended to repres...
The 3x3 part is not contiguous, hence a pointer alone wont help here. You can write a view_as_3x3 that allows you to access elements of the submatrix of the 4x4 as if it was contiguous: struct view_as_3x3 { double& operator[](size_t index) { static const size_t mapping[] = {0, 1, 2, 4, 5, 6, 8, 9, 10}; ...
69,678,651
69,678,940
free(): double free detected in tcache 2 on calling overloaded assignment operator
I'm working on a university project where we are to implement some of the c++ string class as Mystring. I'm working on the overloaded assignment operator and this is the current code for it: Mystring& Mystring::operator=(const Mystring& orig) { if(this != &orig) { delete ptr_buffer; len = orig.l...
In this copy assignment operator Mystring& Mystring::operator=(const Mystring& orig) { if(this != &orig) { delete ptr_buffer; len = orig.len; buf_size = orig.buf_size; ptr_buffer = orig.ptr_buffer; } return *this; } there are at least two problems. If the array of charac...
69,678,689
69,698,394
Address Sanitizer in MSVC: why does it report an error on startup?
I'm trying a project that uses Qt with MSVC 2019 with Address Sanitizer. I built with Address Sanitizer the project, but didn't rebuild all libs, including Qt. it crashes inside Qt in resource initialization (with qRegisterResourceData in the call stack). Is this: Misuse of address sanitizer, like, I should rebuild Qt...
The issue is load order. Qt happens to load before ASan and load C/C++ runtime before ASan DLLs loaded. Qt performs some initialization. So the memory is malloced without ASan knowledge, and later ASan sees realloc without prior malloc, which it reports. Building Qt with ASan should resolve the issue, I have not tried ...
69,678,864
69,679,086
Safe way to use string_view as key in unordered map
My type Val contains std::string thekey. struct Val { std::string thekey; float somedata; } I would like put my type in an unordered map, with thekey as key. For memory and conversion avoidance reasons I would like to have std::string_view as key type. Is it possible to have the key created to point to val.thekey, whi...
Safe way to use string_view as key in unordered map In general there isn't one, because the storage underlying the view might change at any time, invalidating your map invariants. Associative containers generally own a const key precisely to avoid this. In your specific case it makes much more sense to use std::unord...
69,679,026
69,680,901
Inserting a node in LinkedList is giving segmentation error
struct Node { int data; Node * next; Node (int x) { data=x; next=NULL; } }; Node * insertInSorted(Node * head, int data) { Node* temp = new Node(data); if (head == NULL){ return temp; } if (data < head->data){ temp->next = head return temp; } No...
This while loop while (curr->next->data < data && curr->next != NULL){ curr = curr->next; } can invoke undefined behavior because there is no check whether curr->next is equal to nullptr before accessing the data member curr->next->data. You need to exchange the operands of the logical AND operator like while (cur...
69,679,356
69,683,917
How to read and write large std::vector<std::vector<float>> to file in C++
In the constructor of my program I am generating a very large lookup table of 2048 * 2048 floats using nested std::vector<std::vector<float>>. The lookup table is always the same each time, so I'd like to write this table to a file to save recalculating it. What is the best way to achieve this? Is it best to write the ...
The answer in this case has been to optimise the lookup table generation. I was doing much, much more work than was required, and now load times are practically instant. For those in the future looking at this thread with a similar problem, there is great general advice in the commments. Thanks to the attention of all ...
69,679,649
69,679,884
c++ polymorphic method defined in derived class matches type that should match to the parent
I'm experimenting with this code class Base { public: virtual void foo(int) { // void foo(int) { cout << "int" << endl; } }; class Derived : public Base { public: void foo(double) { cout << "double" << endl; } }; int main() { Base* p = new Derived; p->foo(2.1); Derived d; d.foo(2); // wh...
Polymorphism as in calling virtual methods is orthogonal to symbol and overload resolution. The former happens run-time, the rest at compile-time. object->foo() always resolves the symbol at compile-time - member variable with overloaded operator() or a method. virtual only delays selecting "the body" of the method. Th...
69,680,005
69,680,017
Using two types with one template definition
Is it possible to use two different types, one is a subtype of the other, with one template definition? Something like: template<typename T> void foo(T a, T::bar b);
You would need one more usage of typename template <typename T> void foo(T a, typename T::bar b); because bar is a "dependent type" of T. See here for more details.
69,680,174
69,681,167
Shared pointer to array in pool-allocated memory
I am working on writing a fixed-capacity, copy-on-write "string" class which is capable of using Allocators for its memory allocations. Eventually, I want to be able to have these "strings" use a memory pool which returns fixed-sized chunks of memory. If the "capacity" of the string being created is less than the poo...
I would avoid trying to use shared_ptr for this. Not just because you need C++20 in order for allocate_shared to work on arrays, but also because it is inefficient for your embedded needs. The shared_ptr control block has two reference counts in order to allow for weak pointers. Your particular use case doesn't need we...
69,680,293
69,680,591
How to start a thread in another function but inside IF statement
I have a function that I want to run it inside another function, so the main function I have , have a while loop running and the other function outside also have a while loop, and I wanna run both together without any of each other interrupting each other, so the main function will keep its main while loop running norm...
ITNOA You can change your code like below void MatchChecker() { while (1) { if (g_pOBJ->checkInMatch() == 2) { std::cout << "In Match! " << std::endl; } } void mainFunc() { std::thread checker; whi...
69,680,725
69,680,928
C++ 2D algorithm code is reading the array wrong
Like the title said, my code is reading a 2D array entirely wrong. const int WINNING_ROWS[8][3] = { (0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), ...
const int WINNING_ROWS[8][3] = { (0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), ...
69,680,876
69,680,988
Construction of lambda object in case of specified captures in C++
Starting from C++20 closure types without captures have default constructor, see https://en.cppreference.com/w/cpp/language/lambda: If no captures are specified, the closure type has a defaulted default constructor. But what about closure types that capture, how can their objects be constructed? One way is by using s...
Since this is tagged language-lawyer, here's what the C++ standard has to say about all this. But what about closure types that capture, how can their objects be constructed? The actual part of the standard that cppreference link is referencing is [expr.prim.lambda.general] - 7.5.5.1.14: The closure type associated ...
69,680,969
69,682,120
Finding a cycle and saving its vertices in an undirected, unweighted graph using BFS
I've been trying to make this program save the vertices that make the cycle in the graph. But I'm kind of a newbie in algorithms and achieving that functionality seems a bit complex when using BFS. The code below successfully finds cycles, but the question is how to modify this code so I can print all the vertices that...
You could use the parent links to reconstruct the cycle. When two BFS paths meet, then these two paths can each be reconstructed by following the parent link in tandem, until a common node is encountered. The lengths of these two paths can either be equal (the cycle is even), or differ by 1 (the cycle is odd). If you d...
69,681,271
69,681,417
Creating a Service in vs2019
I wanted to create a service in VS2019, but it hasn't a template for it. So I created an empty project and then I try to write a service from ground up. I written the following main function. #define SERVICE_NAME _T("My Sample Service") int _tmain(int argc, TCHAR* argv[]) { OutputDebugString(_T("My Sample Service...
The issue is that the structure is defined as follows: typedef struct _SERVICE_TABLE_ENTRYW { LPWSTR lpServiceName; LPSERVICE_MAIN_FUNCTIONW lpServiceProc; } SERVICE_TABLE_ENTRYW, *LPSERVICE_TABLE_ENTRYW; LPWSTR is wchar_t*. String literal L"..." can be assigned to const wchar_t* pointer, but not...
69,681,305
69,681,441
Segmentation fault in memory allocation when making a dynamically resized array C++
I get a segmentation fault when the append(int val) function is run, and called polymorphically, but I can't see where the memalloc error is coming from. I'm still new to C++, and run into this problem a lot, but when I do fix it on my own, it's always by happenchance. Any pointer? (No pun intended, or is it :)) Intege...
For starters the constructor does not initializes the data member _collection IntegerCombination::IntegerCombination() { _length = 0; } So this data member can have an indeterminate value and using the operator delete with such a pointer invokes undefined bejavior. Moreover as you are trying to allocate an array t...
69,681,755
69,688,653
C++ map custom iterator using the wrong type of begin() overload
For a school exercise I'm trying to recode the map STL container using Red-Black Tree method and I'm having an issue with the use of which begin() overload when I call them. For testing purpose I'm trying to show the content of my map with the following function: template <typename T> inline void printMapContainer(T& c...
As @n.1.8e9-where's-my-sharem said: Any iterator should be convertible to a corresponding const_iterator. You may add either a conversion operator to your iterator class, or a conversion constructor to your const_iterator class. what I was missing is a constructor in my const_iterator class that would be able to copy...
69,681,934
69,682,255
Disable copy assigment in CRTP-template
I'm having a CRTP template in which I use an object pool. Object are allocated using the generate() static method. template <class tDerivedSignal, class tBridgeType, class tPayLoadType = void> class SignalT : public SignalSignatureT<tBridgeType> { ... static tDerivedSignal &generate(tPayLoadType &fPayLoad)...
You want to delete the SignalT copy assignment (and most likely copy construction). By default, any class that inherits from this (as in your CRTP pattern) will have its default copy constructor/copy assignement operators also deleted, which will also inhibit the default move construct/move assignment operators. temp...
69,682,233
69,682,299
How to deduce template parameters based on return type?
I am attempting to create a simple input() function in C++ similarly to Python. I expected the code (below) to prompt the user for their age, then to print it into the console. #include <iostream> using namespace std; int main(void) { int age; age = input("How old are you? "); cout << "\nYou are " << age ...
Conversion operators can mimic that. struct input { const string &prompt; input(const string &prompt) : prompt(prompt) {} template <typename T> operator T() const { T _input; cout << prompt; cin >> _input; return _input; } }; Mind however that this may not be applicable ...
69,682,235
69,683,143
How to store sent/received data with libcurl
Im trying to implement some curl and curlcpp functions for a small project. So far i have implemented a few functions but now i want to add functionality. The idea is to store in a buffer the sent and receive data so later i can access: Sent Data Sent Headers Received Data Received Headers I know there is CURLOPT_WRI...
libcurl expects standalone C-style functions for its callbacks. You can't use a non-static class method for a callback. Declare your trace_data() method as static. You can use CURLOPT_DEBUGDATA to pass the this pointer of the CurlCPPClient object to the method's userptr parameter. class CurlCPPClient { private: ...
69,682,251
69,822,888
Using Conan to build multiple libraries and packaging them to be used without Conan
I am very new to Conan and I am quite lost in the documentation at the moment and I cannot really find a way to do what I want. Maybe I am not using the right tool for this, I am very open to suggestions. Let's say my C++ project needs opencv and nlohmann_json to be built. I want to be able to create an archive of all ...
This question has been answered by Conan's co-founder james here: https://github.com/conan-io/conan/issues/9874 Basically: Use the CMakeDeps generator instead of cmake / cmake_find_package Patch the resulting cmake config files at install time inside the generate() method from the main conanfile.py Edit recipes accord...
69,682,392
69,697,727
C++ code duplication in functions with different number of arguments
I'm trying to remove some code duplication from my code. So there are 2 functions with almost the same code Post and Send but they have different number of parameters which puts me on thought that it should be or variadic template or std::function (correct me if I'm wrong). One function call is different though so I'm ...
Solved it #include <iostream> #include <functional> using namespace std; class MyClass { public: void Post( int responseStream ); void Send(); void send_report( int responseStream, std::string str ); void publish_event( std::string str ); // callbacks void process( int ); void update(); ...
69,682,496
69,705,612
GLSL: Fade 2D grid based on distance from camera
I am currently trying to draw a 2D grid on a single quad using only shaders. I am using SFML as the graphics library and sf::View to control the camera. So far I have been able to draw an anti-aliased multi level grid. The first level (blue) outlines a chunk and the second level (grey) outlines the tiles within a chunk...
You need to split your multiplication in the vertex shader to two parts: // have a variable to be interpolated per fragment out vec2 vertex_coordinate; ... { // this will store the coordinates of the vertex // before its projected (i.e. its "world" coordinates) vertex_coordinate = gl_ModelViewMatrix * gl_Vertex; ...
69,682,609
69,683,402
Correctly catching the CDatabase::Close exception
I thought I would do a little digging about cataching exceptions. According to this question (C++ catching all exceptions) one of the answers states: [catch(...)] will catch all C++ exceptions, but it should be considered bad design. At the moment I have used this approach: CPTSDatabase::~CPTSDatabase() { try ...
Since CDatabase::Close() is using THROW_LAST to throw CDBException, you have to use catch (CDBException* e). Even if you are not handling it, you still have to Delete the error. You might as well do this when CDatabase methods are called directly: void CPTSDatabase::CloseDatabase() { try { if (m_dbDatab...
69,682,659
69,682,711
c++: how to add an environmental variable only for the current process?
Basically the question is in the title. I'm using the setenv() fucntion to set the environmental variable in my cpp program, where I also use fork() exec() chain, which create a child process. The problem is that the created variable is also accessible from this child process. This makes setenv() equivalent to export A...
There is no direct way of doing this. Calling exec is always going to make child process inheriting environment variables of the parent process. You can use exceve to explicitly specify environment variables to be visible to child process.
69,682,947
69,683,002
Fill argv (and get argc) with a string to pass to other method
I receive from another method a string (I don’t know the size of this) and I want to fill my argv (and get argc) with this string to pass to other method and I don’t know how to do it. At the start of the string I set the name of my app so I have a final string like: "myapp arg1 arg2 arg3 arg4" The code I have is the f...
Try something like this: #include <vector> #include <string> #include <sstream> int main (int argc, const char* argv[]) { while (true) { // send_string() give a string like: “the_name_of_my_app arg1 arg2 arg3 arg4” std::string data = send_string(); std::istringstream iss(data); ...
69,683,005
69,683,482
Range-v3: Why is ranges::to_vector needed here?
I'm trying to compute a reversed views::partial_sum. The code below gives the expected result of a non-reversed partial_'min', but I need to use ranges::to_vector in order to un-views::reverse the final result (since you can't views::reverse a views::partial_sum). However, when the second to_vector is uncommented, the ...
This is a range-v3 bug that is a result of views::reverse not properly propagating the value_type, and so you end up with a vector<common_pair<unsigned int, float&>> (note the reference) where you should really be ending up with a vector<pair<unsigned int, float>>. This will be fixed by this PR. In the meantime, you ca...
69,683,071
69,683,523
How to pull text out of a .txt and store it into a dynamic 2d array?
I need to pull text line by line out of my .txt file and store it into a dynamic array that has new space allocated every time I pull a new line out of the .txt file. My code seems to pull out the first line just fine and store it into the first pointers array, but on the second loop, it seems to reset all the pointers...
There are multiple bugs in the shown code. while (!myFile.eof()) This is always a bug that also must be fixed, in addition to the main problem with the shown code: temp = new char* [index + 1]; To help you understand the problem with this line, it's helpful to remember The Golden Rule Of Computer Programming: Your c...
69,683,155
69,683,752
Program seems to be skipping second set of inputs and going directly to the end calculations
after the second output statement, the program doesn't take the second set of inputs. Any idea what I could even do to fix this? Is this just a quirk of C++? Any help at all is much appreciated. :) #include <iostream> using namespace std; int main() { int startHours, startMinutes; int endHours, endMinutes; ...
You have to read one more char, because when you read amPmChar from the input - m is still in your stream. And after that - there is an endline, so your endHours tries to initialize with that value. That's your problem. You may read more about it in this answer, it's about cin validation.
69,683,374
69,683,401
How to pass non-static member function pointer to a template function in C++?
I'm trying to make a function template in a header file that accepts a generic function pointer and packed arguments. The function template would invoke the received function pointer using the packed arguments. My goal is to calculate and return the execution time of the function pointer. #ifndef LOGTIME_HPP #define LO...
Non-static member functions have an implicit parameter of the class type as the first parameter of the function, and it is that object which is mapped to the this pointer. That means that you need to pass an object of the class type as the first argument after the member function pointer like << getExecutionTime(&Obj:...
69,683,517
69,683,871
Fast and precise implementation of pow(complex<double>, 2)
I have a code in which I perform many operations of the form double z_sq = pow(abs(std::complex<double> z), 2); to calculate |z|² of a complex number z, where performance and precision are my major concerns. I read that the pow() function of C++ converts int exponents to double and thus introduces numerical errors ap...
I think it would be hard to beat just taking the sum of the squares of the imaginary and real parts. Below I measure it being about 5x faster than actually calculating the magnitude and squaring it: #include <complex> #include <chrono> #include <random> #include <vector> #include <iostream> double square_of_magnitude_...
69,683,569
69,683,581
Writing a program in c++ to output string in reverse, getting no output as a result
#include <iostream> using namespace std; int main() { int i; string userInput; int index; getline(cin, userInput); index = userInput.length(); for(i = index; i <= 0; i--) { cout << userInput.at(i); } return 0; } Program is generating absolutely 0 output. No errors or bugs, I just can't generate any output... An...
You got the loop condition wrong Try i >= 0 (instead of <= ) In addition, you'll want to start the index at index-1 Working example: #include <iostream> using namespace std; int main() { int i; string userInput; int index; getline(cin, userInput); index = userInput.length(); for(i = index-1;...
69,683,597
69,683,891
Why isn't there an implicit defaulted definition for pure virtual destructor?
I know that if the class is supposed to be abstract, but does not contain any used-defined method, there is technique to achieve this by making the destructor pure virtual. class B{ public: virtual ~B() = 0; } As far as I understand the object in example below should not be able to be instantiated. #include <iostr...
If a function is declared pure virtual, then this means two things: The class with such a declaration cannot be instantiated. Any derived classes must provide a definition for the method, or they also cannot be instantiated. However, #2 only happens if you don't provide a definition for that pure virtual function d...
69,683,869
69,694,512
How to implement the Fortran spacing() function in C++?
The code I'm converting from Fortran to C++ contains the spacing(x) function. From the description, spacing(x) returns the Smallest distance between two numbers of a given type and Determines the distance between the argument X and the nearest adjacent number of the same type. Is there a C++ equivalent function or,...
Using SPACING as Determines the distance between the argument X and the nearest adjacent number of the same type, use nexttoward(). upper = nexttoward(x, INFINITY) - x; lower = x - nexttoward(x, -INFINITY); spacing = fmin(upper, lower); upper != lower in select cases: e.g. x is a power-of-2. May need some work to h...
69,684,527
69,698,617
how to automatically generate a unique c++ class based on a file
let me preface this question by saying I have no idea if I'm asking the right question. I'm pretty new to c++ and I haven't gotten all of its nuances down yet, but I have coded in other OOP languages for nearly 7 years. I originally asked: Is there a way to take a text file and automatically generate c++ code? If yes, ...
It seems like all you want is separate compilation. Firstly, you make an interface for the part of your game you wish to make more decoupled: // Player.hpp #include <memory> struct IPlayer { virtual void run() = 0; virtual ~IPlayer() = default; }; std::unique_ptr<IPlayer> getPlayer(); Then use it in your progra...
69,684,742
69,684,800
If I am learning C++, is it a problem to learn C++11/14 when C++20 is the most modern version?
I am a fairly new programmer, with only a little bit of python experience. I learned python because I wanted to see if I would enjoy programming, and now I love it. I want to learn C++, and according to The Definitive C++ Book Guide and List a really great book is Programming: Principles and Practice Using C++, a book ...
I don't think learning C++14 will hurt you at all. It's still very "modern" in the grand scheme of C++ history. The newer C++ versions tend to build on previous versions with more advanced features, but if you're just getting started with C++, the basics will be the same going back to at least the 90's. If anything,...
69,684,808
69,685,023
Cannot terminate cstring properly
I'm making a program that finds the most frequently inputted character and outputs it but a junk character takes over the output if it's less than the array value. I've tried putting null in multiple places. Putting it at the end, putting it at the beginning. It keeps giving me the junk character ╠ for some reason. #in...
Multiple problems with your code. Before discussing the problems, a suggestion - Read about std::string in C++ and going forward start using it instead of plain C style character array. I am leaving it up to you to use std::string in your program. Below answer is pointing out the problem in your existing code. Lets dis...
69,684,923
69,684,932
If I have heap allocated member in my struct, do I have to allocate the struct itself in the heap?
struct Vector { size_t size; char ** data; } Vector; I have a vector struct. Do I have to allocate the Vector on heap if the struct has dynamically allocated data? Update: Does that applies the same in c++ class?
No, there is no such rule. A pointer residing in any part of memory may point to any other part of memory. That said, if your struct Vector is allocated in a different way than its data, then the two might end up with different lifetimes, and it might be harder to avoid use-after-free bugs or memory leaks. So if data...
69,685,415
69,685,439
Error passing a function in as a parameter C++
I have a working implementation of testing the time of a function for search methods, which take: checkSearchTime(T(*funcPointer) (T myArray[], int size, T wanted) as parameters, I try to do the same thing with sort methods: checkSortTime(T(*funcPointer) (T myArray[],int size) and I get an error. This is the error: E...
It was because sort methods don't return anything.
69,685,438
69,697,561
Qml c++ diffrent delegates qt mvc
How I can use different delegates in qml for the ListView. For example I have QList<SomeObject*> list, SomeObject has two fields: type (circle, rectangle, etc), and someValue. I created QListModel for this list. I have different qml elements (circle.qml, rectangle.qml, etc). How can I view delegate for an item by type,...
You can try a concept of qml Loader that may match your requirements. Basically, you cannot define multiple delegates for a single view. So setting your Top Delegate as the loader and loading the items based on the type will help you with this case. Positioning is also possible you can have x & y pos defined with your...
69,685,745
69,685,765
std::array guarantee zero-initialization?
I'm wondering that std::array initialize all fields to zero struct Foo { int a; int b; std::uint32_t c : 16; std::uint32_t d : 16; }; class Bar { public: std::array<Foo, 2> foo; } foo's all fields are initialized with zero?
std::array is an aggregate class. When you default initialise an aggregate, the members of the aggregate are also default initialised. Default initialising an integer does not zero initialise it. If you value initialise the aggregate, then the members of the aggregate are also value initialised. Value initialisation of...
69,685,842
69,685,909
Why is my merge sort slower than this merge sort?
I've implemented merge sort in C/C++. But my code takes longer time than the code I pulled from a website. The recursive code seems to be exactly same for both cases: void mergeSort(int* arr, int l, int h) { if (l < h) { int mid = (l + h) / 2; mergeSort(arr,l,mid); mergeSort(arr, mid + 1, h)...
Your algorithm need to allocate [h+1] for each step. The algorithm from a website only need to allocate [r-p+1] (your h = its r, your l = its p)
69,685,871
70,798,672
How to do serialization in Miracl library?
Is there a way to do serialization in C++ Miracl library ? Typically, in Crypto world we would do encryption routine and decryption(like AES,RSA) routine in two differenti program, I want the same structure in these pairing based Encryption like the Attributed-based Encryption and Broadcast Encryption , i.e implement E...
There is a build functions spill and restore inside G1, G2 and GT classes. you can use them to spill G1 into a char* and restore G1 back using char*. For example:- pfc.precomp_for_mult(Q); // precomputation based on fixed point Q char *bytes; int len=Q.spill(bytes); // allocates byte array of length le...