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
62,348,400
62,348,709
Overload std::string operator+ for printing enum name
I have an enum enum ft_dev_type { SPI_I2C, GPIO }; I would like to be able to construct a string like this std::string s = "enum =" + SPI_I2C; //would contain "enum = SPI_I2C" To do so, I'm trying to overload the + operator std::string operator+(const ft_dev_type type) const { ...
It seems you want the free function: std::string operator+(const char* s, const ft_dev_type type) { switch (type) { case SPI_I2C: return s + std::string("SPI_I2C"); case GPIO: return s + std::string("GPIO"); } throw std::runtime_error("Invalid enum value"); } (and similar for std::strin...
62,348,550
62,348,771
Are iterators guaranteed to mutate when incrementing and decrementing them?
I'm trying to store a few std::string:iterators in a vector, and iterate over them like so: while (something) { for (auto& it : iterators) { do_things(*it++); } } This seems to work - the iterators in the iterators vector mutate their position when incremented. I do not reassign them in the vector, the...
Are iterators specified to be stateful? They are not "specified" as such, at least not explicitly. Iterators are specified in terms of what operations they support, and what behaviour those operations have. Containing state is implicit in the abstract concept of what an iterator does, and it is very typical for itera...
62,348,574
62,365,382
Trouble building GLEW on Windows using MinGW
I'm trying to build GLEW 2.1.0 on Windows (8.1) using MinGW and have been struggling for a while now. I tried to follow the instructions for "MSYS/Mingw" on the GLEW GitHub page but when running mingw32-make, I only got a couple errors about missing commands (test and config) as well as the following: Makefile:40: *** ...
I could never build it with the instructions I found around the internet, so here's how I build glew (using https://downloads.sourceforge.net/project/glew/glew/2.2.0/glew-2.2.0.tgz) under MSYS2 with MinGW-w64: # change the line below to your desired install path INSTALLPREFIX=/usr/local VERSION=2.2.0 gcc -O2 -Wall -W -...
62,349,018
62,349,097
decltype: Access static member of class using a pointer
I have a templated function f. I am passing it either a reference or a pointer to an object. That object is of struct S. I would like to know the size of S::my_tuple, which is a static member of that struct. I can do that when I pass the object by reference with std::tuple_size<decltype(T::my_tuple)>::value. How can I...
Just remove pointer with a type trait: decltype(std::remove_pointer_t<std::decay_t<T>>::my_tuple) In const T object, T is never a reference. std::decay_t<T> is needed if you use, for example, a universal reference (T&& object) instead. Also note that all branches of your code should compile when you use if. If you wan...
62,349,138
62,349,249
Performance difference for loops in C++
Consider the following C++ class and struct in typedef struct MatrixDims { int rows, cols; } MatrixDims; class Matrix { private: float *_matrixElements; MatrixDims _matrixDims; public: Matrix(int rows, int cols); ~Matrix(); void printMatrix() const; } Notes: I am using an array instead of a ...
First of all in C and C++ there is "AS IF" rule. Here is some SO answer about that. This means that if you enable compiler optimizations there should be no significant differences. In fact for such simple modification I wouldn't be surprised if final machine code is exactly same. So keep your code readable. I did compa...
62,349,586
62,386,850
Monitor task CPU utilization in VxWorks while program is running
I'm running a VxWorks 6.9 OS embedded system and I need to see when I'm starving low priority tasks. Ideally I'd like to have CPU utilization by task so I know what is eating up all my CPU time. I know this is a built in feature in many operating systems but have been so far unable to find it for VxWorks 6.9. If I ca...
If you are looking for a one time measurement done during the developement, then spyLib is what you are looking for. Simply call spy from the command line to get per task CPU usage report in 10s intervals. Call spyHelp to learn how to configure the spy. (Might need to inculude the spyLib to kernel if not already includ...
62,349,861
62,385,640
LRU with shared_ptr in multi-threaded environment
I run into a corner case while using a shared_ptr based "database" that doubles as an LRU. Since C++17, the shared_ptr::use_count is imprecise, so I have trouble deciding on which elements can be safely removed from the LRU. I cannot remove still-in-use elements, as that would break contracts in the rest of the code. A...
General solution I'd propose is while under a lock, identify a candidate element to remove. Then attempt to remove it by doing this: Create a weak_ptr instance to an element you think might be a good candidate to remove Delete the item from the list as you normally would Try to restore the item as a shared_ptr from...
62,350,244
62,362,022
Fill a std::vector from a row of an Eigen Array / Matrix
I have an Eigen Array2Xd and I want to put each of its rows into std::vector<double>. The spline_knots is an Array2Xd of size (2, 4) with following values: Array2Xd spline_knots(2, 4); spline_knots << -1, 0, 30.57, 60.83, 0, 0, 9.73, 15.44; I tried the following based on this answer: vector<double>...
Figured it out. The problem is related to storage order, the way how Eigen lays out a two dimensional array in memory. There are two possible layouts: RowMajor and ColumnMajor. The default layout is ColumnMajor, which stores the 2D array elements column-wise. Knowing this, the weird result I get makes sense. The .row(...
62,350,268
62,352,854
ofstream not printing despite being open
I am trying to print data to a file; however, the file that is created is empty, and nothing seems to be printed to it. I know that the file stream is open and good because my cout statements are printing what i am expecting, but for some reason, the write-file is blank when I check. Any solutions would be appreciate...
Move std::flush to the end of the output. For example like this: fileStream << printString << std::flush;
62,350,287
62,350,423
Call protected function in main class
#include <iostream> using namespace std; class account { private: int accountNumber; string accountName; enter code here`protected: void setAccountNumber(int aNum); void setAccountName(string aName); public: account(int accNum, string accName); account(); }; ...
No you can't. The protected accessor on a method means that only the following can access it: the class itself class that inherits from it another class with friendship https://en.cppreference.com/w/cpp/language/access#Protected_member_access
62,350,331
62,350,764
C++ Setters not assigning values to derivative classes
My setters are not setting. I've worked this problem on an off for about a week and a half now. It's like everything falls into place, code compiles and seems like everything is working hunky-dory, but my setters are not setting, even after correctly instantiating two different objects from the derivatives: #include <i...
Getter Setter were working. You were not calling getter in main. Hope it will help you! #include <iostream> #include <conio.h> // _getch() #include <string> #include <ctype.h> using namespace std; #define VMSG_LEN_PRICE 0.03 // Price of Voice Message #define TMSG_LEN_PRICE 0.02 // Price of Text Message // Base Class...
62,350,368
62,350,418
Array of objects inside another class with a constructor
If we have a class with a constructor to be initialized in another class's constructor we do the following, Class A{ A(int arg):a(arg); int a; }; Class B{ B(int arg):A_obj(arg); A A_obj; } I have encountered a situation like the following, Class B{ B(int arg1,int arg2); A *A_obj//Array of objects of A of size ar...
I would suggest changing your raw array to a std::vector class B{ B(int arg1,int arg2); std::vector<A> A_obj; }; Then you can use the member initialization list B::B(int arg1, int arg2) : A_obj(arg2) {} This will size your vector with arg2 number of default-initialized A objects. If you want each A to be initialize...
62,350,381
62,351,289
ensure class member variables are not modified when cloning
I am trying to add a clone func for class A. This class has a non const and not owned pointer b_. I want to make sure that b_ wont be modified in the cloned objects, but it is ok to modify other member variables, and these non-const func in A can still be called. A bad way is adding a flag and check it every time befor...
You could perhaps design a class hierarchy like this: class cloned_A; class A { public: cloned_A *clone (); private: B* b_; }; class cloned_A : public A { public: cloned_A (const B *b) : read_only_b (b) {} private: const B* read_only_b; }; cloned_A *A::clone () { return new cloned_A (b_); } ...
62,351,083
62,351,101
c++ how does compiler get the length of argv strings
In C/C++, argc is the count of command line arguments and argv is char** or pointer to pointer of characters. I get that argc can be used to get number of arguments, but how does the compiler know the length of the first argument or the second?
Like all C strings, the strings that argv points to are 0-terminated. The compiler doesn't know. (It can't. By the time the program is called with some actual arguments, the compiler is long done.) But the program can find out using strlen.
62,351,110
62,354,660
Undefined class template is not instantiated to check for friend functions
The following program compiles (see on godbolt), but it would not compile if we uncommented the definition of Buffer. template <int size> struct Buffer /*{ char buf[size]; }*/; template <class T> struct Wrapper { void operator+() {} }; Wrapper<Buffer<-5>> a; void f() { +a; } The reason, the uncommented version does...
You can (implicitly) instantiate a class template from only a declaration; you get an incomplete class type, just like from struct A; ([temp.inst]/2). It’s not an error, of course, to do ADL with an incomplete associated class; the class in question is simply not searched for friend declarations.
62,351,236
62,351,363
Can The Free Storage Consume More Memory Left Over?
int memory() { int* p = new int[10000]; } will this make 10000 ints unusable for things like local memory? I don't know if it does.
The new is used to allocate the requested amount of memory(if available) to the object/array variable that you requested. In your case, the pointer p will store the address to this allocated block of memory. There's only a finite amount of memory that's available to you and so your program can only use from that amoun...
62,351,258
62,448,204
Debug C++ code from Dart package using dart::ffi
I am developing a package in C++ to be used in a Flutter app (and therefore in Dart), using dart::ffi and I was wondering if there was a better way to debug (step by step, variable watch, that sort of things) the C++ code, other than logging messages. I've tried both in Android Studio and VS Code, with no success.
Android Studio (or VS Code) doesn't support native (C/C++) code debugging while in Flutter mode (yet). However, there is a workaround! In the project tree, right-click the 'android' folder and select Flutter -> Open Android module in Android Studio. The project will switch to Android development mode where c/c++ debugg...
62,353,013
62,353,283
Exit code 139 when using const char*
so I am writing a program that counts the number of occurrences of the character x in a const char* called p. but I get Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) when running the program. At first I ran this code in Visual Studio and it didn't work so I thought it might be a Windows issue ...
the string "Hello" actually is stored like this H e l l o \0 that last char is called the zero terminator So the while loop needs to look at the char s is pointing at and to stop if the character is logically false - ie equal to 0. while(*s) { if(*s == x) ++count; ++s; } or more explicitly but less id...
62,353,058
62,353,245
How to sort std::list of pairs by key?
I would like to sort a std::list<std::pair<string, int>> by the key as well as by the value in two separate functions. I am getting an error that says: error: reference to non-static member function must be called sort(test.begin(), test.end(), sortByVal); The code class Test { std::list<pair<std::string, in...
The std::sort required to have the iterator passed to be Legacy Random AccessIterator. But the std::list has Legacy Bidirectional Iterator, which is why the error. On the other hand, the std::list has a member function std::list<T>::sort, which would be prefered way to go, if you insist the container must be std::list...
62,353,151
62,353,348
Adding even / odd elements in *argv[] to arrays
I'm fairly new to C++ and I'm making a simple program which takes values and units as system arguments and converts them all to a single unit. The command line execution and input goes something like this: ./unit_conv 3 feet 5 inches centimeters The values and units are separated by spaces, and the final argument is t...
Have you tried using STL? std::vector<std::string> units{}; std::vector<int> values{}; for (std::size_t i {1}; i < argc; ++i) { if (i % 2 == 0) { units.push_back(std::string{argv[i]}); } else { values.push_back(std::atoi(argv[i])); } }
62,353,259
62,353,448
error: cannot convert ‘<lambda(double)>’ to ‘double (*)(double)’
I have this error error: cannot convert ‘<lambda(double)>’ to ‘double (*)(double)’ From the code void Matrice::mapEmplace(double (*fct)(double)) { for (size_t i = 1; i <= nLig; ++i) for (size_t j = 1; j <= nCol; ++j) (*this)(i, j) = (*fct)((*this)(i, j)); } -- void function() { // ... bool ale...
You can only convert the capture-less lambda to a c-style function pointer. In your case, your lambda capture the alea by copy, and hence the conversion to function pointer type is not possible. You have two options: Either use the std::function with some type-eraser overhead. Or make the function as a templated one, ...
62,353,625
62,354,202
C++ candidate function not viable?
Why the following code doesn't compile: B b1(1), b2(2), b3(3); const B b4 = b1 + (b2 + b3); Until I replace this: B operator+(B& b) { return B(n + b.n); } with this:(I don't know why to write const the compiler suggested that) B operator+(const B& b) { return B(n + b.n); } Errors I get: invalid operands to ...
const B b4 = b1 + (b2 + b3); According to the order of operations, the first subexpression to evaluate is b2 + b3. This invokes B::operator+, which returns a B object. More precisely, a temporary B object is returned, one that will be used to help evaluate this full expressions and then discarded. This is much like ...
62,353,629
62,358,277
Does the same floating-point calculation producing different results when performed twice indicate IEEE 754 non-conformance?
In a specific online judge running 32-bit GCC 7.3.0, this: #include <iostream> volatile float three = 3.0f, seven = 7.0f; int main() { float x = three / seven; std::cout << x << '\n'; float y = three / seven; std::cout << (x == y) << '\n'; } Outputs 0.428571 0 To me this seems like it violates IEEE ...
Does this necessarily indicate that the online judge system doesn't conform to IEEE 754? Yes, with minor caveats. One, C++ cannot just “conform” to IEEE 754. There has to be some specification of how things in C++ bind (connect) to IEEE 754, such as statements that the float format is IEEE-754 binary32, that x / y us...
62,353,762
62,353,863
Non-lvalue in assignment in class
I'm kinda of new at c++, so I need some help. I have to make a function tha books ticket for an event. void Event::book(int row, int seat, Date date, char *name, char *note) { if(this->date==date && strcmp(this->name,name)==0) { if(hall.seatsInHall[row-1][seat-1].isFree()==true) { ...
The problem arises because the stuff on the left side of the assignment statements are not lvalues i.e. you cannot assign values to them. The most likely cause is that getNote() and isFree() are returning-by-value. A function can return an lvalue if (and only if) it returns a reference. You need to make sure that isFre...
62,354,314
62,354,331
accessing values from unordered_map in c++
I have an unordered_map: unordered_map<string, list<string>> adj_list; how do I see if the list of strings list<string> contains a value? I tried: if(adj_list.find("find")) printf("value found"); but it gives me a conversion error. How do I access the first string and the second list of strings in this unordered_map? ...
If you know the key you can do this: auto l = adj_list.find("here"); // here we get the correct list if(l != adj_list.end()) { if(std::find(l->second.begin(), l->second.end(),"find") != l->second.end()) { printf("Found"); } } You can do this if you don't know what the key to the correct list<string...
62,354,960
62,356,820
Can `co_yield` return a value from the caller on resumption of the coroutine?
C++20 introduces coroutines, which can be used to create generators and other similar things: generator<int> counter(int max) { for(int i = 0; i < max; i++) { co_yield i; } } Is there any way to create a coroutine such that the caller can provide a response that is returned by co_yield once the corouti...
The key is await_resume, which is called on the awaiter (result of yield_value) to obtain the result of co_yield. You also need to store the response somewhere. As Raymond Chen suggested in comment, you can put the value in a new data member of promise_type. So changes are: Add a data member to promise_type. In respon...
62,355,259
62,355,889
Going around in circles with Pure Virtual Functions
I am using a simple inheritance structure to try and simplify code structure and reduce common code usage across a number of classes. The idea is to allow a simple linked list structure within the class to allow the entire set of instances to be iterated. EDIT: To elaborate, this is intended to support a bunch of class...
The code you posted does have a problem, but I think it's different from the ones you mentioned. The problem I see is that you call register_instance from the cGroup constructor, and then call virtual functions, eg. getFirstInstance() from that. Virtual calls don't work as expected at construction time (because the vt...
62,355,294
62,355,307
C2011: 'Card': 'class' type redefinition (despite using include guards and not redefining class in .cpp file)
Note: I've been reading some articles on this error, but the main problem seems to fall under either one of these: 1.They didn't use include guards (specifically #ifndef) 2.They redefined the class in the .h file, as well as in the .cpp file But I didn't have either of those issues, so I don't think this is a duplicate...
I don't think your guard is correct. Try this: #ifndef CARD_HEADER #define CARD_HEADER class Card { //Code here } #endif Remember, the whole point is to EXCLUDE your code if the header has already been used at least once (if #ifdef CARD_HEADER is true). Look here for more details: https://en.wikipedia.org/wiki/I...
62,355,372
62,355,415
Cannot access private member from within class in C++?
SO I am trying to teach myself data structures in C++. To do so, I made an ArrayList class with a member variable arrayData with type int* and a get method to access values from that pointer. I come from a Java background and C++ OOP is sorta strange, especially with the separation of header and source files. At compil...
This line: int* ArrayList::arrayData; In the source file makes no sense. Compiler thinks you're referencing a static variable of ArrayList (because you've prepended with the class name). Remove this line. You will be able to access arrayData from the other methods. Also, use std::unique_ptr<int> instead of the raw poi...
62,355,395
62,355,603
What does it mean by "#define X X"?
In Linux header file epoll.h, I found the following code: enum EPOLL_EVENTS { EPOLLIN = 0x001, #define EPOLLIN EPOLLIN ... } What does it mean by #define EPOLLIN EPOLLIN?
This create a macro named EPOLLIN whose replacement text is also EPOLLIN. This is most likely a way for the preprocessor to check which event codes are available and conditionally compile code as necessary. If we go to the git repo for glibc and look at the output of git blame we see the following for enum EPOLL_EVENT...
62,355,458
62,355,558
C++ output shown without returning the values
compiler used-: code blocks without returning the "c" how is variable "d" getting its value? #include<iostream> using namespace std; int add(int x,int y) { int c; c=x+y; } int main() { int a,b; cin>>a>>b; int d=add(a,b); cout<<d; }
Write this code: #include<iostream> using namespace std; int add(int x,int y) { return x+y;//CHANGE THIS } int main() { int a,b; cin>>a>>b; int d=add(a,b); cout<<d; }
62,355,613
62,355,649
std::variant cout in C++
I am relatively new to CPP and have recently stumbled upon std::variant for C++17. However, I am unable to use the << operator on such type of data. Considering #include <iostream> #include <variant> #include <string> using namespace std; int main() { variant<int, string> a = "Hello"; cout<<a; } I am unable ...
use std::get #include <iostream> #include <variant> #include <string> using namespace std; int main() { variant<int, string> a = "Hello"; cout << std::get<string>(a); } If you want to get automatically, it can't be done without knowing its type. Maybe you can try this. string s = "Hello"; variant<int, string...
62,355,944
62,356,260
How to detect when a process is terminated in Linux using C++?
The purpose is I want my program running on Linux to be terminated when some random process is terminated. I can get PID or process handle of the process that my program is to monitor. Are there any possible approaches that I could take?
Linux 5.3 introduced pidfd_open, which lets you get a file descriptor from a PID. The FD will become readable when the process dies, which you can detect with select/poll/epoll, like this: #include <iostream> #include <sys/types.h> #include <sys/select.h> #include <sys/syscall.h> #include <unistd.h> int main(void) { ...
62,356,033
62,356,302
Create a text file using TFileStream
I tried code from the following documentation: Reading a String and Writing It To a File But it doesn't work and reports a compiler error: No member named 'fmCreate' in 'System::AnsiStringT<0>' Here is the code I tried: TFileStream *fs; const AnsiString str = "Hello"; fs = new TFileStream("temp.txt", fmCreate); fs->W...
Well it just looks like a typo. Clearly the code is trying to write the string to the file, so the length of the string is needed. Try this TFileStream *fs; const AnsiString str = "Hello"; fs = new TFileStream("temp.txt", fmCreate); fs->Write ((void*)str.c_str(), str.Length()); Caveat, I know nothing about VCL.
62,356,139
62,356,192
Why is movement constructor invoked twice while std::emplace_back is called only once?
I understand that std::emplace_back uses placement-new to construct the element in-place at the location provided by the container. Why is movement constructor invoked twice while std::emplace_back is called only once? Here is the related code(check https://godbolt.org/z/-NXzNY): #include <vector> #include <string> #i...
You have two objects; Putting the second to the vector causes a vector resize, memory reallocation, hence the movement requirement. In addition to construction-in-place that emplace_back does, that's another point of the move construction: To avoid expensive copies when std::vector resizes. When adding this line to you...
62,356,815
62,356,923
LeetCode 380: Insert Delete GetRandom O(1)
I came across this leetcode problem Insert Delete GetRandom where it is asked to implement a Data Structure to support Insert, Delete and getRandom in average O(1) time, and solved it as using map and a vector. My solution passes all the test cases except for the last one and I'm not able to figure out why? The last te...
This is because of undefined behavior when the element removed is the last element. e.g, say the operations are insert(1) // v = [1], mp = [1->0] insert(2) // v = [1,2], mp = [1->0, 2->1] remove(2): int idx = mp[val]; // val = 2, idx = 1 mp.erase(val); // mp = [1->0] swap(v[idx], v[v.size()-1]); // idx = v.size()-1 = ...
62,357,049
62,357,109
Why is stack smashing detected if an empty array[] is initiated in the constructor < 2 inside a class
I am running into this error... ...with this minimal executable code to reproduce the error and ... #include <iostream> class arrayClass { private: int _elements; int _array[]; public: arrayClass() : _elements(32) { //If i is smaller than 2 the "Stack Smashing Detected" error shows up, ...
Because you never allocate memory for the array to begin with, everything is undefined behavior. I don't even know what int _array[] evaluates to without a size specifier. I'll look that up later. Change your construct code to "new" the array. And have a destructor to delete it. class arrayClass { private: int _el...
62,357,107
62,357,155
g++ gives warning for deleting an array for one code but not the other
I come from a Java background and am still confused as to how pointers and stuff work. I have 2 examples. int arr[10] = {}; delete[] arr; Here, my compiler throws a warning about deleting arr. int *arr = new int[4]; delete[] arr; But it doesn't throw a warning here? Why is that?
In your first code, arr is statically allocated (on the stack), and will be automatically freed when going out of scope. Calling delete[] on statically allocated variables is pointless. In your second code, arr is dynamically allocated on the heap, and will not automatically be freed when going out of scope, hence the ...
62,357,610
62,357,670
C++ reverse 'for' loop
I have a vector: std::vector<int> vec = {1, 2, 3}; And I want to make a reverse for loop. It works, when I write: for(int i = vec.size() - 1; i >= 0; --i) { std::cout << i << std::endl; // 2, 1, 0 } But I get a very large number (like 18446744073709223794) if I write: for(size_t i = vec.size() - 1; i >= 0; --i) {...
Let the compiler tell you what's wrong! If you compiled your program with warnings enabled, the compiler would tell you something like this: <source>: In function 'int main()': 7:43: warning: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits] 7 | for(std::size_t i = vec.size() - 1; i >=...
62,357,675
62,357,731
C++ finding uint8_t in vector<uint8_t>
I have the following simple code. I declare a vector and initialize it with one value 21 in this case. And then i am trying to find that value in the vector using find. I can see that the element "21" in this case is in the vector since i print it in the for loop. However why the iterator of find does not resolve to tr...
are you sure it doesn't work? I just tried it: #include<iostream> // std::cout #include<vector> #include <algorithm> using namespace std; int main() { vector<uint8_t> v = { 21 }; uint8_t valueToSearch = 21; for (vector<uint8_t>::const_iterator i = v.begin(); i != v.end(); ++i){ cout << unsigne...
62,357,713
62,357,939
Is there any better way to sort three integers in C++?
In the programming textbook I'm using (Programming: Principles and Practice using C++ by Bjarne Stroustrup), I'm trying to do one of the exercises found in the very early chapters (before the introduction of arrays or anything), but I can only solve it using an algorithm that looks quite weird and "backwards" to me. Th...
Depends on what you mean by "better". There is a shorter way to do that, just like most other things in C++: #include <iostream> #include <iterator> #include <algorithm> #include <cstdio> int main() { std::istream_iterator<int> it{std::cin}; int a[]{ *it++, *it++, *it++ }; std::sort(std::begin(a), std::end...
62,357,952
62,358,262
All possible sum from a given of coins
You have n coins with certain values. Your task is to find all the money sums you can create using these coins. Input The first input line has an integer n: the number of coins. The next line has n integers x1,x2,…,xn: the values of the coins. Output First print an integer k: the number of distinct money sums. After th...
your code is simply too slow 2^n subsets gives ‭1,267,650,600,228,229,401,496,703,205,376‬ subsets in the worst case (when n=100) while C++ does on average about 1000,000,000 operations per second. This problem can be solved with dynamic programming, consider having an array dp of size 100001, so that dp[x] denotes if ...
62,358,009
62,367,348
OpenCV C++ read image and patch NaN Error: Assertion failed (_a.depth() == CV_32F) in patchNaNs
I have the following code which read an RGB JPEG image, however, the image sometimes has NaN value so I want to patch it with 0: cv::Mat model = cv::imread(path); cv::patchNaNs(model, 0.0); I keep getting the following error message: OpenCV(3.4.5) Error: Assertion failed (_a.depth() == CV_32F) in patchNaNs, file .......
The function requires that the input be 32-bit floating-point. You can use cv::convertTo to convert your image to 32-bit: cv::Mat model = cv::imread(path); cv::Mat output; model.convertTo(output, CV_32F); cv::patchNaNs(model, 0.0); Depending on your use case, you may want to normalise the input values so that they ar...
62,358,124
62,360,059
Specifying the DEF file when compiling a DLL with Clang
I am trying to compile a DLL using clang in windows clang -shared structs.c -o structs.dll but the symbols aren't being exported.. If I add __declspec(dllexport) to my declarations in structs.h, They symbols are exported to DLL. But instead, I would like to do this using a DEF file (structs.def) I created, But I can't...
Finally figured it out - We can use the -Wl flag in clang to pass some comma-separated arguments to the linker. DEF files can be specified using /DEF argument Example clang -shared structs.c -o structs.dll -Wl"/DEF:structs.def"
62,358,169
62,358,324
Using recursion in bubble sort
Hello everyone I am starting to learn Data structures and Algorithms and implemented bubble sort myself after learning the concept. Following is the code I have written with my understanding but the problem is it runs for only one cycle and does not sort recursively. For example: { 5,1,4,2,8} is sorted one time -> ...
Your function takes a vector<int> vector by copy, hence after first swaps only this copy is send to recursively sort. Just add & to your function parameter: vector<int> bubble_sort(vector<int> &vec) and it should work
62,358,207
62,358,349
compiler not recognizing methods defined outside the class declaration
new to c++.Im stuck with a question here, i made a bank account program which has functions like withdraw() and deposit() defined in a class called 'account'.So, i defined my class in a different file(account.h) also i defined withdraw() inside the class itself but defined the deposit() function outside the class in 'a...
While compiling more than source file (.cpp) you should compile with that files. g++ main.cpp account.cpp -o main then run it like: ./main If you try with that command you can run successfully
62,358,347
62,358,708
Casting children classes dynamically
I have the following classes: class Base{ public: virtual int do_Something(); }; class ChildA : public Base { public: int do_Something(); // ChildA does something }; class ChildB : public Base { public: int do_Something(); // ChildB does something }; In my main.cpp I want to create an object ChildA...
The problem here is classe (Base *) is not polymorphic. It's a simple pointer. You can see it in the output. On Linux with GCC it's: P4Base, pointer to Base What you want is typeid(*classe).name(). The output is 6ChildB, object of type ChildB. Polymorphism won't change the type of the pointer (neither static type nor d...
62,358,519
62,372,024
Last digit of partial sum of Fibonacci series
I'm trying to find the last digit of the sum of the fibonacci series from a starting to an end point. As we find the last digit using %10 , Fibonnaci will repeat it's last digit sequence every 60 times - using the Pisano Series My attempt at the solution: We find the last digits of the first 60 digits, store them in an...
#include <vector> using std::vector; int fibonacci_fast(long long n,long long m) { // write your code here long long a[60]; a[0]=0; a[1]=1; long long sum=0; sum = a[0] + a[1]; for(long long i=2;i<60;i++) { a[i] = a[i-1]+a[i-2]; a[i] = a[i] % 10; sum = (sum + a[i]...
62,358,534
62,360,839
what will be the output of the following code related to pointers?
for the following code, what should be displayed on the screen? int num = 125; int *numPtr ; numPtr = &num; cout << numPtr << ’\t ’ << *numPtr; the options: A. memory address of variable numPtr, followed by a tab, followed by 125 B. memory address of variable num, followed by a tab, followed by 125 C. value of num in...
Think about it for a minute: you create an int called num with the value 125 int num = 125; You then creates a pointer numPtr ( remember pointers are only a memory address ) that has to point to an int. int *numPtr; You then take the memory address of num ( that is what the address-of operator (&) means, "take the memo...
62,358,790
62,359,285
Call template function for each argument of variardic template
I am trying to make simple DI with specialized template function, like this: #include <iostream> template<typename T> T inject(); template<> int inject() { std::cout << "injected int" << std::endl; return 123; } class Test { public: Test(int arg) { std::cout << arg << std::endl; } }; template...
#include <type_traits> #include <utility> #include <cstddef> struct injected { operator int() const { return 123; } operator double() const { return 3.14; } operator const char*() const { return "foo"; } }; template <std::size_t, typename T> using repeat = T; template <typename C> C* instantiate(std::ind...
62,359,169
62,359,301
C++ generic class, why do I need .cpp file?
I'm looking to write a generic class (like this: template <Class T>) in C++11 but I was told that the implementation could only be written in the .h file. on the other side I am supposed to submit some .cpp file. May someone explain the contradiction? If all definitions and implementations need to be in the .h file why...
You actually don't need a .cpp file at all and there are plenty of header-only library examples. However, it can be beneficial to provide .cpp files for some template instantiations since this give the opportunity to ship a binary another project can link against. This can save compile-time. An example: Your header Foo...
62,359,172
62,485,784
Is this use of static_assert inside if constexpr well-formed?
I read a couple of answers yesterday, on the use of static_assert(false, "Some message") inside the else clause of an if constexpr. I understand that it's considered to be ill-formed, according to the standard (even if some compilers, including MSVC2017, will accept it). Qt will also mark this as an error. My question ...
Both of your attempts (with the function and with the struct) are well-formed as is. The other answer mentions [temp.res]/8, but I disagree with how it was interpreted. The validity of a template may be checked prior to any instantiation. ... The program is ill-formed, no diagnostic required, if: — no valid specializa...
62,359,221
62,359,395
Finding the smallest of 3 numbers. (School assignment)
I am fairly new in programming and I am not quite sure how to do this assignment given to me for school. Write a function void print_min(unsigned char a, short b,int c),which prints "Min of (a,b,c)=M". M is the smallest of these 3 numbers. For computing and printing use functions int min(unsigned char a, short b,int ...
There are multiple issues with your program issue 1: print_min is returning void whereas you probably want it to return an int. int print_min(unsigned char a, short b, int c) { int m = 0; if( a < b ) m = a; else m = b; if( c < m ) m = c; return m; } issue 2 M = print_m...
62,359,347
62,370,128
Boost with Qt Creator
I was trying to use boost/filesystem in my C++ project made with QtCreator. The problem was that when building, I got the following error: "error: undefined reference to `boost::system::generic_category()'" To use boost, I had performed the following actions: download boost library boost_1_73_0.7z file unzip it in my...
As @drescherjm commented, you need to build the boost libraries. They are not in the D:/Development/Boost/libs directory. You appear to be using Windows and have boost installed on your "D:" drive. I assume your using the MinGw compiler that comes with Qt Creator, not Visual Studio. To build boost with MinGw, first ope...
62,359,358
62,359,457
Visual Studio 2017 - Debug and Relese configurations, setting runtime library
I use Visual Studio 2017. I have noticed that runtime libraries for Debug and Release configurations can bet set arbitrary. For example I can set MDd for Debug configuration and MT for Release configuration. Does it make any sense ? Please correct me if I'm wrong but only the following combinations are correct (Debug/R...
Generally, "debug" and "release" are just presets for specific compiler and linker settings. You can set any option to any configuration, no matter if it makes sense or not. The MT options are incompatible, a library compiled with the debug version won't link correctly with a release project. The same issue occurs wi...
62,359,366
62,437,339
LeetCode 15: 3Sum using hash maps
I have written code in cpp but its not giving correct output. class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> v; if(nums.size()==0) { return v; } for(int i=0;i<nums.size()-1;i++) { set<int> s; ...
I guess this would be an efficient solution O(N ^ 2) for the problem, which passes LeetCode's "Online Judge": class Solution { public: vector<vector<int>> threeSum(vector<int> &nums) { vector<vector<int>> triplets; std::sort(nums.begin(), nums.end()); for (int index = 0; index < nums.size...
62,359,389
62,359,759
Is it true that "std::forward" and "std::move" do not generate code?
Is it true that "std::forward" and "std::move" do not generate code? I saw this saying in << An Effective C++11/14 Sampler >>. The related code is at the footnote. Could somebody explain the code in detail? I would be very grateful to have some help with this question. As per the documentation(https://gcc.gnu.org/onlin...
Whether something "generates code" or not depends on the compiler and its settings. As the other answer shows, you can expect some extra code to be generated if the optimizations are disabled. std::move and std::forward merely return a reference to the parameter, which doens't require any actions at runtime (the change...
62,359,458
62,359,490
How to initialize whole array to single element in class constructor in c++
Hi I am looking to initalize whole array to single element in constructor of class.I have tried this solution but I am getting this errror. 1>C:\Users\Ahmad Mustafa Anis\source\repos\ciruclar queue\Source.cpp(8,8): error C2590: 'sig': only a constructor can have a base/member initializer list 1>Done building project "c...
If you want to initialize all values with 0 CircularQueue() : dataItems{} {} Or, CircularQueue() : dataItems{0,0,0,0,0,0,0,0,0,0} {} If the array is too long, you can do this. It is not initializing. It's assigning after initialization. CircularQueue() { std::fill(dataItems, dataItems+10, 3); //3 for example }
62,359,628
62,360,136
How can i change values of elements of a set while comparing (in c++)?
I want to change the elements of a set while comparing, like this :- #include<bits/stdc++.h> using namespace std; struct cmp { bool operator()( pair<int,int> a, pair<int,int> b) { if(a.first<=b.first) { b.first++; } return a.first<b.first; } }; signed main() { ...
You cannot. Elements in a std::set are immutable. You would have to remove the item from the set, change it, and add it back. Other issues in the code: Don't #include<bits/stdc++.h> Don't using namespace std; Your compare function should be const. Your compare function should take its arguments by const reference; oth...
62,359,685
62,360,812
Check for Element Existence in TinyXML
I have been looking through the API for TinyXML and I can't find a way to check if an element exists before I try and get it by name. I have commented what I am looking for below: #include <iostream> #include "tinyxml.h" int main() { const char* exampleText = "<test>\ <field1>Test Me</field1>\ <fi...
The FirstChildElement function will return a pointer, so that pointer can be used in the if-statement like so. #include <iostream> #include "tinyxml.h" int main() { const char* exampleText = "<test>\ <field1>Test Me</field1>\ <field2>And Me</field2>\ </test>"; TiXmlDocument exampleDoc;...
62,359,805
62,591,053
TraciMobility::getExternalId error when adding custom module into Veins_Inet example (Omnet++)
I am attempting to add a new custom RSU module (extending AdHocHost) into the Veins_Inet example. Here is my updated scenario (with 1 RSU). network TestScenario { submodules: radioMedium: Ieee80211ScalarRadioMedium; manager: VeinsInetManager; node[0]: VeinsInetCar; // added rsu rsu: VeinsInetRSU; ...
Your application might be inheriting from VeinsInetApplicationBase, which calls TraCI methods (that fail for nodes that are not a TraCI-managed vehicle). See also its source code. To be doubly-sure, run your simulation in debug mode, turn on debug-on-errors, and check the stack trace to see where the call is coming fro...
62,359,896
62,362,178
"Cannot find -l<directory>" error - CMake
My program includes a subdirectory, because a header and a source file are there which are needed. My project looks like this: EDIT: Perhaps I didn't specify: my goal is to link frame_cap.cpp to the header grab_cut.h, as I require its functions. [-] raspicam | [-] main_folder | frame_cap.cpp | CMakeList...
The error: /usr/bin/ld: cannot find -lraspicam/main_folder/opencv-plus/ occurs because you try to link a directory to your frame_cap executable here: TARGET_LINK_LIBRARIES( frame_cap ${OpenCV_LIBS} ${OpenCVPLUS_DIR}) This doesn't make sense; only libraries should be linked to your executable. From your comments, it ...
62,359,955
62,360,401
How to sort a matrix in the descending order by the sum of its row in C++
My question is this: Given a matrix, sort it in the ascending order according to the sum of its rows. That is, if A is the following matrix: A = [2, 5, 6, 1] [8, 2, 5, 3] [9, 7, 4, 6] therefore, I would get: B = [9, 7, 4, 6] [8, 2, 5, 3] [2, 5, 6, 1] because the sum of the 1st row of A is 14, the sum ...
the easies way (but also the less efficient) is to use selection sort, so you take the smaller, you put it in first position, then you take the second smaller, and put it in the 2nd position and so on: #include <iostream> int sum(const int* array, int size){ int tot = 0; for (int i=0; i<size; i++){ tot...
62,360,110
62,360,742
lock-free "closable" MPSC queue
Multiple producers single consumer scenario, except consumption happens once and after that the queue is "closed" and no more work is allowed. I have a MPSC queue, so I tried to add a lock-free algorithm to "close" the queue. I believe it's correct and it passes my tests. The problem is when I try to optimise memory or...
I think closed = true; does need to be seq_cst to make sure it's visible to other threads before you check producers_num the first time. Otherwise this ordering is possible: producer: ++producers_num; consumer: producers_num == 0 producer: if (!closed) finds it still open consumer: close.store(true, release) becomes ...
62,360,228
62,360,273
How to make a value in C++ undefined?
I was working on a little program that would take a number as input, check if it's bigger than the variable largest and check if it's smaller than the variable smallest. Those variables were supposed to keep track of, well, the largest and smallest value entered so far. The only problem is that both values start off ho...
The simplest approach would be to set smallest to the largest possible value, and largest to the smallest possible value: double largest = std::numeric_limits<double>::lowest(); double smallest = std::numeric_limits<double>::max(); If you actually want to make a variable have no value, that's what std::optional is for...
62,360,715
62,408,608
How to send large Video file over http in c++?
I am trying to build a web server for videos and my client is a web-browser. I am using HTTP with header structure with content-Disposition: attachment std::string make_header(std::string filename, int file_size) { std::ostringstream header; header << "HTTP/1.1 200 OK\r\n"; header << "Content-Type: " << get...
The short answer is: Yes, of course. In the end, HTTP goes over TCP, which goes over IPv4/v6. IP is a sequence of small packets, and TCP is even a bytestream protocol. The other side won't notice that you are still reading bytes from disk when you're sending the first bytes. In practice, that means the client can't see...
62,360,919
62,364,047
C++ struct with dynamically allocated char arrays
I'm trying to store structs in a vector. Struct needs to dynamically allocate memory for char* of a given size. But as soon as I add the struct to a vector, its destructor gets called, as if I lost the pointer to it. I've made this little demo for the sake of example. #include "stdafx.h" #include <iostream> #include <v...
The Classroom class cannot be used in a std::vector<Classroom> safely because it has incorrect copy semantics. A std::vector will make copies of your object, and if the copy semantics have bugs, then you will see all of those bugs manifest themselves when you start using the class in containers such as vector. For you...
62,361,004
62,361,101
Visual Studio 2019 / E0167 / "const char"
I have a little problem, anyone can help me? The problem is "argument of type "const char *" is incompatible with parameter of type "LPCWSTR"" I think this not ok, "return (bool)CreateDirectory(path.c_str(), NULL)" , but i cannot realise it, that for what... the program the "path" cites. Many thanks! Code: #ifndef IO_H...
LPCWSTR expects a Unicode UCS-16 character array, which is unsigned short [] or WCHAR []. To get that from a string constant you would need to prepend the L macro like this: std::wstring s = L"\\Microsoft\\CLR"; You can also convert ASCII string to WCHAR string using mbstowcs, but for a simple short program like yours...
62,361,028
62,369,445
how to store values of x.y coordinates in different arrays
Following code returns the values of x,y coordinates on mouseclick. I want to store x coordinate in one array a[10] and y coordinate in other array b[10]. For this purpose i tried with for loop, but x,y coordinate is not shown in array. How can i store these coordinates in array? I want to click mouse 10 times on an ...
Comments are explaining your problem well. If you need exact solution, just replace your CallBackFunc() func with this: void CallBackFunc(int event, int x, int y, int flags, void* userdata) { if ( event == EVENT_LBUTTONDOWN ) { cout << "Left button of the mouse is clicked - position (" << x << ", " <<...
62,361,137
62,361,345
vector::emplace_back result to call destructor twice
Simple program is written as: #include <iostream> #include <vector> using std::vector; class Test { public: Test( int d ) : data(d), addr(&data) { } // Test( Test &src ) : data(src.data), addr(src.addr) { } const int data; const int *addr; ~Test() { delete addr; } void print()...
As mentioned in comments the problem is the delete statement in destructor which is unwanted for non-dynamic data member.
62,361,581
62,364,746
Memory not freeing up std::list<std::shared_ptr<std::string>> C++
I'm populating a list of string shared pointers. At some point in my program, I clear the list. But the memory consumption of my program does not reduce even after I call clear() function of list. Any Idea why? #include <memory> #include <string> #include <list> #include <iostream> int main() { std::string text = ...
I used both linux top (on WSL) and Windows Task Manager to check memory usage at each stop. But valgrind does not report any memory leaks. TLDR: Allocating memory is an expensive operation relative to other code paths. To improve performance, almost all heap managers will continue to hold onto the memory for subsequ...
62,361,588
62,361,769
C++: Looking for correction for "returning address of local variable..."
I am, currently, taking an online C++ class to fill my time while unemployed and I have a question concerning returning the address of a local variable. I realize that this is not a recommended practice and I'm looking for an alternate solution to what I'm trying to do (return data for copying into my object "co" which...
You can return a reference to a temporary duration object, but this is just one of the ways to shoot oneself into the foot. C++ is not a nanny language and allows this. Consider: foo& bar() { foo f; return f; } This code will compile, but what happens? At first you create an object f, but when you return from ...
62,361,744
62,397,960
Strange performance difference of matrix row summation with RowMajor and ColMajor data arrangement
I decided to check how data arrangement in matrix influences performance of simple operations. I wrote simple row summation algorithm using Eigen::Matrix as data storage. I though that RowMajor storage should demostrate better performance due to better cache utilization. I used g++ compiler with -O2 option and it gives...
The ColMajor-based loop is much faster in -O3 because GCC 7.5 is able to automatically vectorize it as opposed to the RowMajor-based loop. You can see that in the assembly code (L11-labelled loop). Automatic vectorization is not performed by GCC in -O2. Indeed, mentioned cache effects are relevant especially for big ma...
62,361,802
62,361,803
How should I loop over the elements of a C++ container in reverse order?
Suppose I'm a newbie C++ programmer. I have a C++ container; say, a vector: std::vector<int> vec { 12, 34, 56, 78 }; I know I can iterate over all of the elements with a simple loop: for(std::vector<int>::size_type i = 0; i < vec.size(); i++) { std::cout << vec[i] << '\n'; } and maybe I've even learned a little a...
Well, first of all, about your two snippets: Part of the problem is that they're a bit bug prone for actual newbies - the integer underflow, off-by-one in the comparison, forgetting what i signifies and using it as a plain index etc. So I would definitely recommend something else. Also, those snippets may invoke vec.si...
62,361,962
62,362,440
visual studio c++ project cannot find .dll
I have downloaded the Autodesk fbx sdk and trying to build a simple console app. I have added additional directories in Linker / General / Additional Library Directories like follows: see the screenshot of the directory below. There are several libs that (I suppose) I should add in dependencies, and there's also the ....
The linker settings have nothing to do with finding DLL files at run-time. If you want this SDK to be available to all programs - which without reason to do otherwise would be my recommendation - hit the start button and search for "environment", choosing "Edit environment variables for your account". Edit the value of...
62,362,032
62,363,166
When will using C subset of C++ be bad?
I am currently joining a new project in C++, but I am only acquainted with C. I will look to learn the STL and BOOST, but in the meantime, I foresee myself only programming in the C subset of C++. My question is, when will just using the C subset of C++ and compiling with the C++ compiler be notably worse than just com...
I ask mostly in performance I would say that this is the wrong metric to use. Many C++ compilers share their codebase with C compilers. That is, if a given block of code is valid C and valid C++ (with the same semantics in both languages), the object code produced by the C compiler is likely to be comparable to – if ...
62,362,084
62,362,179
C++: construction and destruction of static inner class instance in outer class
I'm new to C++ and learning the nested classes and static class member of C++, I write the code below: #include <iostream> using namespace std; class Outter { public: Outter() { //get(); cout << "construct Outter" << endl; } ~Outter() { cout << "destruct Outter" << endl; } priv...
The output is not as you expect because Inner i; is already constructed when you call get. What happens is the following: 1. In get you get a static instance to i, which is a copy operation, no default construction is going here. 3. You return a temporary copied Inner object, which gets immediately destructed, hence ...
62,362,365
62,362,677
How compiler decide which function template to call?
How compiler to decide which function to call when overloading two function templates: #include <iostream> #include <typeinfo> #ifndef B1 template <typename T1, typename T2> auto max(T1 a, T2 b) { std::cout << "auto version called" << std::endl; return b < a ? a : b; } #endif #ifndef B2 template <typename RT...
I built the code with command: $ g++ -o m1 ./maxdefault4.cpp -std=c++14 -DB1 $ g++ -o m2 ./maxdefault4.cpp -std=c++14 -DB2 It means that both two function template can match, but why no ambiguity error caused. That's not correct: when you pass -DB1, or -DB2, you are compiling only one template, so there is no que...
62,362,616
62,363,112
How is implemented this function foo.getSize().x
Recently I've start learning sfml graphics and I saw this kind of functions window.getSize().x or .y, my question is how can I write such a function, more exactly to use .x or .y on an object function?
Those functions return a vector object that have the variables x and y internally. Something kinda like this template<typename T> struct Vec2 { T x, y; Vec2(T x, T y) : x(x), y(y) }; class Window { public: Vec2<unsigned int> getSize() { return size; } private: Vec2<unsigned int...
62,363,045
62,365,421
how to open a directory using its d_name
I list the directories and then want to open the d_name of one of the entries.For this, I input an integer i.e. the number of the item in the list. and open it's corresponding file. I'm getting this error: [Error] request for member 'c_str' in 'ent->dirent::d_name', which is of non-class type 'char [260]' code: #inclu...
Remove the call to c_str(). d_name is a character array (C-style string), not a std::string type.
62,363,053
62,363,269
Getting segmentation fault in my trie implementation
I wrote a C++ program for trie implementation. But it displays segmentation fault after getting the input string (here named as elem) #include <iostream> #include <vector> #include <algorithm> using namespace std; struct trie { char val; vector<struct trie*> children; trie(char c){ val = c; ...
Use a different struct trie pointer to assign the trie find method return value. Something like below (only giving the modified logic below)- while (elements--) { cin >> elem; temp = &root; struct trie* exists; for (auto c : elem) { exists = temp->find(c)...
62,363,205
62,363,474
How to insert multiple data types of varying length into variables?
I need to insert the following values from a text file; however, I am a little confused on how to take in a name that may be of different length in C++ and spaced out differently. This is the Text file contents: 2.5 John Jones 4.0 Madonna 3.773 Ulysses S. Grant I was thinking to have a loop that tak...
You can use >> (stream extraction) for the double, and std::getline for the std::string, like this: double gpa; std::string name; while (file >> gpa && std::getline(file, name)) { std::cout << gpa << ":" << name << "\n"; }
62,363,561
62,366,657
array wrapper corrupts stack
my project is a dynamic array wrapper like std::vector. this is how it works: when adding a new element, the memory is either allocated (malloc), if it is 0, or reallocated with a new size (realloc), if it is not 0. the size is the number of elements * size of type when getting an already added element, i calculate th...
Lets take the code apart and fix it slowly. Starting with the constructor, everything should be initialized. It is very important that you initialize your variables as soon as possible: darr() { start = nullptr; end = nullptr; elemc = 0; size = 0; } Now lets look at the method a...
62,363,658
62,363,692
No return statement warning in function returning non-void
This is lines of my code that I get a warning saying "No return statement warning in function returning non-void" I have declared total as: static int total; int Rooms::getTotalEmptyRooms() { return total; } int Rooms::setTotalEmptyRooms(int i) { //warning here total = i; } Any suggestion how can I get rid of...
When you declare it as an int, it has to have return with an in inside the function. Either change the head to void Rooms::setTotalEmptyRooms(int i) { total = i; } or have it return something, like int Rooms::setTotalEmptyRooms(int i) { total = i; return total; }
62,363,891
62,364,832
Can concepts be used with template template parameters?
Let us consider following code: #include <concepts> template<typename X> struct Concrete_M { X f() const { return X{}; } }; struct Concrete_X {}; template<typename T, typename X> concept M = requires (T t) { { t.f() } -> std::convertible_to<X>; }; template<M<Concrete_X>> struct C {}; const C<Concrete_M<Co...
The shorter hand type-constraint syntax for concepts: template <Concept T> struct C { }; is only valid for those cases where Concept's first template parameter is a type parameter. When that is not the case, you have to simply use the long form syntax: a requires-clause: template <template <typename> class Z> requ...
62,363,934
62,367,835
How can i store binary data using redis-plus-plus like i want to store a structure? @for_stack?
In C, we use hiredis to store data in the form of binary by using %b specifier in redisCommand function, how can we do this in c++ using redis-plus-plus or any other alternative? #include <sw/redis++/redis++.h> #include<...
There are two ways: You can save the binary data into a std::string object, which is binary safe, and then pass the std::string object to redis-plus-plus's API. If you already have a pointer to the binary data, and the length of the data, you can construct a StringView object, and pass it to redis-plus-plus's API. st...
62,363,973
62,367,504
position of bits in binary stream
I wrote a C++ program for boost/serialization. I already write and read the items on binary stream. But problem is that, i want to change some items position. example case: void write(...){ if(!file_streamer_) { ... a_ = new boost::archive::binary_oarchive(*file_streamer_); } for(...){ (*oa_) & obj[i] ;} // ...
I don't think that a binary archive is what you think it is in the first place. docs The existence of the << and >> suggests a relationship between archives and C++ i/o streams. Archives are not C++ i/o streams There's even an entire section in the Rationale of the docs: Archives are not streams Archive classes are ...
62,364,181
62,366,483
Problem with SFML 2.5.1: Collision Detection not working
can you pls help me on what I did wrong here? I followed this tutorial on YT: https://www.youtube.com/watch?v=l2iCYCLi6MU&t=605s for making a collision detection, but my penguin seems to go through my objects. I'm very frustrated. The version of sfml i use is the 2.5.1. I use Visual Studio 2017. I promise, in the file...
I found the problem: I need to change this: Move(intersectX * (1.0f - push), 0.0f); to this: Move(-intersectX * (1.0f - push), 0.0f); the same on the Y axis. I spent all the night finding this stupid error.
62,364,193
62,365,233
Can I create a pointer to an object in the constructor of said object?
The goal is that every time I create an object of my Car class, a pointer of this object is then created and placed in the "car registry". This is what I have: class Car { private: string color = "blah blah"; string make = "blah blah"; string model = "blah blah"; public: Car(CarRegisterManager* carRegis...
You already know the answer, because you state it in your question: I know I need to use a "this" or something to indicate that this created Car object needs a pointer created for it, and then this pointer is put into the CarRegisterManager's registerCar function. You can use the literal this pointer, eg: Car(CarReg...
62,364,201
62,367,330
push_back(value) is automatically reduced by 1
Consider the following code: int t,n; cin>>t; while(t--) { cin>>n; int num,i,ct=0; vector<int> summ; i=0; while(n) { if(n%10) { cout<<(n%10)*pow(10,i)<<" "; summ.push_back((n%10)*pow(10,i)); ct++; ...
The issue is with the use of pow. You should be storing the result as either a float or a double, as storing directly into an int is causing the imprecision. This seemingly strange behaviour is well known. This behaviour appears to vary depending on your compiler. To correct this, change your vector<int> summ to vector...
62,364,334
62,364,589
How to know if the last elements are deleted in a map?
I have two maps (for sake of simplicity let's focus only on keys). I want to compare and tell the differences. Target Map: 1 3 4 6 7 8 9 Reference Map: 1 2 3 4 5 6 7 8 10 11 Using a while loop, I'm able to find differences easily. From the reference, I can tell 9 is inserted, 2, 5, 10, 11 are deleted. But the order/ind...
I can tell 9 is inserted, 2, 5, 10, 11 are deleted Do this first. Now, iterate the deleted results starting from the back, and compare to the reference map starting from the back. If the elements match, then the deleted element is last and can be removed from the results if that is what you try to achieve. Move the i...
62,364,387
62,371,514
CLion is unable to find Eigen3 on macOS
I know there have been similar questions in the past. However, none of the solutions have worked for me so far. Just a few details: I am using CLion 2020.1 and Eigen 3.3.7 on macOS 13.13.6. Just an overview of what I have done so far: I downloaded Eigen 3.3.7 and unzipped the file. After that I renamed the file from "...
I thing next solution should help here. I downloaded Eigen 3.3.7 and unzipped the file. After that I renamed the file from "eigen-3.3.7" to "Eigen3". I moved this to the "usr/local/" directory. Please try to install eige n3.3.7 via brew. Just do brew install eigen. That's it. find_package will find it properly.
62,364,810
62,380,875
Visual studio 2019 compile and build
Im learning c++, just began and want to make sure I got it right, in visual studio; pressing compile and after that build is that the same thing as pressing Local Window Debugger with the Release option?
First of all, compiling and building is basically the same as creating files when using Local Windows Debugger in Release mode. But the Local Windows Debugger will start the application and open the debugger, so it will perform some other operations. Second, cl [filename] and then run in the terminal is very different ...
62,364,904
62,364,937
Error: invalid use of void expression in parameter
I have the objective to have my loop function repeated every 1000ms thanks to the timer_start function. But everything does not go as planned : g++ -DDMP_FIFO_RATE=9 -Wall -g -O2 -c -o demo_raw.o demo_raw.cpp demo_raw.cpp: In function ‘int main()’: demo_raw.cpp:66:33: error: invalid use of void expression ...
Here timer_start(loop(), 1000); You are passing the return value of loop as the first argument to timer_start. But loop returns void (aka nothing) so that doesn't make any sense. You probably wanted to pass the function instead of the result of calling it, as in timer_start(loop, 1000);
62,365,176
62,365,826
How to drop element from std::tuple?
Given a struct A{}; struct B{}; struct C{}; std::tuple<A,B,C> tabc; How to drop second element B from it to get tuple<A,C>, like std::tuple<A,C> tac = drop<B>(tabc); or the same std::tuple<A,C> tac = drop<1>(tabc); I assume this produces a new type with copies of elements.
This is fairly simple enough to code with meta-programming techniques: template<size_t drop, size_t ...ixs> constexpr auto calc_drop_sequence_dropper(std::index_sequence<ixs...>) { return std::index_sequence<(ixs >= drop ? ixs + 1 : ixs)...>{}; } //Creates a monotonically increasing sequence on the range [0, `coun...
62,365,328
62,365,419
Execute terminal commands in C++ with arguments passed from terminal with C++ file when executing it
What would be the equivalent of the following Python code in C++? import sys, os #Example command os.system(f"touch {sys.argv[1]}")
a close equivalent can be : #include <cstdlib> #include <iostream> #include <string> int main(int argc, char ** argv) { if (argc == 2) { std::string cmd = std::string("touch ") + argv[1]; std::system(cmd.c_str()); } else std::cerr << "Usage: " << argv[0] << " <file>" << std::endl; return 0; } ...
62,365,489
62,365,688
C++ register function
i need a help to register a function from my application to a lib and can use it in lib later. The function is a singleton one. This is how i want to send it like: extern "C" void __declspec(dllexport) RegisterFunctionsLib(const std::function<void(int, const std::string&)>& func_1, const std::function<void(const std::s...
You will need to bind a member function to a specific instance, you can't just pass a member function as though it is a normal function pointer - the two things are quite different. A member function effectively consists of two things - an instance and a function. Fortunately lambdas can solve this specific issue reall...
62,365,503
62,366,073
Array Wrapper Corrupts Heap
Sequel to: array wrapper corrupts stack The project: I am working on a std::vector replacement. The error: I get a heap corruption error whenever I attempt to delete a temporary array I am creating in order to store the copied elements of another array that I delete in order to reallocate it when my array gets resized....
In your alloc function there lie a few problems, such as: if (0 == element_count) { element_count = 1; } is unnecessary. Instead, you can just do a +1 where necessary which is almost everywhere except the temp dynamic array. bool alloc(...) { this->array = new T[this->element_count]; //... else ...
62,365,614
62,365,749
Failing to link GLEW library
this is my makefile: ### OUTPUT ### BUILD = Build ### SOURCES ### SRC = Src/main\ Src/Game/Game\ Src/Shader/Shader ### OBJECTS ### OBJ = $(addsuffix .o, $(addprefix $(BUILD)/, $(SRC))) ### INCLUDES ### INC = -ID:/Development/OpenGL/Glfw/include/GLFW\ -ID:/Development/OpenGL/Glew/glew-2.1.0/include/...
In a single-pass linker (like almost all linkers today) the order of items is critical. In particular, you have to make sure that all your object files appear on the link line first, before any libraries. Secondly you have to make sure that libraries are ordered correctly, so that the higher level libraries come earl...
62,366,083
62,366,314
Binary search or iterator based on a function instead of a collection?
As a simple example, let's say I want to find the square root of N by using binary search. But I don't want to implement the binary search myself, but use std::lower_bound or similar. Can I write something like int square(int x) { return x * x; } int square_root(int N) { // Assume I know the results is between 0 a...
C++20's standard library includes ranges, which was basically made for this kind of stuff. You'll want a transform_view: int square(int x) { return x * x; } int sqrt(int x) { auto space = std::views::iota(0, x + 1) | std::views::transform(square); return std::lower_bound(space.begin(), space.end(), x) - space.b...