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
70,057,456
70,057,559
No type named 'iterator_category' in 'struct std::iterator_traits<int* const>'
I'm writing a custom vector class: #include <iterator> template <typename T> class vector { public: using value_type = T; using pointer = value_type*; using iterator = pointer; using const_iterator = const iterator; using const_reverse_iterator = std::reverse_iterator<const_iterator>; auto crbegin() cons...
The problem can be reduced to this: #include <iterator> template <typename T> class vector { public: using value_type = T; using pointer = value_type*; using const_reverse_iterator = std::reverse_iterator<const pointer>; auto crbegin() const -> const_reverse_iterator { return const_reverse_iterator(data_...
70,057,585
70,057,640
How to convert java merge sort algo to cpp
Problem I have a source code in Java for sorting array elements using the merge sort algorithm. The principle uses a loop to compare an element in the array with the element in the next index in the array. If the earlier is bigger than the later then the numbers are swapped logically to reassign the array elements in t...
For starters there is no merge sort algorithm in your question. In fact there is a modified selection sort algorithm. This function declaration void sorting(int d[]) is adjusted by the compiler to the declaration void sorting(int *d) That is the parameter has a pointer type. So the expression sizeof(d) yields the si...
70,057,715
70,079,186
How to #include inside .cpp file?
In the following example, the FileA header is included in FileB header; Some of the classes in FileB.h are forwardly declared inside FileA.h; in FileA.h //Forward Declaration. class classB; //Main classes. class ClassA { //... private: void MemberFunction(ClassB* PtrToClassBObj); } In FileB.h //Includes. #include Fil...
Is that enough to make FileA.cpp capable of accessing public members of said classes from FileB.h? No, it is not "enough" - the full definition of ClassB needs to be visible. or should FileA.cpp itself include FileB.h? It should, because it uses the class at PtrToClassBObj->MemberVariable. was the forward declarat...
70,057,831
70,058,075
Why is not possible to have a queue implemented as a vector?
What are the drawbacks of using a std::vector for simulating a queue? I am naively thinking that push_back is used for push and for pop one just stores the position of the first element and increments it. Why does not std::queue allow a std::vector implementation like this in principle (I know the reason is it has no p...
Why does not std::queue allow a std::vector implementation like this std::queue is a simple container adapter. It works by delegating pop function to the pop_front function of the underlying container. Vector has no pop front operation, so std::queue cannot adapt it. but maybe there is something deeper that makes it...
70,058,063
70,058,099
c++ opengl 4.5 doesn't show the object
I writed code which must to show triangle but it doesn't. I really don't know where is problem. I checked everything and don't find out what is the problem. If you can please help me. Here is code: #include <glad/glad.h> #include <GLFW/glfw3.h> #include <glm.hpp> int width = 800, height = 600; int main() { glfwI...
The 2nd argument to glBufferData is the size of the buffer in bytes: glBufferData(GL_ARRAY_BUFFER, 6, Points, GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, 6*sizeof(float), Points, GL_STATIC_DRAW);
70,058,259
70,058,359
How does copy constructor that returns value, discards the temp?
having this code: #include <iostream> class Base { public: Base() = default; explicit Base(int val) : _var(val) {} Base operator=(const Base &rhs) { _var = rhs._var; return *this; } void print() const { std::cout << _var << std::endl; } private: int _var; }; int...
To get the desired result of your assignment operator (which, by the way, is different from copy constructor), you need to return a reference: Base& operator=(const Base &rhs) This is the canonical form. Without the reference, the result of (b[1] = b[2]) is stored in a temporary. (b[1] = b[2]) = b[0]; assigns to that ...
70,058,310
70,058,452
What is the big-O of this for loop...?
The first loop runs O(log n) time but the second loop's runtime depends on the counter of the first loop, If we examine it more it should run like (1+2+4+8+16....+N) I just couldn't find a reasonable answer to this series... for (int i = 1; i < n; i = i * 2) { for (int j = 1; j < i; j++) { //const time ...
It is like : 1 + 2 + 4 + 8 + 16 + ....+ N = 2 ^ [O(log(N) + 1] - 1 = O(N)
70,058,519
70,058,586
Data lost after assigning object to linked list and jumping between functions (C++)
I am trying to implement an application that will involve creating a custom object (containing pointer to another customer object) and organising them into a linked list. I have created some functions to attempt to add them to linked list. Based on debugging using gdb, all values are passed to Event constructor and ad...
In addEvent, your line EventNode *tmpNode = new EventNode(e); will store a reference to e in your new node. Since you pass e by value, you've made a copy and this copy will be destroyed at the end of the function, so the reference stored in the event node will be dangling. You likely want to pass e by reference: void R...
70,058,537
70,059,740
Cannot read with `std::cin.read`: return key not recognized
I am trying to read a string from the keyboard with the std::cin.read() function. What happens is that it looks like the string is being read as I type it, but the [Return] character is treated as a normal new line, and not as a terminator. What is the terminator for this function? Is it possible to modify it? #include...
On Windows console, the EOF indicator is Ctrl+Z (not the Ctrl+C, which will invoke a signal handler routine instead, which will call ExitProcess by default). But the problem with Ctrl+Z on Windows is that it has to be the first character of a separate line (i.e., you have to press Enter and then Ctrl+Z, otherwise the C...
70,058,562
70,089,564
Align a matrix to a vector in OpenGL
I'm trying to visualize normals of triangles. I have created a triangle to use as the visual representation of the normal but I'm having trouble aligning it to the normal. I have tried using glm::lookAt but the triangle ends up in some weird position and rotation after that. I am able to move the triangle in the right ...
Your code doesn't work because lookAt is intended to be used as the view matrix, thus it returns the transform from world space to local (camera) space. In your case you want the reverse -- from local (triangle) to world space. Taking an inverse of lookAt should solve that. However, I'd take a step back and look at (h...
70,059,428
70,059,601
Convert uint64_t to int64_t generically for all data widths
How does one generically convert signed and unsigned integers into each other without having to specify the specific width? For example: uint8_t <-> int8_t uint16_t <-> int16_t uint32_t <-> int32_t uint64_t <-> int64_t It would be nice to write: uint32_t x; int32_t y; static_cast<signed>(x) static_cast<unsigned>(y) H...
However, I suspect that doesn't do what I want. Indeed, your suspicion is valid: the expression, static_cast<signed>(x), is exactly equivalent to static_cast<signed int>(x), so the cast will always be to an object of the 'default' size of an int on the given platform (and, similarly, unsigned is equivalent to unsigne...
70,059,527
70,059,863
Reorder simple 2D matrix in-place
I have a simple 2D (row, column) matrix which I currently reorder according to the algorithm below, using another array as final container to swap items. The problem is that I need to save memory (the code is running on a very low end device), and thus I need to figure a way to reorder the array in-place. The algorithm...
After you posted code, I will suggest another solution, that's rather simple and quick to implement. In your current Matrix class: struct Matrix { // ... // add this: void transpose() { is_transposed = !is_transposed; } // ... // modify these: /// Returns the numbe...
70,059,528
70,072,382
How can I convert a std::string to UTF-8?
I need to put a stringstream as a value of a JSON (using rapidjson library), but std::stringstream::str is not working because it is not returning UTF-8 characters. How can I do that? Example: d["key"].SetString(tmp_stream.str());
rapidjson::Value::SetString accepts a pointer and a length. So you have to call it this way: std::string stream_data = tmp_stream.str(); d["key"].SetString(tmp_stream.data(), tmp_string.size()); As others have mentioned in the comments, std::string is a container of char values with no encoding specified. It can conta...
70,059,598
70,059,653
Assigning value to integer literal
Whenever a prvalue appears as an operand of an operator that expects a glvalue for that operand, the temporary materialization conversion is applied to convert the expression to an xvalue. Source: https://eel.is/c++draft/basic.lval#7 Why is 5 = 6 ill-formed? Should it not perform a temporary materialization conversio...
5 = 6 is illegal by fiat. That is, it's illegal because [expr.ass]/1 explicitly says so: All [assignment operators] require a modifiable lvalue as their left operand 5 is not a modifiable lvalue. Therefore, this rule is violated and the code is il-formed. Note that it doesn't expect a "glvalue" generally; it requires...
70,060,476
70,063,066
How do I get an int with a maximum/minimum width?
I'd like to get an int with a certain width for vectorization purposes. Something like int_atleast< 3 /*bytes*/ > should give int32_t, and int_atmost< 5 > should give the same int32_t. I tried to implement this with template specialization, but hit a wall because I'd need to specialize every possible argument. I though...
A C++17 solution is surprisingly simple. if constexpr allows us to alter the return type of a function based on a constant expression. This allows one to write the algorithm rather succinctly namespace detail { template<unsigned W> auto compute_atleast_integer() { if constexpr (W <= 1) retur...
70,060,501
70,063,886
The last node in linked list not working in Bubble sort
i try to sort a linked list using bubble sort algorithm, but the last node seems to not sorted in the list. Every element in the list can be sorted but except the last one. Can anyone suggest me where i'm doing wrong and how to fix it? Thanks a lot! ( Sorry for bad English ), Here is my code: struct Node{ int data;...
first of all, j->next will be 0 if j is the last element in the list. so j will skip the last element. second of all, if you let j iterate from i to the end of the list and increase i every time, you'll skip elements. you need to move the end point to the left (aka decrease the end index) instead of moving the start to...
70,060,573
70,061,944
Loading Qt Versions property page error in Qt Vs Tools
I meet the same problem as "Qt VS Tool is not loading properly the Qt Versions in VS 2019". sceenshot is here. what I tried: Reinstall Visual Studio 2019. Reinstall Qt and Qt Vs Tools several times. Set QTDIR in my pc environment. The problem is still present. Could you give me some suggestions?
I fix it now. The cause of the problem is that the previous Qt version information remains in registry. The solution steps are following: Open regsitry editor. you can pressed keys win+r, then input regedit. Find 计算机\HKEY_USERS\S-1-5-21-1609438195-1965026858-116498148-500\Software\Digia\Versions. Delete the contents o...
70,060,699
70,060,878
Why is my code expecting a primary expression in a switch case before curly brackets?
I am trying to use a switch case as a sort of menu selection for the user in my code. I have this enum list: enum menuChoice {ADD = 1, REMOVE = 2, DISPLAY = 3, SEARCH = 4, RESULTS = 5, QUIT = 6}; Then I have this code: menuChoice switchChoice; Student student; cout << "1. Add\n" << "2. Remove\...
default: } is a syntax error. The default label must be followed by a statement or a block. (This applies to any othe sort of label too). For example it could be default: break; or default: ; or default: {} .
70,060,871
70,060,879
Does the synthesized destructor destroy the memory allocated on the heap?
I have a class without a destructor and a constructor like this: class Foo { public: Foo(int a) : p(new int(a)) {} private: int *p; }; { Foo a(4); } After this block of code will the memory allocated on the heap be released ? Or do i have to explicitly provide a destructor like this: class Foo { public: ...
Any memory we allocate on the heap using new must always be freed by using the keyword delete. So,you have to explicitly free the memory allocated by new on the heap using the keyword delete as you did in the destructor. The synthesized destructor will not do it for you. Note if you don't want to deal with memory manag...
70,060,959
70,062,171
understanding c++ move_constructible concept implementation
I've got the following implementation of the c++ concept move_constructible from cppreference template<typename _Tp> concept move_constructible = constructible_from<_Tp, _Tp> && convertible_to<_Tp, _Tp>; I don't get why this works. I presume any type can be converted to itself, so the second requirement is poi...
Most traits/concepts automatically add && to the types of "source" arguments (things that are passed to functions, as in std::is_invocable, or constructed from, as in std::is_constructible). I.e. constructible_from<A, B> is equivalent to constructible_from<A, B &&> (&& is automatically added to the second argument, but...
70,061,769
70,062,378
How to declare a template function with a std::ratio template parameter
I'm trying to define three functions with C++14 as below: template <typename D = std::chrono::seconds> typename D::rep test() { // somethinig } template <std::intmax_t N, std::intmax_t D = 1, typename V = uint64_t> V test() { // something } The two functions work as expected. I can call them like test<std::c...
Define some traits to detect whether the type T is a specialization of duration or ratio: #include <chrono> #include <ratio> template<class> struct is_duration : std::false_type { }; template<class Rep, class Period> struct is_duration<std::chrono::duration<Rep, Period>> : std::true_type { }; template<class> struct ...
70,061,779
70,061,854
Weird behaviour when using the modulo operator between a negative int and std::size_t
This code snippet: #include <iostream> #include <cstddef> int main() { int a{-4}; std::size_t b{3}; std::cout << a % b; return 0; } prints 0 while this code snippet: #include <iostream> int main() { int a{-4}; int b{3}; std::cout << a % b; return 0; } prints -1 So, why does the...
Oh, it's because a implicitly converted into std::size_t becuase b is std::size_t, which is 4294967292(on my machine), and 4294967292 % 3 == 0
70,062,212
70,062,576
Creating a pointer to a class in a function belonging to a different class
I'm trying to populate a vector of type pointer to class B, which I'll be using later. When I try to read the vector's element, the value I'm getting is different from what I've given. Can someone please help me here, what mistake I'm making and how to correct it? Thanks #include <iostream> #include <vector> class B {...
Using value instead of pointer, as per the comments above: #include <iostream> #include <vector> class B { public: int b; B (int n) { b = n; } }; std::vector<B> v; class A { public: int a; void func(int n); }; void A::func(int n) { v.emplace_back(n); } int main() { A obj_...
70,062,653
70,062,831
SUMMARY: UndefinedBehaviorSanitizer
Trying to solve Odd Even Linked List question. Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. My try: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ...
The problem is (once we fix the typo): ListNode *l = nullptr; ListNode *u = l; ... return u; u is always nullptr. One quick hack would be: ListNode *l = nullptr; ListNode **u = &l; ListNode *r = nullptr; ListNode **ru = &r; ... l->next = *ru; return *u; Or you could try: if(r == nullptr){ r = c; ru = r; // A...
70,062,766
70,128,634
Set XMM register via address location for X86-64
I have a float value at some address in memory, and I want to set an XMM register to that value by using the address. I'm using asmjit. This code works for a 32 bit build and sets the XMM register v to the correct value *f: using namespace asmjit; using namespace x86; void setXmmVarViaAddressLocation(X86Compiler& cc, ...
The simplest solution is to avoid the absolute address in ptr(). The reason is that x86/x86_64 requires a 32-bit displacement, which is not always possible for arbitrary user addresses - the displacement is calculated by using the current instruction pointer and the target address - if the difference is outside a signe...
70,063,812
70,063,933
Why shared_ptr object works well without lock in such case?
One reader thread & multi writer threads concurrently access shared_ptr object and it works well, code as below (BUT, if i modify the write line code from "=" to "reset", it will coredump while reading) : shared_ptr.reset means coredump and "operator =" means works well ? ( I tried more than 100 times) bool start = fa...
Both versions suffer from a race condition. std::shared_ptr is not magically thread-safe. If you want to share it between threads, you have to protect it with a mutex. Just that you tried it a few times is no proof: It could be that it's just very unlikely to cause errors or even that the error is impossible on your co...
70,063,981
70,064,357
How to do press any key to continue prompt?
I am writing a program where the code reads off the text from a .txt file in where anything more than 24 lines must be continued with the enter key, but unsure how to put in the prompt asking for the enter key that doesn't mess up the formatting as it must show the first 24 lines instantly. #include <iostream> #include...
Just place braces {} for the appropriate if (as pointed out in the comments) and your program will work. Note also that there is no need to use ifstream twice as you did in your program. #include <fstream> #include <string> #include <iostream> int main() { std::string fileName; std::cout<<"Enter filename"<...
70,064,017
70,064,857
crypto++ Sending IV to another Function but i get an error: StreamTransformationFilter: invalid PKCS #7 block padding found
Test Program to Encrypt using crypto++, then it sends the iv and message as IV::EncryptedMessage. I am able to encrypt but get a padding error #7 when decrypting, I've searched for hours but can't find anyway to pass a std::string IV to crypto++. I believe my error is in the decc function, where I use hexdecode? string...
I Decoded the hex of the IV but never the actual encrypted message. Of course I seen it after I posted smh... This is a functional example of crypto++ encode and decode functions for anyone looking for it. string encc(string plain) { using namespace CryptoPP; AutoSeededRandomPool prng; SecByteBlock iv(A...
70,064,144
70,064,339
Find if allocation is trivially resizable?
realloc may simply update bookkeeping info here and there to increase your allocation size, or it may actually malloc a new one and memcpy the previous allocation (or may fail). I want to be able to query the memory manager if an allocation is trivially resizable (either because it reserved more than I mallocd or becau...
Suggest realloc anyways. This can be quite inefficient for large quantities of data, where the double-copy can have serious effect. Due to reasons why realloc can sometimes avoid copying and allocation, this is an irrelevant point because in practical implementations, that condition doesn't exist with large quantitie...
70,064,702
70,065,134
Display words that do not contain the specified letter
#include <string> #include <windows.h> #include <stdlib.h> #include <sstream> using namespace std; int main() { string s = "We study C++ programming language first semester.", word; cout << s << endl; s.pop_back(); stringstream in (s); while (in >> word) { if (word.find('e') == s...
If you really want to go with only std::string and loops, I guess maybe this? But it's a lot longer than just using stringstream and such, #include <iostream> #include <string> int main() { std::string s = "We study C++ programming language first semester."; s += ' '; //safeguard; std::string word = ""; ...
70,065,317
70,065,556
"const std::string &getStr" vs "std::string getStr"
Can someone explain in simple words why a developer did the following const std::string &getStr() const { return m_Str; } instead of std::string getStr() const { return m_Str; }
That's two separate things. The second example returns a copy of the member variable m_Str, the first one a constant reference to the same variable. The difference is quite noticeable, if you take a look at the caller of this method. Imagine another method setStr that changes the member variable. Now take a look at the...
70,065,971
70,099,839
UDP livestream (GoPro Hero4) opens using OpenCV in python but not in C++
i want to do image processing on a GoPro Hero4 Black livestream using OpenCV in C++. The firmware version is 5.0. With python it successfully works. When i implement it the same (!) way in C++ status 31 and 32 switch to 1 when opening the VideoCapture, so the livestream is started and the client is connected. However, ...
The solution was to deactivate the windows firewall for private networks. Cant be more trivial but in case someone struggles at that point...here is the hint :)
70,066,137
70,066,267
nLohmann lib in C++ from raw http data
I have raw http data char text[] = R"({\"ID\": 123,\"Name\": \ "Afzaal Ahmad Zeeshan\",\"Gender\": true, \"DateOfBirth\": \"1995-08-29T00:00:00\"})"; I am using Json nlohmann lib , it gives me the parse error and if i tried the following then it parse R"({"happy": true, "pi": 3.141})" Is the nloh...
You are using a raw string literal so drop the backslashes: char text[] = R"({ "ID": 123, "Name": "Afzaal Ahmad Zeeshan", "Gender": true, "DateOfBirth": "1995-08-29T00:00:00" })"; Full example: #include <nlohmann/json.hpp> #include <iomanip> #include <iostream> using json = nlohmann::json; int main...
70,066,434
70,066,528
Why is temporary object living after end of the expression
Why if string getString(){ return string("string"); } int main(){ const string& a = getString(); cout << a; } Will give an UB This: class vector{ void push_back(const T& value){ //... new(arr + sz) T (value); ++sz; } } main(){ vector v; v.push_back(string("abc")); } will be OK? ...
Case I: I guess that in first case temporary object expires right after end of the expression const string& a = getString(); Note that, const references are allowed to bind to temporaries. Also, const references extend the lifetime of those temporaries. For example, const int &myRef = 5; Here the reference myRef e...
70,066,544
70,066,646
Problem with structure and organization in big c++ project
I started my first big c++ project, in which I divided the functionality of the program into different files. I ran in a situation where library include each other and there was some declaration problem. sometingh like this: in apha.h #pagma once #include "betha.h" struct alpha { int data; betha bb; }; int fu...
For starters it seems there are two typos in the header name apha.h that should be alpha.h and in this declaration int fun1(apha a); It seems you mean int fun1(alpha a); After including the header apha.h in a compilation unit you in fact have struct betha { double data; double moreData; }; int fun2(alpha a...
70,066,685
70,067,022
Unhandled exception when trying to retrieve the value from the JSON ptree using Boost C++
I am getting the below error when reading the value from the JSON ptree using Boost C++ Unhandled exception at 0x7682B502 in JSONSampleApp.exe: Microsoft C++ exception : boost::wrapexcept<boost::property_tree::ptree_bad_path> at memory location 0x00DFEB38. Below is the program, Could someone please help me what i am ...
There is a shape mismatch between your code and your data: The data is a plain nested dictionary: Student.name is "John". The code expects to see an array under the Student key, so it tries to fetch Student.0.name, Student.1.name, ... for every subitem of Student. Either fix the code: // Drop the BOOST_FOREACH auto &...
70,066,919
70,066,969
expected primary expression before } in C++
Why a label can not be placed immediately before }while(/*exp*/); in a do-while loop, instead of expecting a primary expression. int main() { int x = 5; do{ if(x==2) goto label; printf("%d", x); label: ; // if not error: expected primary-expression before ‘}’ token ...
Labels may be placed before statements. The symbol '}' does not denote a statement. So you need to include a null statement after the label and before the closing brace. label: ; }while(--x); Pay attention to that it is better to rewrite the do while statement without the goto statement like do{ if ( x...
70,067,946
70,068,460
How can I get qjsonvalue to string?
What should i do to get output for example: Bid value is 2248.48? Here is code: QNetworkRequest request = QNetworkRequest(QUrl("https://api.30.bossa.pl/API/GPW/v2/Q/C/_cat_name/WIG20?_t=1637005413888")); QNetworkReply* reply = m_manager.get(request); QObject::connect(reply, &QNetworkReply::finished, [repl...
You either want _quote.toString() (first listing) or root.toString() (second listing)
70,068,085
70,068,463
Why can an object with deleted copy- and move-constructor still be passed to a function accepting an r-value reference?
I have the following code, which apparently compiles in MSVC and GCC: #include <iostream> class Test { public: Test() = default; Test(Test const& other) = delete; Test(Test&& other) noexcept = delete; Test& operator=(Test const& other) = delete; Test& operator=(Test&& other) = delete; auto getX() -> int ...
rvalue references are just references just like lvalue references. The difference between them is the kind of expression that can be used to initialize them. std::move casts an lvalue reference to an rvalue reference. It doesn't require the type to be movable. If you try to actually move thing in something then you wil...
70,068,251
70,068,756
How to quickly search a large vector many times?
I have a std::vector<std::string> that has 43,000 dictionary words. I have about 315,000 maybe-words and for each one I need to determine if it's a valid word or not. This takes a few seconds and I need to complete the task as fast as possible. Any ideas on the best way to complete this? Currently I iterate through on ...
Is there a better way to iterate multiple times? Yes. Convert the vector to another data structure that supports faster lookups. The standard library comes with std::set and std::unordered_set which are both likely to be faster than repeated linear search. Other data structures may be even more efficient. If your goa...
70,068,327
70,068,422
Updating a variable in a struct
So I just created a struct that makes a rectangle. the struct itself look likes this struct _rect { //bottom left vertex int x = 0; int y = 0; // width and height int width = 0; int height = 0; //top right vertex int y2 = y + height; int x2 = x + width; }; //init rect _rect ...
You should create a specific class: class Rect { public: Rect(int x, int y, unsigned int width, unsigned int height) : m_x(x), m_y(y), m_width(width), m_height(height) {} int x() { return m_x; } int y() { return m_y; } int top() { return m_y + m_height; } int right() { return m_x + m_width; } private: ...
70,068,998
70,070,145
Is the pointer from casting to base gurenteed to be a pointer into the memory region of the derived object
Given this code: #include <cassert> #include <cstring> struct base{ virtual ~base() = default; }; class derived: public base{ public: int x; }; using byte = unsigned char; int main() { byte data[sizeof(derived)]; derived d; memcpy(data, &d, sizeof(derived)); base* p = static_cast<base*>(rei...
potentially wrong alignment your data array is a char array, so its alignment will be 1 byte. your class however contains an int member, so its alignment will be at least 4 bytes. So you data array is not sufficiently aligned to even contain a derived object. You can easily fix this by providing an alignment of your da...
70,069,151
70,070,935
Prevent fmt from printing function pointers
I have a following buggy program. Logic is nonsense, it is just a toy example. #include <ranges> #include <iostream> #include <fmt/format.h> #include <fmt/ranges.h> template<typename T> constexpr bool size_is_4(){ return sizeof(T)==4; } int main() { std::cout << fmt::format("float size is 4 bytes : {}\n", si...
This is a bug caused by function pointers not caught by the pointer detection logic. I opened a GitHub issue: https://github.com/fmtlib/fmt/issues/2609. Update: the issue has been fixed.
70,069,205
70,069,247
error: ‘leftHeight’ was not declared in this scope
I have the following function to computer height of a node in a binary tree (and its descendants): void computeHeight(Node *n) { // Implement computeHeight() here. if (n->left) { computeHeight(n->left); int leftHeight = n->left->height; } else { int leftHeight = -1; } if (n->...
The problem is that you have defined leftHeight inside if else block and therefore they are not visible outside of those blocks. Similarly the variable rightHeight is also visible only inside the blocks in which it was defined. To solve this just define leftHeight outside(of those blocks) once and then just assign valu...
70,069,540
70,069,596
C++ singleton class by making the constructor private
I tried to use the pattern to make a class practically a singleton by making the constructor non-public. However, when I tested it, the result is not what I expected. If only one instance is created, the value should be the same for the references, but apparently, they are different like below. What is wrong with the c...
auto type deduction does not include references. Instead each instance variable will be its own copy of the object. You must explicitly use & to define a reference: auto& instance1 = SortOfSingleton::getInstance(); ... auto& instance2 = SortOfSingleton::getInstance(); On that note you need to disallow copying as we...
70,069,688
70,069,726
Want to compile only if statement in if-else
I am working on a project which should have to run on both ros melodic (ubuntu 18.04) and ros noetic(ubuntu 20.04). so while doing so I made an if-else statement in my code that, if(distro=="noetic"){ ...do this else ...do this The problem occurs basically, noetic and melodic support different versions of Poin...
Use preprocessor macros. This needs to be handled before compile time. The preprocessor macros #ifdef and #ifndef will check if a token is present in the symbol table (check the documentation for your OS to see if there is a defined token for it), and skip to the according if/else section. #ifdef NOETIC_DISTRO //Code ...
70,069,717
70,070,767
Queries for cyclic proportional assignment of work to hosts
Consider M pieces of work distributed over N hosts in a cyclic way where each host must get the amount of work proportional to its speed. Without proportions, this is implemented as: int64_t AssignWorkToHost(const int64_t i_work) { return i_work % N; } Proportions are weights p[i] that sum up to 1.0, so that i-th ho...
I would suggest using a priority queue storing pairs of (estimated processing time, worker) with a custom comparator that compares in that order. In pseudo-code, the body of assign to work looks like this: (estimated_time, i) = queue.pop() queue.push((estimated_time + worker_time[i], i)) return i This is deterministic...
70,069,809
70,069,810
"Unrecognised emulation mode: ain" when compiling with gcc on Ubuntu
Consider the following code lying in main.cpp: #include <iostream> int main() { std::cout << "Hello World!\n"; } Compilation with g++ main.cpp -o -main fails: /usr/bin/ld: unrecognised emulation mode: ain Supported emulations: elf_x86_64 elf32_x86_64 elf_i386 elf_iamcu elf_l1om elf_k1om i386pep i386pe collect2: er...
You've accidentally typed a dash before specifying your output file: it should be -o main, not -o -main, so the full command line is g++ main.cpp -o main GCC has a -m key which allows specifying target machine architecture. For some reason, even when -main immediately follows -o, GCC still checks that the architecture ...
70,069,882
70,069,909
Class constructor doesn't seem to be working?
Hi I'm new to c++ and I would like to know why the following code is not working as expected: #include <iostream> using namespace std; class Person { public: int age; Person(){ int age = 20; } }; int main() { Person p; cout << p.age << endl; } I'm expecting to cout 20, but the program ret...
You are creating a local variable age with value 20 and doing nothing else with it. Your constructor needs to look like this: Person() : age{20} {} Then it will actually initialize the instance field as expected. (Otherwise age = 20; in the constructor body (without the int declaration that hides the field name) would...
70,070,178
70,070,233
Problem with dynamic arrays (I suppose) for numbers from 200
I am writing an algorithm which outputs all prime numbers in range [3; n]. Take a look at my code and I will explain the problem: #include <iostream> using namespace std; int main() { int n; cout << "Enter the value of n:" << endl; cin >> n; int k = (n - 2) / 2 + 1; bool* nums = new bool[k]; ...
This loop while (i + j + 2 * i * j <= k) { nums[i + j + 2 * i * j] = false; j++; } might access nums out of bounds in the last iteration, when i+j+2*i*j == k, because the last valid index is k-1. Out of bounds access is undefined behavior in C++, hence your code might appear to work for n <...
70,070,537
70,070,576
save line from file to char pointer in c++, without pointing to variable
This might be a very basic c/c++ question, but I am really struggeling at it right now. I have a struct that looks something like this: struct connection_details { const char *server, *user, *password, *database, *mysql_port, *ssh_port; }; And I have the data in a seperate text file. So I would like to write a fun...
If you want to store string data in a way that is kept around as long as the struct is alive, then std::string does exactly that. So, ideally, you should replace the const char* members of connection_details with std::string: struct connection_details { std::string server, user, password, database, mysql_port, ssh_...
70,071,109
70,072,187
error when declaring an inner class template field
I have an error with the following code, using the inner template class Node. the error is when declaring the root private field: "member root declared as a template". template <typename KeyType, typename ValueType> class TreapBST : public AbstractBST<KeyType, ValueType> { public: ..... private: template <typen...
I think you have the basic idea right but are getting the syntax confused. When you write a class template you do not need to keep repeating template <typename K, typename V> for each member unless you want that K and V to be two types that are different from class parameters KeyType and ValueType. If you just need Key...
70,071,581
70,071,848
How to split definition and declaration with friend function and inheritance
I need to compile something like this: struct Base { virtual void func1()=0; // ... friend void Derived::func2(Base *base); private: int some_private; } struct Derived : Base { virtual func3()=0; // ... void func2(Base *child) { std::cout << child->some_private; } }; But I keep...
You have a few basic solutions. The most obvious is to change from private to protected. In C++, protected means subclasses have access. You can add more public (perhaps protected) accessor methods instead. You can forward-reference the entire Derived class and friend the entire class. Personally, I have never felt a n...
70,071,928
70,072,041
Having different specialization of a class template and the specialization definitions have functions with other specializations in its signature
So I have a class template for example in Template.h template <typename T> class Something { public: static_assert(std::is_floating_point<T>::value, "Floating Point only"); }; and I separated the float and double specialization into different .h files float.h #include "Template.h" template<> class Something<...
An explicit specialization is a distinct class and does not have to resemble the original template at all. You can change the functions, make completely different ones, or whatever. This is usually the point of partial specialization, so a const T can be a different interface than a plan T etc. Any explicit specializa...
70,072,105
70,072,148
"More?" in C++ when taking in console input
I was programming in C++ when I noticed some... odd behavior when taking in console input. Let me explain. #include <iostream> int main(int argc, char *argv[]) { if (argc == 1) { std::cout << "Hello!\n"; } if (argc >= 2) { } } Pretty simple program, right? Now, when I type in "programName ^" ...
I'm able to reproduce the behavior with g++ on Windows. The DOS shell is interpreting "^" as some kind of "continuation character". The ^ symbol (also called caret or circumflex) is an escape character in Batch script. When it is used, the next character is interpreted as an ordinary character. Look here for more det...
70,072,902
70,232,896
c++ vector string problem about case sensitivity
so in c++ 'A' and 'a' are different characters, if we have a vector that contains both upper and lowercase letters, how to write a function that transforms this vector into some vector that is case insensitive, for example, 'ABba' becomes the same as 'abba'. so for example, I want to count the number of different cha...
The standard approach for doing case insensitive comparisons is: Decide for either upper or lower case and convert all letters to this case. Then, do your operations. In C++ you have a family of functions for that purpose. std::toupperand std::tolower. Please check in CPP Reference. If you know what character set you h...
70,072,926
70,079,715
yaml-cpp : How to read this yaml file content using c++ /Linux (using yaml-cpp version = 0.6.3 )
i am trying to read each Node and its respective content (yaml content is below) I am ending up with belwo error . Error: terminate called after throwing an instance of 'YAML::TypedBadConversion sample code : #include <yaml-cpp/yaml.h> YAML::Node config = YAML::LoadFile('yamlfile'); std::cout << config["Circles"]["x"]...
The code in the question does not match the sample.yaml file you've provided but here's an example of how you could extract the floating points you have in the Rectangle in sample.yaml. #include "yaml-cpp/yaml.h" #include <iostream> int main() { try { YAML::Node config = YAML::LoadFile("sample.yaml"); ...
70,073,211
70,073,342
How do you find a string/char inside another string that's in a vector in C++? [that works for me]
I looked this up on multiple forum pages, not just stack overflow, and have tried many solutions from the 'Check if a string contains a string in C++' post, along with others, and tried almost every single solution posed but none of them seem to work for me? I tried the vector[i].find(std::string2) along with if(strstr...
How do you find a string/char inside another string that's in a vector in C++? If the std::vector<std::string> isn't sorted, I would use std::find_if. Example: #include <algorithm> #include <iostream> #include <string> #include <vector> int main() { // A vector with some strings: std::vector<std::string> vec...
70,073,526
70,104,450
Matrix multiplication in c++ armadillo is very slow
I'm doing some basic multiplication using armadillo but for some reason it takes very long to complete. I'm quite new to c++ so I might be doing something wrong, but I can't see it even in this very basic example: #include <armadillo> #include <iostream> using namespace arma; int main(){ arma::vec coefficients = ...
Armadillo is a template-based library that can be used as a header-only library. Just include its header and make sure you link with some BLAS and LAPACK implementation. When used like this, armadillo assumes you have a BLAS and LAPACK implementation available. You will get link errors if you try to use any functionali...
70,073,540
70,074,272
C++ detect if a type can be called with a template type
I'm working on a program where some data is statically allocated and some is dynamically allocated. Now I want to have another type that can be called with any template of the type as its argument. #include <array> #include <vector> template <int size> class Foo { std::array<int, size> data; public: int& operator[]...
A callable F could write a restriction that it can be called by Foo<x> such that an arbitrary function of x must be true to be valid. In order for your "can be called with any Foo" test to work, you would have to invert an arbitrary function at compile time. There is no practical way to do this short of examinjng all 2...
70,074,226
70,074,280
How compile a c++ complex folder with a simple command?
I have a many c++ files in a folder: > project - a.cpp - a.h - b.cpp - b.h - main.cpp - .editorconfig - .gitignore And use this command to compile my code: g++ *.c* -o main However I need organize my code in > project > src > classes - a.h - b.h > methods - a.cpp - b.cp...
I would try to compile it with the following command: g++ src/main.cpp src/methods/*.cpp -I src/classes -o myprogram As long as your compilation times are reasonable, there is not much need to use a build system like Make yet. I don't know if it's a good directory structure, but that's a pretty subjective question. I...
70,075,005
70,081,226
Issues working with "raw" pointers. How do I remove duplicate values from a custom Linked List?
Right now my code is a little... over-complicated. I feel I must be missing a simpler algorithm for getting this task done. Basically the only rules for this assignment are that we can't use containers or other libraries. I'll include my code below so you might get a better idea what I'm trying to do. The code compiles...
I would suggest providing a remove method on your linked list, and then you can just remove any found duplicates in your nested loop: void removeNode(Node* node) { // This method assumes that the provided node is a member of the list if (node == head_) { head_ = head_->next; } el...
70,075,048
70,078,863
Would using placement new make the following code valid?
I am building a buffer that will be used in a class and wanted to know if the following is valid according to the C++ standard: #include <iostream> #include <cstdint> int main() { alignas(std::int32_t) char A[sizeof(std::int32_t)] = { 1, 0, 0, 0 }; std::int32_t* pA = new (&A) std::int32_t; std::cout << *pA << st...
(Assuming int and int32_t are the same type for brevity) In C++20, since A is an array of characters, an object of type int can be implicitly created in A, so only the following is needed: alignas(int) char A[sizeof(int)] = { 1, 0, 0, 0 }; int * pA = reinterpret_cast<int*>(&A[0]); std::cout << *pA << std::endl; The p...
70,075,288
70,075,358
Can a concept satisfaction of an expression, contains both type and the reference?
Is there a way to make the following code not so bloated? I mean join both type and a reference somehow (|| does not work). template<typename T> concept IntegralVector = std::integral<typename T::value_type> && requires(T t) { { t.size() } -> std::convertible_to<std::size_t>; } && (requires(T t) { { t[0] } -> s...
You probably want something like this: template <typename T, typename U> concept decays_to = std::same_as<std::decay_t<T>, U>; To use as: template<typename T> concept IntegralVector = std::integral<typename T::value_type> && requires (T t) { { t.size() } -> std::convertible_to<std::size_t>; { t...
70,075,346
70,075,583
Issues reading text from a file. Getting double reads
Hello friends at stackoverflow! I have written a program that saves 3 strings to a textfile. The code to write is: void my_class::save_file(const char* text) { for(auto ad: ad_list) { std::ofstream outputFile; outputFile.open(text, std::ios::app); if (outputFile.is_open()) { outp...
You can simplify your splitString function to look like below. Note the second parameter to splitString is a char now and not a std::string. //note the second parameter is a char and not a string now vector<string> splitString(string text, char delimiter) { vector<string> parts; std::string words; std::ist...
70,075,933
70,075,956
c++ sort() function is not sorting my vector
This is my code - Problem: The sorting comparator function which I have written is not doing anything. the code gets executed, comparator function also runs, but it does not modify my vector. And I don't understand why. Logic(which I have written): I have used region index as an index of my vector. For each region I h...
for (auto vec : cands) { This create a copy of the elements in cands, not the actual element of cands itself. Change your code to: for (auto &vec : cands) {
70,076,273
70,076,531
What does ch!=?.? mean in c++
This is used here do {....} while(ch!=?.?); what does ch!=?.? mean here can anybody please help with it.
It's a syntax error with both clang and gcc. @JonathanLeffler is usually right and I think he nailed the root cause. I used to see this when text was being copied from Microsoft Word to the web (lack of transcode from a Windows code page to ascii/utf8?).
70,076,659
70,077,070
In C++, how do I fix a pointer class's variable becoming a nullptr when I call it?
I want to use a class: class2, within a class: class1. From what I read, to prevent a circular dependency, one must forward declare class2 in class1.h and have it be a pointer. After calling a function from class2 in my class1.cpp file. I'm unable to call the variables within class2 without getting "Unable to read memo...
Generally, it is a good idea to keep dependencies between headers to a minimum, and using pointers for classes that are only forward-declared is an established way to do that. This is good practice even if there are no circular dependencies because it can greatly reduce recompilation times in large projects. Regarding ...
70,076,843
70,897,891
The matplotlibcpp show an error when I use subplot() in cpp
I tried to use matplotlibcpp.h for plotting graph in c++ code. Normal graphs are plotted well. However, when I write plt::subplot(); the program throw runtime error with "Call to subplot() failed". How can solve this problem? Below is my source code. #include <iostream> #include <vector> #include <map> #include <string...
I had this problem too. But I finally found that if you use root user to run it or "sudo ./your_program", it would be alright enter image description here
70,076,998
70,077,024
all multiples of 3 from 1 to 100 by a for loop in c++
for (int x = 3; x <= 100; x%3 == 0; x++ ) { printf("%d\n", x); } I'm using the book "how to program C" by Deitel and there is this exercise, for this for loop, and they want me to fix it and get the output of all multiples of 3. I've solved this with an if statement. But im curious if there is another way to fix it w...
You can add 3 instead of 1 after each iteration, so that it will guarantee to be a mutiple of 3 Something like this: for (int x = 3; x <= 100; x += 3) { printf("%d\n", x); }
70,077,013
70,077,248
memory leak in c++ and how to fix it
I am getting this error with memory leak, I know i have to deallocate the memory but how to do it I am getting this error with memory leak, I know i have to deallocate the memory but how to do it please guide SongCollection::SongCollection(char* filename) { try { std::ifstream file("songs.txt"); if (file) { whi...
The "best"™ solution is to not use pointers at all, as then there's no dynamic allocation that you can forget to delete. For your case it includes a few rather minor changes to make it work. First of all I recommend you create a Song constructor taking all needed values as arguments, then it becomes easier to create So...
70,077,570
70,089,910
Make a event for a mouse button even if application is minimized
I want to make an application that responds to a mouse button so I done this: case WM_LBUTTONDOWN: MessageBox( NULL, (LPCWSTR)L"HALLOOOO", (LPCWSTR)L"Worked", MB_ICONASTERISK | MB_OK | MB_DEFBUTTON2 ); break; but the problem is that this only work...
Since you already have a window, call SetWindowsHookEx with WH_MOUSE_LL. The API is documented here and the parameters are explained. HHOOK SetWindowsHookExW( [in] int idHook, [in] HOOKPROC lpfn, [in] HINSTANCE hmod, [in] DWORD dwThreadId ); The lpfn hook procedure can be defined as follows: HWND hm...
70,077,576
70,077,787
How to properly read data from CSV file in C++
My input file userinfo.csv contains username and password in this format username,password shown below. frierodablerbyo,Rey4gLmhM pinkyandluluxo,7$J@XKu[ lifeincolorft,cmps9ufe spirginti8z,95tcvbku I want to store all the usernames and passwords in vector<string> usernames; vector<string> passwords; I've never used C...
You can try something like this std::vector <std::pair<std::string, std::string>> vec_credentials; std::ifstream is("credentials.csv"); if(is.is_open()) { std::string line; while(getline(is, line)) { std::stringstream ss(line); std::string token; std::vector <std::string> temp; ...
70,078,468
70,079,348
Are move semantics guaranteed by the standard?
I think I understand the gist of move-semantics in general but am wondering, whether the C++ standard actually guarantees move-semantics for std-types like std::vector. For instance is the following snippet guaranteed to produce check = true (if the used compiler/std-lib is standard-compliant)? std::vector<int> myVec; ...
I believe this is guaranteed for allocator-aware containers by the following requirement from [tab.container.alloc.req]: X(rv) X u(rv); Postconditions: u has the same elements as rv had before this construction;... Note the words "same elements", not "elements with the same content". For instance, after std::vector<i...
70,079,733
70,090,828
Opengl Camera rotation around X
Working on an opengl project in visual studio.Im trying to rotate the camera around the X and Y axis. Thats the math i should use Im having trouble because im using glm::lookAt for camera position and it takes glm::vec3 as arguments. Can someone explain how can i implement this in opengl? PS:i cant use quaternions
The lookAt function should take three inputs: vec3 cameraPosition vec3 cameraLookAt vec3 cameraUp For my past experience, if you want to move the camera, first find the transform matrix of the movement, then apply the matrix onto these three vectors, and the result will be three new vec3, which are your new input int...
70,079,824
70,079,908
Error when passing arguments to pthread_create()
I am trying to create a Thread-Pool-like structure for pthreads to do identical jobs for network programming, which is very similar to this question. However, a problem occurred as I tried to pass the arguments of the init() method to pthread_create(). Code class ThreadPool{ public: BlockingQueue socket_bq;...
The definition of threads is incorrect. It should be: pthread_t* threads[THREAD_NUM];
70,080,102
70,082,595
How do i "filter" output from vector<Parent*>
Here is the problem. I have vector<D2*>, where D2 is a Parent. I add there childs: D3 and D4. void readFromInput(std::vector<D2*>& vec) { std::cout << "\nSecond class input"; int x = 0, y = 0, z = 0; std::cout << "\nEnter x: "; std::cin >> x; std::cout << "Enter y: "; std...
For your particular case you can use dynamic_cast<T>(expression). See some other stack overflow answers dynamic_cast and static_cast in C++ When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? You can do something like this void output(std::vector<D2*>& vec) { for (const auto...
70,080,132
70,080,179
winforms identifiers are not visible
I have a button click event handler that draws a graph. System::Void Practform::MyForm::draw_Click(System::Object^ sender, System::EventArgs^ e) { . . . } then I decided to put the drawing of the graph into a separate function, since I would have to call it for the timer.and I got the following...
You are missing a reference to the System::Drawing assembly. Add using namespace System::Drawing; at the top of your program. System::Windows::Forms contains classes related to, well, forms and controls. System::Drawing contains class related to, well, drawing.
70,080,192
70,080,336
Can we replace `if (!x) x=true` with `x=true` directly?
I am doing some refactoring work and came across such a piece of code: bool x = false; ...// maybe some logical work would change the value of x. if (!x) { x = true; } So, I am curious whether I can do such a replacement: x = true; As you can see, I assign x to true directly, which may reduce the number of instru...
x = true; is clearer than if (!x) { x = true; }. From performance point of view, former avoids branching, whereas the later doesn't touch to "cacheline" (in one case). And compiler might change one to another with as-is rule anyway.
70,080,350
70,080,961
QCandlestickSet is undefined C++ Qt5.15
I'm using Visual Studio 2019 Community x64, Qt version 5.15.2. I have the 'Charts' module installed and selected in Project -> Properties -> Qt Project Settings -> Qt Modules My code: #include <QCandlestickSet> struct Bar { double open, close, high, low; qint64 timestamp; Bar() : open(0.0), close(0.0), h...
As mentioned in the comments by G.M., everything QtChart related is held within a namespace called QtCharts. Doing any of the following will fix this issue: using QtCharts::QCandlestickSet; OR using namespace QtCharts; OR QtCharts::QCandlestickSet * toCandle(void) { return new QtCharts::QCandlestickSet(this->open...
70,080,367
70,080,722
How to read Ctrl+C as input
(in Linux) The methods I found all use signal . Is there no other way? Is there anything I can do to make the terminal put it into the input buffer?
In order to "read CTL+C as input" instead of having it generate a SIGINT it is necessary to use tcsetattr() to either clear cc_c[VINTR] or clear the ISIG flag as described in the manual page that I linked to, here. You will need to use tcgetattr, first, to read the current terminal settings, adjust them accordingly, th...
70,081,393
70,102,704
Clang Tidy config format
At the moment I am using the Clang Format utility in my project. In order to share its settings in my team, I put the .clang-format configuration file in the root of the project folder, and now IDE automatically loads it when working with the project. In the same way, I want to use the Clang Tidy utility. However, unli...
.clang-tidy file format is actually specified in the command-line help, see the documentation. --config=<string> - Specifies a configuration in YAML/JSON format: -config="{Checks: '*', Che...
70,081,432
70,082,530
How to explicitly instantiate a func template with no parameter?
I have a member func template as following: using ArgValue_t = std::variant<bool, double, int, std::string>; struct Argument_t { enum Type_e { Bool, Double, Int, String, VALUES_COUNT }; template<typename T> as( const Argument_t& def ) const; std::string name; ArgValue_t valu; ArgValue_t max...
I think I found the answer: The type ArgValue_t is a instance of the template std::variant with arguments: bool/double/int/std::string, but NOT with int8_t/uint8_t/int16_t/uint16_t/... as arguments, therefore in the invokations of get(), it only can accept bool/double/int/std::string as template arg. May I complain the...
70,081,830
70,083,194
Getting an exception when reading values using BOOST_FOREACH from the JSON array in C++
I am getting the below error when reading the values using BOOST_FOREACH: Unhandled exception at 0x76FCB502 in JSONSampleApp.exe: Microsoft C++ exception: boost::wrapexcept<boost::property_tree::ptree_bad_path> at memory location 0x00CFEB18. Could someone help me how to read values from the array with the below JSON f...
You asked a very similar question yesterday. We told you not to abuse a property tree library to parse JSON. I even anticipated: For more serious code you might want to use type-mapping Here's how you'd expand from that answer to parse the entire array into a vector at once: Live On Coliru #include <boost/json.hpp> #...
70,082,108
70,082,365
How to make a template specialization for integral, floating and char* types without if constexpr?
I need a function void foo(T &t) that will have one implementation for char*, another for std::is_integral_v and yet another for std::is_floating_point types. I don't want to make a constexpr approach because it would create a gigantic function with a lot of branches that are difficult to navigate and understand and sc...
This does the job: // For integral types only: template<typename T> std::enable_if_t<std::is_integral_v<T>> foo(T *t) { cout << "integer" << endl; } // For floating point types only: template<typename T> std::enable_if_t<std::is_floating_point_v<T>> foo(T *t) { cout << "floating point" << endl; } template <ty...
70,082,344
70,157,161
Initializing an array of trivially_copyable but not default_constructible objects from bytes. Confusion in [intro.object]
We are initializing (large) arrays of trivially_copiable objects from secondary storage, and questions such as this or this leaves us with little confidence in our implemented approach. Below is a minimal example to try to illustrate the "worrying" parts in the code. Please also find it on Godbolt. Example Let's have a...
What you're trying to do ultimately is create an array of some type T by memcpying bytes from elsewhere without default constructing the Ts in the array first. Pre-C++20 cannot do this without provoking UB at some point. The problem ultimately comes down to [intro.object]/1, which defines the ways objects get created: ...
70,082,906
70,082,950
Why do so many libraries define their own fixed width integers?
Since at least C++11 we got lovely fixed width integers for example in C++'s <cstdint> or in C's <stdint.h> out of the box, (for example std::uint32_t, std::int8_t), so with or without the std:: in front of them and even as macros for minimum widths (INT16_C, UINT32_C and so on). Yet we have do deal with libraries eve...
Why do so many libraries define their own fixed width integers? Probably for some of the reasons below: they started before C++11 or C11 (examples: GTK, Qt, libraries internal to GCC, Boost, FLTK, GTKmm, Jsoncpp, Eigen, Dlib, OpenCV, Wt) they want to have readable code, within their own namespace or class (having t...
70,083,091
70,196,247
How to safely compare std::complex<double> with Zero with some precision Epsilon?
I need to safely check is my complex number a zero (or very similar to it). How can I do it for floating point numbers? Can I use something like: std::complex<double> a; if(std::abs(std::real(a)) <= std::numerical_limits<double>::epsilon() && std::abs(std::imag(a)) <= std::numerical_limits<double>::epsilon()) { //... }...
Have you tried std::fpclassify from <cmath>? if (std::fpclassify(a.real()) == FP_ZERO) {} To check if both the real and imaginary part of a complex are 0: if (a == 0.0) {} As mentioned by @eerorika a long time before I did. An answer you rejected. Floating point precision, rounding, flag raising, subnormal is all imp...
70,083,167
70,084,355
no matching function for call to 'LiquidCrystal::write(String&)'
void printOnLcd(String s){ for (int i =0; i<2; i++){ if( i % 2 == 0){ for(int a=0; a<16; a++){ lcd.setCursor(a,i); lcd.write(s); delay(200); lcd.setCursor(a,i); lcd.write(" "); } } else { for(int a = 0; a<16; a++){ ...
now I don't have a chance to look for a possible solution. Open a webbrowser, enter www.google.com, enter "Arduino LiquidCrystal", click the first hit: https://www.arduino.cc/en/Reference/LiquidCrystal < the Arduino manual btw. Read it! You're trying to use LiquidCrystal.write, so click write and read. Syntax lcd.w...
70,083,616
70,083,687
Create std::string from int8_t array
In some code int8_t[] type is used instead of char[]. int8_t title[256] = {'a', 'e', 'w', 's'}; std::string s(title); // compile error: no corresponding constructor How to properly and safely create a std::string from it? When I will do cout << s; I want that it print aews, as if char[] type was passed to the construc...
Here you are int8_t title[256] = { 'a', 'e', 'w', 's' }; std::string s( reinterpret_cast<char *>( title ) ); std::cout << s << '\n'; Or you may use also std::string s( reinterpret_cast<char *>( title ), 4 );
70,083,648
70,083,739
Updating an array (passed as parameter) inside a C++ function
I have the following declaration and function call: unsigned int myArray[5] = {0, 0, 0, 0, 0}; ModifyArray(&myArray[0]); The above code cannot be modified, it is given as is. I need to write the implementation for ModifyArray to update myArray to contain 1, 2, 3, 4, 5. I have written it as: void ModifyArray(unsigned i...
*out_buffer is an unsigned int. &updatedValues is an unsigned int(*)[5] - a pointer to an array of five elements - which you can't assign to an int. You should not assign any arrays (it's impossible), you should modify the contents of the given array: void ModifyArray(unsigned int *out_buffer) { out_buffer[0] = 1;...
70,083,774
70,083,926
Metaprogramming - power-like function
I want to define template which would behave similar to power function a^n a^n = -1 where a < 0 or n < 0 a^0 = 0 (so not exactly as std::pow) otherwise std::pow I have a problem defining the condition for point 1 - I assume this will be a combination of enable_if and some defined constexpr checking whether integer is...
There are several ways Simpler IMO, would be constexpr function constexpr int hc_impl(int a, int n) { if (a < 0 || n < 0) return -1; if (n == 0) return 0; int res = 1; for (int i = 0; i != n; ++n) { res *= a; } return res; }; template <int a, int n> struct hc { constexpr int v = hc_i...
70,083,996
70,084,044
Variable is not declared in the scope error in c++?
I'm new bee in c++! I'm to iterate over integers using the for loop, but getting the error error: ‘frame’ was not declared in this scope auto position_array = (*frame)[i][j]; But as you can see in the code below it is declared auto ds = data_file.open_dataset(argv[1]); // auto fra...
Sounds like you need a nested for loop. Using for (int i = 0; i < 3; ++i) { auto frame = data_file.read_frame(ds, i); for (size_t j = 0; j < nsamples; ++j) { for (size_t k = 0; k <= 2; ++k) { // j<=2 assign all columns auto position_array = (*frame)[i][j]; } corr.sample(f...
70,086,124
70,086,373
Copying parent nodes
I'm trying to write a copy-constructor that is only allowed to copy from a parent node. Since I'm constrained to using C++17, I would like to accomplish this by imitating concepts/require clauses with the use of the std::enable_if type trait (if there is a better way to accomplish this, please let me know). #include <f...
Your code and SFINAE usage for node(node<O> const&) (currently commented) look OK to me. If I uncomment the static_assert, my local g++ 11.2.0 by msys2 yields the following error: a.cpp: In instantiation of 'node<N>::node(const node<O>&) [with int O = 4; int N = 3]': C:/tools/msys64/mingw64/include/c++/11.2.0/bits/invo...
70,086,144
70,086,244
Template type inference using std::views
I am coming somewhat belatedly to Functional Programming, and getting my head around ranges/views. I'm using MSVC19 and compiling for C++ 20. I'm using std::views::transform and the compiler doesn't seem to be inferring type as I might naively hope. Here's a small example, which simply takes a vector of strings and com...
This has nothing to do with views. You can reduce the problem to: template <typename T> int length(T const& x) { return x.length(); } template <typename F> void do_something(F&& f) { // in theory use f to call something } void stuff() { do_something(length); // error } C++ doesn't really do type inference. Wh...
70,086,227
70,086,336
C++ ofstream Binary Mode - Written file still looks like plain text
I have an assignment that wants plain text data to be read in from a file, and then outputted to a separate binary file. With that being said, I expect to see that the contents of the binary file not to be intelligible for human reading. However, when I open the binary file the contents are still appearing as plain tex...
As stated here, std::ios::binary isn't actually going to write binary for you. Basically, it's the same as std::ios::out except things like \n aren't converted to line breaks. You can convert text to binary by using <bitset>, like this: #include <iostream> #include <vector> #include <bitset> int main() { std::stri...
70,086,350
70,087,313
Unexpected output in c++ classes and copying objects to another object
I have a robot class that has a pointer vector of ints (to store work done history), however when I copy an object of one robot to another and the first robot goes out of scope, and then I print the history of the robot it gives me a massive list of random numbers. I ve tried making my own copy constructor and setting ...
Here's one example of how to implement the five special member functions in the rule of 5. First, your default constructor and the constructor taking a string could be combined so that the default constructor delegates to the one taking a string: Robot(const std::string& name) : _history(new std::vector<int>()), ...
70,086,762
70,087,190
byte-wise operation on multibyte native types idomatically
In C I would, without hesitation, write the following: uint32_t value = 0xDEADBEEF; uint8_t *pValue = &value; for (size_t i = 0; i < sizeof(value); i++) { pValue[i] ^= 0xAA; } But in C++17 I'm faced with two constraints from my code scanner Use "std::byte" for byte-oriented memory access. Replace "reinterpret_ca...
As noted at https://en.cppreference.com/w/cpp/language/ Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true: ... AliasedType is std::byte (since C++17), char, or unsigned cha...
70,087,104
70,087,160
In C++, how to express the largest possible value of a type via its variable name?
Assuming there is a declaration in a header file you don't control that states something like: static const uint16 MaxValue = 0xffff; // the type could be anything, static or not Inside a file that includes the above you have code like this: int some_function(uint16 n) { if (n > MaxValue) { n = MaxValue; ...
typeid results in a type_info const & rather than the type of variable, use std::numeric_limits<decltype(variable)>::max() instead.
70,087,348
70,087,968
How to create if statement from curl command output (c++)
I am trying to get the output of the curl command to work inside of an if statement I am new to C++ and don't know how I could do this. int curlreq; curlreq = system("curl localhost/file.txt"); string curlreqstring = to_string(curlreq); if ((krxcrlstr.find("hello") != string::npos) ) { cout << "hello\n"; } else if ...
std::system returns an int with an implementation-defined value. On many platforms, 0 means success and anything else means some sort of failure. I'm making this assumption in the below example. My advice is to use libcurl which is what the curl command is using internally. With a little setup you can make your program...