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
72,370,627
72,372,732
error C2106: '=': left operand must be l-value when trying to change value from function
I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list. I have a function that returns the data in the first node. I want to be able to change it using queue1.front() = 3;. However, I am getting lvalue required as left operand of assignment ...
The member functions T Node::getData() ... T Queue<T>::front() ... returning a copy of the member m_data, which is an r-value temporary. In order to work with assignment, you need non-const l-value reference qualified T. Hence, the compiler error. Therefore, you need the following fix: template<class T> class Node { ...
72,371,911
72,372,473
How is incrementing and dereferencing the iterator faster than incrementing a separate variable and indexing it into the array?
Why is the following: for (auto & x : vec) { /* do stuff with x */ } faster than for (int i = 0; i < v.size(); ++i) { /* do stuff with v[i] */ } As my title said, I was told that incrementing and dereferencing the iterator faster than incrementing a separate variable and indexing it into the array, but don't underst...
The only way it MAY be faster, at least in unoptimized code is because you call size() member function at beginning of every iteration and it's really depends on container and type of iterator it uses. Otherwise using iterators for array-like container is same as using pointer arithmetics and which order is faster dep...
72,372,117
72,372,353
How can I retrieve the return value of pclose when the unique_ptr is destroyed?
As @user17732522 pointed out that the deleter of std::unique_ptr is supposed to be callable with exactly one pointer as argument. How can I retrieve the return value of pclose when the unique_ptr is destroyed? This code snippet does not compile, #include<memory> #include<iostream> #include<string> #include<cstdio> int...
Since you can only provide a custom deleter which can be callable with exactly one pointer as argument, you can not have the lambda with two arguments in it as deleter. Your lambda with capture will also not work, as it can not be converted to a pointer to a function (i.e. only stateless lambdas can be converted to fre...
72,372,253
72,372,341
cannot find the nanosleep function when cross compile configure
I use toolchain from here, then extract to gcc11_arm_armv7_none_gnueabihf, below is command: export ASFLAGS='-march=armv7-a -fPIC -fstack-protector -Wall -fno-omit-frame-pointer --sysroot=gcc11_arm_armv7_none_gnueabihf/arm-none-linux-gnueabihf/libc -no-canonical-prefixes -Wno-builtin-macro-redefined -D__DATE__=redacte...
nanosleep requires _POSIX_C_SOURCE >= 199309L feature macro as specified by man nanosleep. Try adding #define _POSIX_C_SOURCE 199309L before #include <time.h>.
72,372,495
72,372,601
Not able to load texture using DSA
My code works if i don't use DSA to create texture. This is how i am creating texture using DSA. My opengl version is 4.6 unsigned int loadTexture(char const* path) { unsigned int textureID; // glGenTextures(1, &textureID); glCreateTextures(GL_TEXTURE_2D, 1, &textureID); int width, height, nrCompone...
You have to create the texture storage with glTextureStorage2D. e.g.: glCreateTextures(GL_TEXTURE_2D, 1, &textureID); glTextureStorage2D(textureID, 1, GL_RGBA8, width, height);
72,373,002
72,383,335
fscanf read another format in same file.csv
My data file: name/month/date/year 1.Moore Harris,12/9/1995 2.Ragdoll Moore,11/5/2022 3.Sax,Smart,3/1/2033 4.Robert String,9/7/204 bool success = fscanf(fptr, "%[^,]", nameEmploy) == 1; bool success = fscanf(fptr, ",%d", &month) == 1; I only can read 1,2,4 and then the program skips No.3. What should I use in this fo...
To parse the CSV file, it is recommended to read one line at a time with fgets() and use sscanf() to parse all fields in one call: #include <stdio.h> #include <string.h> struct data { char name[32]; int month, day, year; }; int parse_csv(FILE *fp) { char buf[256]; char c[2]; struct data entry; ...
72,374,384
72,376,916
patchelf set interpreter to a path relative to executable
I have tried to do this: patchelf --set-interpreter ../lib/ld-linux-x86-64.so.2 "${APPDIR}/usr/bin/myapp" so I have this: readelf -l AppDir/usr/bin/myapp ... [Requesting program interpreter: ../lib/ld-linux-x86-64.so.2] But it looks like it does not like the relative path as I get the error: $ AppDir/usr/bin/myapp ...
You need to specify the path relative to the current working directory (the one you use to execute the program) and not relative to the directory that contains the binary file. echo 'int main() { return 0; }' > main.c gcc -Wl,--dynamic-linker=./lib/ld-linux-x86-64.so.2 -o main main.c mkdir bin mkdir lib cp /lib64/ld-l...
72,374,472
72,374,545
How to exit QApplication from another thread?
So the problem is that in any application sometimes the GUI might freeze. Regardless of why it has happened, I want to be able to terminate/exit/quit my application. Is there any way to do it from another thread (in the same application instance)? Assume that the GUI event loop is frozen and stuck in a while(1); line f...
Do you want a hard or a graceful exit? For a super hard exit, that can't be blocked by shutdown handlers (destructors, functions registered with atexit) use the C standard function abort: https://en.cppreference.com/w/cpp/utility/program/abort
72,374,596
72,374,758
How can I get the correct json in FlatBuffers?
I successfully parsed the data,but then are not correct json data.How can I get the correct json in FlatBuffers? My code: auto result = GenerateText(parser, in, &json_data); flatbuffers::SaveFile("test.json",json_data.c_str(), json_data.size(), true); test.json`s content: { account: "0520-1", passwd: "", device:...
You need to enable the strict_json option on the Parser, otherwise you don't get the quoted field names that JSON requires: auto options = IDLOptions(); options.strict_json = true; auto parser = Parser(options);
72,375,020
72,375,659
c++: cross interactions within dual hierarchy
In a C++ application, I have two class hierarchies, one for Workers and for Stuff. I want each sub-class of Worker to interact differently with each sub-class of Stuff through a do_stuff function. I'm not sure how to do that without systematically down-casting both the worker and stuff inside do_stuff and have specific...
A bit of an effort to implement, but at least possible: class Worker1; class Worker2; class Stuff { public: virtual ~Stuff() { } virtual void doStuff(Worker1*) = 0; virtual void doStuff(Worker2*) = 0; }; class Worker { public: virtual ~Worker() { } virtual void doStuff(Stuff* stuff) = 0; }; class ...
72,375,442
72,375,695
I made this code where it will display the product of all positive integer inputs inputted by the user, but the output is wrong
So we were tasked to create a program that will ask user a positive integer until the user inputted a non-positive number or zero and then display the product of all positive inputs. Using function prototypes. Everything is working fine, however, the displayed output is wrong. I'm guessing it's related to the formula ...
Let's say you input 2 at the beginning of the program. Now you'd expect total to be 2 (2*1 = 2). But with what you're doing, this is not the case: total += product(userNum, total); ..substituting values in this case: 1 += product(2, 1); ..which is 3. What you're doing is adding the product of userNum and total to tot...
72,375,794
72,376,365
Template class compiles with C++17 but not with C++20 if unused function can't be compiled
The following compiles without error in VS2019 (version 16.11.15) with C++ 17 selected as the language. But it fails with C++ 20 with error "error C2027: use of undefined type 'Anon'" template <typename T> class a_template { public: void do_something(class Anon& anon) const; }; template <typename T> void a_templat...
Is this a change in language rules? No, this is due to the fact that a C++ compiler is permitted (but not required!) to diagnose errors at the time the template is parsed when all of the instantiations of the template would produce that error. This means that for your given example, at the time of parsing the definit...
72,376,102
72,376,167
Delete nth node from both beginning and end of singly linked list
I'm just starting to learn linkedlist. I can come up with an approach to delete a nth node from the beginning and end separately but I couldn't take care of the checks needed to perform both at the same time. Delete nth node from both beginning and end INPUT: 1->2->3->4->5->6->7->8->9->10->NULL N =4 OUTPUT: 1->2->3->5...
Suppose you are at node 3. helper = this -> next -> next; delete this -> next; this -> next = helper; So basically you need to get to the node after the one you seek to delete prior to that deletion as then there will be no way of accessing it. To check if there are any nodes at all: if(root == NULL) { /// there are...
72,376,163
72,376,316
What is the proper syntax in C++ for template classes with pointer template types with reference variables?
If I have a template class like this: template <class T> class MyClass { public: virtual void MyFunction(const T& t) { /// } }; How will MyFunction look like in a concrete class with a pointer T? class Data; class MyDerivedClass : public MyClass<Data*> { public: void MyFunction(???) ove...
If you really want this setup, you can. Example: class MyDerivedClass : public MyClass<Data*> { public: using value_type = Data*; // alias to simplify overriding void MyFunction(const value_type& dpr) override { // .... } }; how should I use the variable? You'd use it like any other pointer. N...
72,376,513
72,376,804
a value of type "int" cannot be assigned to an entity of type "Node<int> *"C/C++(513)
I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list. I have a function that returns the first node. I want to be able to change the m_data in the first node using queue1.front() = 3;. However, I am getting invalid conversion from ‘int’ to...
Queue<T>::front() is returning a Node<T>*& when it should return a T&. Example: template <class T> T& Queue<T>::front() { if (this->m_size == Queue<T>::SIZE_EMPTY) { throw Queue<T>::EmptyQueue(); } return m_head->getData(); } template <class T> const T& Queue<T>::front() const { if (this->m_siz...
72,377,360
72,377,494
How come std::initializer_list is allowed to not specify size AND be stack allocated at the same time?
I understand from here that std::initializer_list doesn't need to allocate heap memory. Which is very strange to me since you can take in an std::initializer_list object without specifying the size whereas for arrays you always need to specify the size. This is although initializer lists internally almost the same as a...
The thing is, std::initializer_list does not hold the objects inside itself. When you instantiate it, compiler injects some additional code to create a temporary array on the stack and stores pointers to that array inside the initializer_list. For what its worth, an initializer_list is nothing but a struct with two poi...
72,377,596
72,383,290
verify google IdToken with jwt-cpp
How to verify google tokenId jwt with jwt-cpp lib or something else lib on c++? I tried to redo the example from the library on github, but I don't have enough knowledge in tokens to do everything right, that's what I got: std::string raw_jwks = R"({ "keys": [ { "kid": "486f16482005a2cdaf26d92...
The array in your question raw_jwks is a JSON Web Key Set (JWKS). This contains an array of public keys. The key ID is either kid which you have or commonly x5c. Some libraries accept a public key in the raw number format (n and e), others require that you create a public key in PKCS format from those numbers first. I ...
72,377,861
72,378,114
create member variable of type that contains atomic value as its member
I'm using a third-party library with a class containing atomic<double>. Now the library returns a reference to that class object while calling a function. Now I want to keep that reference somewhere to reuse it in my application workflow. Here is the actual class from the third party lib Here is the function that retur...
TL;DR How about writing this? Gauge & g = prometheus::BuildGauge() .Name("cpu_usage_percent") .Help("cpu usage in percent") .Register(*m_registry) .Add({}); Long Answer If you have a function returning a reference, say X &f(); then you ca...
72,378,266
72,385,294
With boost::json, Is it possible to declare two separate value_from conversions in different namespaces?
Lets say I have a class Customer in namespace Data. Using boost, I know I can convert this into valid JSON by declaring a function with the signature: void tag_invoke( const value_from_tag&, value& jv, Customer const& c ). However, in all of the examples in the boost documentation, it appears that this tag_invoke funct...
Tag invoke is a more useful implementation of the old-fashioned ADL customization points. But it still heavily uses ADL. That means that associated namespaces are considered for overload resolution. See https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1895r0.pdf for rationale. You can declare unrelated overloa...
72,378,941
72,379,004
.hpp files not running in vscode
I was trying to create a .hpp file in vscode, but when I tried running it I was told it was not compatible with my system. However, I am able to use and run .cpp files just fine. TreeNode.exe is not compatible with the version of Windows you're running. Check your computer's system information and then contact the soft...
*.hpp are the header files without main() function, whereas *.cpp files containing main() function are for compiling through (gcc or clang). To test out your *.hpp files you need to include it in *.cpp file. #include "./my_header_file.hpp" Always remember, main() is the entry of your program, it should exist. Also, I...
72,379,023
72,379,248
Can you read and delete chunk of a file?
I am using ofstream and ifstream to read a chunk from a file post it over middleware (DDS) to another process and the other process writes that chuck of the file. Basically transferring a file. The two components are unaware of each other and may live on the same hardware or on different hardware (DDS takes care of the...
I am using linux, so I can use any linux APIs directly, but would probably prefer a pure c++ approach. I can't really see any good options here. i/ostream does not appear to let you do this. Options like sed will (I think) end up using more memory by copying. Are there any better mechanisms for doing this? There is n...
72,379,364
72,379,654
What does "template <> int line<0>::operator[](int y) const" do?
#include <bits/stdc++.h> using namespace std; constexpr int mod = 1e9 + 7, maxn = 2e6; int N, M, p[1 << 10], buf[maxn]; template <bool t> struct line { int *v; int operator[](int y) const; }; template <> int line<0>::operator[](int y) const { return v[y]; } template <> int line<1>::operator[](int y) c...
What is this operator thing? Is it a function? If it is then why does it have square brackets You're declaring operator[] as a member function of the class template named line. By providing this, we say that we're overloading operator[] for our class template line(really for a specific class type that will be instant...
72,379,380
72,379,469
Callback With Forwarding vs Without
Lets say I have a function which triggers a callback. template <typename Callback> void call_callback(Callback&& rvalue_callback) What is the difference between the following to calling snippets: no forwarding: { rvalue_callback(); } with forwarding: { std::forward<Callback>(rvalue_callback)(); } A cal...
... rvalue_callback First of all, note that you are dealing with a forwarding (or universal; common non-standard word) reference here, not an rvalue reference. For details, see e.g.: rvalue reference or forwarding reference? What is the difference between the following to calling snippets: You can assume in you...
72,379,704
72,379,835
invalid operands of types 'const char*' and const char[4]' to binary 'operator+'
I am getting the below error when I use the query to insert data in a database . This is my code : void Journal::insert_info() { //Variables int id_journal= getId_journal(); string nom_journal=getNom_journal(); //Here is where the error string insert_query = "INSERT INTO `info_journal`(`id_journal`, `...
Like the error message says, you can't add pointers and arrays The problematic part is: "INSERT ..." + id_journal + "','" Here the literal string "INSERT ..." will decay to a pointer (const char*) and then the value of id_journal is added. This result in the pointer &(("INSERT ...")[id_journal])). In other words, the ...
72,379,794
72,381,181
iterator operator++ overload compiling error
I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list. I've implemented iterator for Queue that points to the address of the node, I've already succeeded implementing begin(),end() and ==,!=, and tested too, but I'm unable to implement ++()...
How do I make it work without typename at the start of the definition? If you meant about the function Queue<T>::Iterator::operator++() definition, you can do it via trailing return type as follows: template<class T> auto Queue<T>::Iterator::operator++() -> Iterator& //^^^ ^^^^^^^^^...
72,380,211
72,381,282
Global function call from function in unnamed namespace with the same name
I have a some code. file1.cpp: extern void callout(); int answer() { return 5; } int main(){ callout(); return 0; } file2.cpp #include <iostream> using std::cout; using std::endl; namespace { int answer() { cout << ::answer() << endl; return 12; } } void callout() { cout <...
First of all, if you want to call a function, it needs to be declared in the translation unit. The answer function from file1.cpp is currently not declared in file2.cpp's translation unit. To fix this add a header file included in both .cpp files containing int answer(); (By the way: extern on a function declaration i...
72,381,138
72,381,399
Random ABCD char generator
I am making a quiz game and want when the player calls his friend(which is a simple cout), the program prints a random char of an answe(A, B, C or D) and a random number to present how sure he is(from 1 to 100). Whetever I try the char in console is always D, and the number is always 87. I don't know how to make this w...
Random numbers generation is not as simple as you might think. See here some general info: Random number generation - Wikipedia. In order to use rand properly, you should initialize the random seed (see the link). Using the current time as seed is recommended for getting "nice" random values. Note that setting the seed...
72,381,198
72,388,616
std::conditional - Invalid parameter type ‘void’ even when testing for 'void'
The following compiles on Visual Studio: template<typename ArgType, typename ReturnType> struct Test { using FunctionPointerType = std::conditional_t< std::is_same_v<ArgType, void> , ReturnType(*)() , ReturnType(*)(ArgType) >; FunctionPointerType Func; }; int main() { Test<void,...
In std::conditional_t<B, T, F> both the true and false specialization should have valid types T as well as F. In your case, since the F deduce to an invalid char(*)(void) type, std::conditional can not be used here. I would suggest a helper traits function_ptr_t as alternative #include <type_traits> template<typename ...
72,381,728
72,396,026
Cannot find >>() and <<() declared in unnamed namespace
The simplified example bellow illustrates the problem with the stream operators >> and <<. The example compiles in GCC10 and GCC11 with C++17 standard, but it does not compile in GCC 12.1. In GCC 12, the operators >> and << for ns_f::A declared in an unnamed namespace are not found. This is my first question, why are n...
When using an operator like << (or calling a function with unqualified name) there are two ways that matching names (i.e. here operator<< overloads) can be found as candidates. The first way is by simple unqualified name lookup which traverses the scopes from inner to outer until the name is found, and then stopping. T...
72,381,803
72,381,839
C++ higher order functions: different results when declaring multiple functions
I was plying with higher order functions, and I started getting different results when I created two instances and assigning them to variables. I reduced the issue to the following example: #include <iostream> using ColorGetter = int(*)(void); auto paint(const ColorGetter &f) { return [&]() { return f(); }; } in...
Let's look at this code: auto paint(const ColorGetter &f) { return [&]() { return f(); }; } The f parameter only exists for the lifetime of the function paint. Your lambda function captures it by reference (that's the [&] bit), and so your lambda capture is referencing a variable (the reference f) that no longer e...
72,382,432
72,383,295
Templated constexpr function invocation with partially defined class changes subsequent results
I have a struct with multiple overloads of a static function taking some counter<int> as an argument: struct S { static void fn(counter<1>); static void fn(counter<2>); static void fn(counter<3>); }; A templated constexpr function can be used to look for a specific overload in that class: template <typenam...
The section of the standard that is supposed to govern this kind of code is [temp.point]. Unfortunately, it's considered to be defective. CWG 287 The standard technically says that in your example, where count_fns<U> is referenced inside the definition of U, the point of instantiation is considered to be right after th...
72,382,695
72,383,055
Issue when calling template function that returns a pointer to base class
My goal is to create many objects of derived classes and store them in a std::map with a std::string as a key and the pointer to that object as the value. Later in the flow, I access all the keys and values and call some virtual functions re-implemented in the derived classes. I ended up in a situation where I had to c...
Your map expects pointers to free-standing functions, but your createT() is a non-static class method, so it is not compatible (also, your createT() is not actually return'ing anything). When insert()'ing into your map, you are calling createT() and then trying to insert its returned object pointer, when you should ins...
72,382,940
72,383,585
I get a warning when I try to run the recursion program with return keyword
I was expecting 1 2 3 as output, but when I try to run this code: #include <iostream> using namespace std; int fun(int x){ if (x>0){ return fun(x-1); cout<<x<<endl; } } int main() { int x=3; fun(x); return 0; } I get this warning: warning: control reaches end of non-void function...
Once a function has return'ed, it can't execute any more code: if (x>0){ return fun(x-1); cout<<x<<endl; // <-- NEVER EXECUTED } The warning is because your function has a non-void return type, but is not return'ing any value when x is <= 0, thus causing undefined behavior. Try this instead: #include <iostream...
72,383,004
72,383,449
Initialze a member of a C++ templated class only for specific type
Suppose I have a templated class like this: template <typename C> class ValArray { ValArray() = default; ValArray(const ValArray&) = delete; C& operator[](size_t pos) { return _values[pos]; } ... private: std::array<C, ARRAY_SIZE> _values; }; This is instantiated with lots of different types. What ...
In C++17 and later, you can use if constexpr inside the constructor to assign the array elements, eg: template <typename C> class ValArray { public: ValArray() { if constexpr (std::is_same_v<C, bool>) { _values.fill(false); } } ... private: std::array<C, ARRAY_SIZE> _values...
72,383,007
72,383,327
Speed of native R function vs C++ equivalent
When I compare the speed of the native Gamma function gamma in R to the C++ equivalent std::tgamma I find that the latter is about 10-15x slower. Why? I expect some differences, but this is huge, isn't it? My implementation: library("Rcpp") library("microbenchmark") cppFunction(" double gammacpp(double x) { ...
Look at the code of gamma() (for example by typing gamma<Return>): it just calls a primitive. Your Rcpp function is set up to be convenient. All it took was a two-liner. But it has some overhead is saving the state of the random-number generator, setting up the try/catch block for exception handling and more. We hav...
72,383,405
72,383,570
Question on while (true), while (cin >> x && x), while (cin >> x, x)
I have encountered a problem with this task: your input is a number and the output is from 1 to the input number. If the number is zero, the output will be nothing. For instance your input is 5 10 3 0 Your output will be 1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 1 2 3 So, there are apparently three answers. The first solution...
The >> operator, by convention, when applied to an istream object should return the istream object itself. So the return value of cin >> x is the cin object itself. When used as a Boolean, a stream object returns truthy if there are no errors in input/output. while (cin >> x && x) This says "while the loop successfull...
72,383,571
72,384,031
Deducing a shared base of two classes in C++
I am almost certain that what I'm looking for cannot be done without reflection, which is not yet in the language. But occasionally I'm getting surprised with exceptional answers in SO, so let's try. Is it possible to deduce the "common_base" of two types that have a common shared base class, so the following would be ...
The standard library's std::common_reference<> is tantalizingly close to what you want, and arguably what your foo() function should be using, as it clearly expresses the desired semantics: template<typename T1, typename T2> std::common_reference_t<const T1&, const T2&> foo(const T1& a1, const T2& a2) { if(a1 < a2)...
72,383,979
72,384,080
Dynamically allocate buffer[] for URLOpenBlockingStreamW() output
I'm super new to C++ and I'm trying to download an executable file from a URL and write it to disk. I have the below code which successfully downloads the file and stores it in memory. The issue I am having is then writing that to disk. I am pretty sure this is down to where I am creating the buffer where the downloade...
The IStream that URLOpenBlockingStreamW() gives you isn't guaranteed to be able to give you the full file size up front, so if you want to hold the entire file in memory, you will have to use std::vector or other dynamically-growing buffer. Though, you don't actually need to hold the entire file in memory just to save ...
72,384,300
72,384,883
Access Violation when using OpenSSL's Camellia
I'm trying to write a camellia decryption program in windows using c++ as the language and OpenSSL as the cryptographic provider. When attempting to execute the code I get the following error Exception thrown at 0x00007FFABB31AEF8 (libcrypto-3-x64.dll) in Lab8.exe: 0xC0000005: Access violation reading location 0x00000...
Looks like you need to declare unsigned char plaintext; to be unsigned char plaintext[17];, otherwise you're overwriting uninitialized memory.
72,384,353
72,384,703
How to get value from a vector by value from another vector?
I have two vectors: one contains numbers and names of things; second collects numbers that have already been showed to the user; I'm trying to make a history list of all objects that have been shown. Here is my code: class palettArchive{ private: std::vector<std::pair<int,std::string>> paletts; int palletsCount...
for_each and lambda are just making your life difficult. The simpler code is explicit iteration: void history() { for (auto i : choosen) { auto tempPair = paletts[i]; std::cout << tempPair.first << " " << tempPair.second; // did you mean to send a newline "\n" al...
72,384,672
72,384,696
How can I avoid circular dependency in my Makefile compiling obj file with g++ and gcc?
I tried to create a makefile for a project that use c++ and c. I need to compile those file in order to make de .o file, but when I compile using make I have circular dependency that is dropped. I don't know why this error occurs as I tried to separate the building of .o files that comes from .c and .o files that comes...
The rules you wrote are %.cpp : %.o and %.c : %.o. You wrote those rules the wrong way around. The target being built must be to the left of the colon, and the things it depends on must be to the right. The error message tells you about a circular dependency because GNU Make defines an implicit rule where the depend...
72,385,584
72,385,656
C++ Linked list, program stuck when calling the next pointer in the list
I have made a linked list with c++. I have no idea when trying to point to the next element of the list, the program stops. My Node Class as follows: class Node { friend class List; private : Node* next; public: int value; Node() { value = 0; next = nullptr; } Node(int data) { this->value = data; this-...
in erase you never assign a value to 'before' Node* before; then you do before->next = ptr; Error C4703 potentially uninitialized local pointer variable 'before' used ConsoleApplication1 C:\work\ConsoleApplication1\ConsoleApplication1.cpp 124 also - more importantly your printLst function sets head t...
72,386,389
72,441,304
Does a range based for loop over an array ODR-use the array?
When a range based for loop is used to iterate over an array, without binding a reference to each element, does this constitute an ODR-use of the array? Example: struct foo { static constexpr int xs[] = { 1, 2, 3 }; }; int test(void) { int sum = 0; for (int x : foo::xs) // x is not a reference! sum...
Is the definition of foo::xs necessary? Yes, because as NathanOliver points out in the comments, a reference is implicitly bound to foo::xs by the range-based for loop. When you bind a reference to an object, the object is odr-used. The same would occur if an std::array were used rather than a raw array. What if we ...
72,386,590
72,386,897
C++ unhandled Exception while checking ARGV values
Can someone tell me why this code worked 10 minutes ago but keeps failing now? I keep getting unhandled exception error. In the debug menu I am entering 32 and 12.5. The code fails each time I try to check i > 0; bool CheckArgInputs(char* inputs[], int numInputs) { const char validChars[] = ".,+-eE0123456789"; ...
Your CheckArgInputs() function is coded to act like it is being given a pointer to an individual string, but main() is actually giving it a pointer to a pointer to a string. And then the function is not coded correctly to iterate the individual characters of just that string, it is actually iterating through the argv[]...
72,387,132
72,387,238
How to use void parameter when using template in C++
I want to make a function to test the running time of the incoming function. I use templates to make it applicable to many functions. I omitted the code for counting time. like this: template<typename F> void get_run_time(F func) { //time start func; //time end } But if a function I pass in is void, an error will be ...
First, you need to call the passed function to actually time its execution. Note, in your code you do not call it, using the () call operator: template <typename Func> void timer1 (Func func) { // start timer func(); // stop timer } Second, note these nuances: // Will take the same time as the timer1 temp...
72,387,375
72,387,391
Error array bound is not an integer constant before ']' token
What am I doing wrong in this? Error array bound is not an integer constant before ']' token using namespace std; bool cars_present[20]; int count = 0; void sortArrayIntegers(int IDs[count]); struct date { int day, month, year; }; struct car { int ID; char owner_name[20], owner_surname[20], make[20], mod...
void sortArrayIntegers(int IDs[count]); Please try changing this line to void sortArrayIntegers(int IDs[]); You dont need to provide a value here
72,387,756
72,388,139
supply custom hashing/equal func to unordered_map
I have this following code: typedef std::size_t (*hash_func)(const sp_movie& movie); typedef bool (*equal_func)(const sp_movie& m1,const sp_movie& m2); typedef std::unordered_map<sp_movie, double, hash_func, equal_func> rank_map; These are my actual functions I want to use in my unordered_map: std::size_t sp_movie_ha...
The only suitable constructor is the one that also accepts bucket_count. Passing 0 seems to work: rank_map check(0, sp_movie_hash, sp_movie_equal); However, if you don't want to select the hash/equality functions at runtime, you should make them into functors (default-constructible classes). If you don't want to write...
72,387,774
72,388,169
Strange behavior about WEXITSTATUS with `G++ 4.9.4`
This code snippet below does compiles, #include<sys/types.h> #include<sys/wait.h> #include<iostream> int main() { int ret = 0xFFFF; std::cout << WEXITSTATUS(ret); } whereas this code snippet does not compile indeed with G++ 4.9.4: #include<sys/types.h> #include<sys/wait.h> #include<iostream> int main() { ...
The WEXITSTATUS macro is a matter of the C standard library implementation, not the compiler per se. Typically (and in the case of GCC) the compiler doesn't supply the C standard library implementation. It is an independent package. Most Linux distributions, including Ubuntu, use glibc as C standard library implementat...
72,387,925
72,387,973
How to use an abstract class as the type of the index variable of a for each loop?
I was translating a Java program of mine to C++. I got to a problem trying to use polymorphism the same way as in Java. My code looks something like this: class Base { public: virtual void print() = 0; }; class Derived_1 : public Base { public: void print() { std::cout << "1" << std::endl; } }...
Coming from java to c++, there are a lot to take-care; Especially memory management! In your first shown case, you are slicing the objects. See What is object slicing? In order to access the virtual functions, you should have used std::vector<Base*> (i.e. vector of pointer to Base), or std::vector<std::unique_ptr<Base>...
72,388,684
72,390,558
Find the missing numbers in the given array
Implement a function which takes an array of numbers from 1 to 10 and returns the numbers from 1 to 10 which are missing. examples input: [5,2,6] output: [1,3,4,7,8,9,10] C++ program for the above approach: #include <bits/stdc++.h> using namespace std; // Function to find the missing elements void printMissing...
By this approach we are using space to reduce execution time. Here the time complexity is O(N) where N is the no of elements given in the array and space complexity is O(1) i.e 10' . #include<iostream> void printMissingElements(int arr[], int n){ // Using 1D dp to solve this int dp[11] = {0}; for...
72,388,932
72,389,046
Why does printf output characters instead of data?
Why does printf output characters instead of data? Looking at the code, you can relatively understand what I want to do, but it is unclear why the output is like this #include <vector> #include <string> #include <cstdio> class Person { public: Person(const std::string& name, uint16_t old) : m_Name(name) ...
Using printf() with "%s" requires a (const) char* (or something that decays into a (const) char*, like (const) char[]). std::string has a c_str() method which returns a char const* that you can pass to printf(). Therefore, your printf() line should be: printf("Name: %s Old: %hu\n", person[i].GetName().c_str(), person[i...
72,389,210
72,389,267
I want to print all the data in the text file into the edit controller
I can take the text file string with "fgets" and print it out one line using "SetWindowTextA". Like This code FILE *p_file = fopen("Test.txt", "r"); if (p_file != NULL) { text = fgets(temp, sizeof(temp), p_file); m_Edit_load.SetWindowTextA(text); fclose(p_file) } But I want to print out all the lines. I've used ...
Problem here is, SetWindowTextA is setting text, not appending. Hence, your window might be ending up with last line. To remove this problem, first create a dynamic array, append all characters, then call SetWindowTextA at last.
72,389,382
72,389,668
Binary representation of a number, why so
int DecimalToBinary (int number){ int binary = 0, remainder = 0, i = 1; while (number != 0){ remainder = number % 2; number /= 2; binary += remainder * i; i *= 10; } return binary; } There is a function that represents numbers from decimal to binary. With...
Although comments have already explained the answer. Consider the following number i.e. abcd. This number can also be represented as a*1000+b*100+c*10+d. This is the only purpose of line binary += remainder * i; and after every iteration we are multiplying i by 10 to increase the multiple. Hope it answered your query.
72,389,788
72,389,930
Why can an array of char be a template parameter but a const char* can't
I'm trying to pass a literal string as a template parameter in a C++14 project. Google told me that I can do as below: struct Test { static const char teststr[]; template<const char* str> void p() {std::cout << str;} }; const char Test::teststr[] = "Hello world!"; int main() { Test t; t.p<Test::t...
The error message from the compiler is clear enough: error: 'Test::teststr' is not a valid template argument because 'Test::teststr' is a variable, not the address of a variable So you need: #include <iostream> struct Test { static const char* teststr; template<const char **str> void p() {std::cout << *...
72,390,142
72,393,426
What happens if two distinct processes use mmap to map the same region of file (one with MAP_SHARED, another with MAP_PRIVATE)?
Can two distinct(not parent/child) processes use mmap to map the same region of file, the process A with flag MAP_SHARED, the process B with MAP_PRIVATE)? If process A changes something in the region, can the process B see it?
Then A gets the file mapped and B gets the file mapped but any writes will not be written back to the file. From the manpage: It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.
72,390,151
72,390,819
How to use a 2d texture array in opengl
I am trying to load textures into a 2d array and than apply them. But the screen only shows Black. This is my code. Creating Textures. void int loadTexture(char const* path) { glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &textureID); int width, height, nrComponents; unsigned char* data1 = stbi_load("C:\\Tem...
The 5th argument of glTextureSubImage3D is the zoffset. This is 0 for the 1st texture and 1 for the 2nd texture. The 2nd argument is the level not the number of levels: glTextureSubImage3D(textureID, 1 , 0 , 0 , 1 , width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data1); glTextureSubImage3D(textureID, 1 , 0, 0, 2, width, h...
72,390,543
72,484,394
Error C7626: Unnamed class used in typedef name cannot declare members other than non-static data members,
I am using C++ in VS2022 to build a project. I have to include a header file from an sdk named eve.h. I have added the include folder holding this file into the project properties. However, when I build this project, I get a number of C7626 errors stating the following, and pointing to certain lines of the eve.h file. ...
I solved this problem by giving the structures in the sdk names. As follows: Before: typedef struct { int isOpen; int clearAll; int clearSome; int buttonFifty = -1; int buttonTwenty = -1; } After: typedef struct a { int isOpen; int clearAll; int clearSome; int buttonFifty = -1; ...
72,391,023
72,391,144
istringstream skip next (n) word(s)
Is there a propper way in an isstrinstream to skip/ ignore the next, or even the next n words? The possibility to read n times a variable seems to work, but is very clunky: for (int i = 0; i < n; ++i) { std::string tmp; some_stream >> tmp; } std::istream::ignore doesn't seem to do the job, as only n letters a...
It's clunky because it's not common enough to have gotten the appropriate attention to get a standard algorithm in place. { std::string tmp; for(size_t i = 0; i < number_of_words_to_skip; ++i) some_stream >> tmp; } You can make it fancier by creating a null receiver: std::copy_n(std::istream_iterator<std::stri...
72,391,384
72,391,546
Template parameter type `void` vs explicit use of `void`
In the following code why does the explicit expansion of template function foo fail to compile, yet the expansion of bar compiles successfully ? Live link - https://godbolt.org/z/o8Ea49KEb template <typename T1, typename T2> T1 foo(T2) { T2(42); return T1{}; }; template <typename T1, typename T2> T1 bar(void) { T2(42...
The rule saying a parameter list (void) is the same as the empty parameter list () is found in C++ Standard [dcl.fct]/4: A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list. Except for this special case, a parameter shall not have type cv void. ...
72,392,699
72,398,871
How to call a parameterless function using boost::json::value
I'm modifying from here code: #include <boost/describe.hpp> #include <boost/mp11.hpp> #include <boost/json.hpp> #include <boost/type_traits.hpp> #include <boost/utility/string_view.hpp> #include <stdexcept> #include <string> #include<iostream> template<class C1, class C2, class R, class... A, std::size_t... I> boost::j...
The arguments are required to be passed as a JSON array. The simplest way to to fullfill the requirement is: std::cout << call(obj, "foobar", boost::json::array{}) << std::endl; See it Live On Coliru #include <boost/describe.hpp> #include <boost/json.hpp> #include <boost/json/src.hpp> // for Coliru #include <boost/mp1...
72,392,738
72,393,748
Any way to create an anonymous reference container in C++?
In python, we can simply using such code: a = [1,2,3] b = [4,5,6] for m in [a, b]: for e in m: print(e) "[a, b]" is an "anonymous" container which contains the "reference" of a and b, during the traverse, none of additional list is created so that the traverse is very effective. Is there any way to do the ...
Not sure what C++ you're on. C++17 onwards it can be done like this: #include <vector> #include <functional> #include <iostream> int main(int, char*[]) { std::vector a{1,2,3}; std::vector b{3,4,5}; for ( auto&& v : std::vector{std::ref(a), std::ref(b)}) { for (int& el : v.get()) { ...
72,393,020
72,393,091
How to split a path to subpaths and store it in std::vector?
My question is how could I split my main path into several separate sub-paths and store it in a vector or list? Example I have path for example: Assets/A/B/C And I need to break them into separate sub-paths (or just strings): Assets A B C And then stores it in std::vector. The last part i know how to do just push_bac...
A std::filesystem::path is iterable, so you can simply write: for(auto p:path) vector.push_back(p.string()); Or even shorter: std::vector(path.begin(),path.end()); If you do not need strings, but a vector of subpaths is also accaptable.
72,393,147
72,401,259
Nested ListView in Qml
I am trying to achieve this output [Refer snapshot : click here] I tried Using, since I am new to Qt not sure whether my approach of using repeater is right or wrong. ListView { id: outer model: model1 delegate: model2 anchors.fill: parent } Component { id: model1 Item { Column{ Repeater { ...
I have found the solution to my problem. Obtained output click here Rectangle { width: 360 height: 360 ListView { id: outer model: 4 delegate: Rectangle { id: rect color: listColor[index] width: 60 implicitHeight: ...
72,393,507
72,442,074
Determine number of AVX-512 FMA units
Is there a possibility to determine the number of AVX-512 FMA units during runtime using C++? I already have codes to determine if a CPU is capable of AVX-512, but I cannot determine the number of FMA units.
The Intel® 64 and IA-32 Architectures Optimization Reference Manual, February 2022, Chapter 18.21 titled: Servers with a Single FMA Unit contains assembly language source code that identifies the number of AVX-512 FMA Units per core in an AVX-512 capable processor. See Example 18-25. This works by comparing the timing ...
72,393,594
72,402,065
How to set app icon for linux revisited and how does xfreerdp do it
I discovered that my appimag-ed application does not show any app icon in the window manager when launched, even though it has the icon inside itself. By the way, e.g., Obsidian app does suffer from this problem. In general, from searching on the Web, it looks like appimage fails with icons. Here e.g., a person also an...
Here is an incomplete answer, since it only cover the X11 case and does not describe how to translate from QT object to X11 handles. I don't even know if this method will solve your specific problem. The idea is to talk directly with X server to set the window icon, here, using the XCB API (same thing can be achieved u...
72,393,901
72,394,038
Passing 2D array as class parameter
I am trying to set up a class that initializes with a 2d array of an unknown size at compile time. I figured the best way to do this would be to pass the array as a pointer. This works as expected with a 1d array, but when I try to do the same with a 2d array. I get an error that states that it cannot convert argument...
You can pass a 2D array by passing the address of the first element: TestClass Test("TestName", &TestArray[0][0]); But how is TestClass supposed to know the dimensions of the array? There is no way to query the data or to guess. You have to also pass num_rows and num_cols. But then I see: std::cout << Test.data[2] << ...
72,394,010
72,394,688
How to choose an operator when making a simple calculator in C++?
I'm making a simple calculator in C++, but I'm having trouble choosing an operator, I wonder who can help me? I'm using this code: include <iostream> using namespace std; int main() { string operation = ""; cout << "enter operation:"; if(operation = "/"){ int x; cin >> x; int y; cin >> y; int sum = x / y; } if(o...
I think you're missing a line to read in the operation the user enters. After the line cout << "enter operation:";, you probably need cin >> operation. A couple of other code improvements worth doing: consider moving setting X and y outside the if statements, as you repeat the same code 4 times consider using a switch...
72,394,948
72,395,509
Use of operator()() without parentheses?
The following code is a dumbed down version of a wrapper around an object. I would like to be able to access the underlying Object seamlessly, that is, without the need for parentheses, as the comments describe: struct A { void Func() {} }; template <typename Object> struct ObjectWrapper { ObjectWrapper(Object& o...
I think you need overload operator -> and/or * (this is how smart pointers are done): template <typename Object> struct ObjectWrapper { ObjectWrapper(Object& o) : object_(&o) { LOG(); } Object* operator->() const { LOG(); return object_; } Object& operator*(...
72,395,229
72,395,816
Trying to add an element to a dynamic array
i've tried to add an element from class type to an empty dynamic array, but nothing happens, nor it changes the counter after adding one element. This is the function void Bank::addCustomer(const Customer& newCustomer) { Customer* temp = new Customer[getCustomerCount()+1]; for (int i = 0; i < getCustomerCoun...
Your loop is exceeding the bounds of the old array if it is not empty. And your assignment of the newCustomer is exceeding the bounds of the new array. Try this instead: void Bank::addCustomer(const Customer& newCustomer) { int count = getCustomerCount(); Customer* temp = new Customer[count + 1]; for (in...
72,395,266
72,395,390
C++ Impossible nullptr call mystery
So I decided to get rid of singletons in my project and introduce dependency injection. I did all the necessary changes, and I got a little problem: no matter what I did, my NetworkService was called anyway, regardless of the fact it was initialised to nullptr. I started to investigate, and I got an impossible scenario...
Even If I try to dereference it on purpose, it DOES succeed. No, the program has undefined behavior meaning it is still in error even if it doesn't say so explicitly and "seems to be working". This is due to the use of -> for dereferencing in your program. Undefined behavior means anything1 can happen including but ...
72,395,426
72,395,635
tbb::parallel_invoke excuting the functions only once
So I started learning TBB just today. I'm working on Ubuntu system, so installed TBB using sudo apt sudo apt-get install libtbb-dev now I'm trying to compile and run HELLO_TBB #include <iostream> #include <tbb/tbb.h> int main() { tbb::parallel_invoke( []() { std::cout << " Hello " << std::endl; }, []() { st...
Regarding the output: tbb::parallel_invoke is a: Function template that evaluates several functions in parallel. As you can see in the link, you can pass several functions, and the tbb framework will attempt to run them in parallel (each function in a separate thread). Each of the functions will be executed once. Not...
72,395,483
72,396,611
How should I approach parsing the network packet using C++ template?
Let's say I have an application that keeps receiving the byte stream from the socket. I have the documentation that describes what the packet looks like. For example, the total header size, and total payload size, with the data type corresponding to different byte offsets. I want to parse it as a struct. The approach I...
There are many different ways of approaching this. Here's one: Keeping in mind that reading a struct from a network stream is semantically the same thing as reading a single value, the operation should look the same in either case. Note that from what you posted, I am inferring that you will not be dealing with types w...
72,395,705
72,397,515
c++: arithmetic operator overload
I have a class called HealthPoints that has hp and max_hp members. I want to overload the + operator so it will work like this: HealthPoints healthPoints1; healthPoints1 -= 150; /* healthPoints1 now has 0 points out of 100 */ HealthPoints healthPoints2(150); healthPoints2 -= 160; /* healthPoints2 now has 0 points out o...
In this statement: healthPoints2 = healthPoints1 + 160; Your + operator is creating a new HealthPoints object that is a copy of healthPoints1, thus the object's m_maxHP is set to 100. Then you are adding 160 to that object, increasing its m_HP but preserving its m_maxHP. Then you are assigning that object to healthPoin...
72,396,340
72,396,596
OpenGL shader reader returns garbage characters
Why does this function: string Utils::readShaderFile(const char* filePath) { string content; ifstream fileStream(filePath, ios::in); string line = ""; while (!fileStream.eof()) { getline(fileStream, line); content.append(line + "\n"); } fileStream.close(); return content; }...
So, the problem was with the fact that I created my shader .glsl files with Command's Prompt echo "" >> shader.glsl, which set some weird character at the beginning of the file. After I have created the file through VS2019 add item option it worked well.
72,396,391
72,399,728
compile-time variable-length objects based on string
Related SO questions: variable size struct string-based generator Sadly neither one (or other similar ones) provide the solution I'm looking for. Background USB descriptors are (generally) byte-array structures. A "string descriptor" is defined as an array of bytes, that begins with a standard "header" of 2 bytes, fo...
Adding a CTAD to UsbDescrString should be enough template<size_t N> struct UsbDescrString final: UsbDescrStd { char str[N * 2]; constexpr UsbDescrString(const char (&s)[N+1]) noexcept : UsbDescrStd{sizeof(*this), UsbDescriptorType::USB_DESCR_STRING} , str {} { for(size_t i = 0; i < ...
72,396,857
72,396,951
Optimization for specific argument without template
I ran into some optimized code that is fast, but it makes my code ugly. A minimal example is as follows: enum class Foo : char { A = 'A', B = 'B' }; struct A_t { constexpr operator Foo() const { return Foo::A; } }; void function_v1(Foo s){ if(s == Foo::A){ //Run special version of the code } ...
Is there a way to write a function in the style of function_v1, but still have the compiler make different instantiations? If we expand your example a bit to better reveal the compiler's behavior: enum class Foo : char { A = 'A', B = 'B' }; struct A_t { constexpr operator Foo() const { return Foo::A; } }...
72,398,772
72,398,929
Is this quote from cppreference.com about implicit throw from a destructor a typo?
Does this quote from https://en.cppreference.com/w/cpp/language/function-try-block have a typo? Reaching the end of a catch clause for a function-try-block on a destructor also automatically rethrows the current exception as if by throw;, but a return statement is allowed. It seems hard to believe that a destructor a...
The answer is no, it is not a typo. The cppreference article did not show an example of a destructor function try block, so I crafted one myself and tested it. Below is the same code. I tested with Microsoft VS2019, using the v142 platform toolset and C++20 dialect. If you execute this, an abort will be called, which...
72,398,925
72,398,935
error: use of deleted function 'Hund4::Hund4()'
I am a newbie in C++. I wrote this code to understand the difference between public, protected and private. The problem is, when I create an object of Hund4, I get this error: use of deleted function This error is in the last line. Can you please help me to solve this problem? #include <iostream> #include <iostream> ...
The Hund class that Hund4 derives from has no default constructor, so Hund4 has no default constructor. You can construct a Hund4 from a std::string or a Hund, though: Hund4 ace4(std::string{"ace4"}); Hund4 ace4(Hund{"ace4"}); using std::literals; Hund4 ace("Waldi"s); For some reason, somebody else please explain why...
72,399,427
72,399,535
C++ Is it possible to overload a function so that its argument accept literal and reference respectively?
I'm having a problem with using C++ overloading and was wondering if anybody could help. I'm trying to overload functions so that its argument accept reference and literal respectively. For example, I want to overload func1 and func2 to func: int func1 (int literal); int func2 (int &reference); and I want to use func...
Literals and temporary values can only be passed as const references while named values will prefer a non-const reference if available. You can use this with either & or && to create the 2 overloads. For why and more details read up on rvalues, lvalues, xvalues, glvalues and prvalues. The code below shows which functio...
72,399,510
72,400,381
How to specify a default argument for a template parameter pack?
I have the following method template <std::size_t N, std::size_t... Indices> void doSomething() { ... }; It seems not possible to supply default values for Indices, e.g. template <std::size_t N, std::size_t... Indices = std::make_index_sequence<N>> void doSomething() { ... }; Compiler complains that error: ex...
There's already two excellent answers so far (including NathanOliver's comment). I think that having a couple of overloads that act as wrappers is really the simplest solution here, but just for completeness, let's provide your desired functionality in one function: Often it's best to take as much of the template logic...
72,400,779
72,400,878
Question about custom conversion of "lambda []void ()->void"
TestCase2 and TestCase3 can compile normally. However, in TestCase1 I get the following error: E0312, Custom conversion from "lambda []void ()->void" to "EventHandler" is not appropriate. Why am I getting this error? I want to know how to solve it. #include <functional> #include <iostream> class EventHandler {...
Why am I getting this error? The lambda []() {} is not the same as std::function<void()>. That means decltype([]() {}) != std::function<void()> and it has to be implicitly or explicitly converted. At the line EventHandler TestCase1 = []() {}; copy initialization take place, where compiler first has to convert the l...
72,400,955
72,400,979
Can i give a parameters on "cmd console?"
I want to utilize CMD console. For example If a.cpp is like below int main(int argc, char* argv[]) { for (int i = 0; i < argc; i++) { cout << "argv : " << argv[i] << endl; } string path = "c:\\test"; vector<fs::path> v; vector<fs::path>::iterator it; for (auto& entry : fs::recurs...
You can do this portably since C++17 using #include <filesystem> std::filesystem::current_path(std::filesystem::path(path));
72,401,100
72,401,254
Trying to understand why my C++ program is slowing down after running for long time
None of the threads close to the topic that I could find (like this one) helped me so far. I have a C++ program that reads some data from a file, runs pretty complex and intensive operations and then writes outputs to new files. When I let the process run for few hours, here are the behaviours that I noticed: The CPU ...
I suspected memory leaking, but then wouldn't the RAM keep increasing indefinitely? It is increasing indefinitely, you just don't see it in the RAM usage statistics that you are looking at. What happens is that the OS will keep allocating new physical RAM pages up until the observed ceiling point. At that point whene...
72,401,352
72,401,620
How to draw grid line only in a circle using QGraphicsItem
Please forgive the poor English in advance. hello! I am currently implementing view widget using QGraphicsView & QGraphicsItem. Is there any way to draw gridlines only inside a circle? Rectangles are fine, but trying to draw them inside a circle is a pain. Below is sample code. for(int x = rect.left(); x <= rect.ri...
It's just a matter of tigronometry calculation. From the position on the X or Y axis you can calculate the angle to go to the point on the circle using arc sin and arc cosine. The code below should work #include <math.h> class Point { public: double X = 0.0; double Y = 0.0; }; int main() { double radius ...
72,401,947
72,402,076
Can std::future cause coredump without get or wait
void func() { std::future<int> fut = std::async(std::launch::async, []{ std::this_thread::sleep_for(std::chrono::seconds(10)); return 8; }); return; } Let's say that I have such a function. An object fut of std::future<int> is initialized with a std::async job, which will return an integer...
Futures created with std::async have a blocking destructor that waits for the task to finish. Even if you instead create a future from std::promise, the docs for ~future() don't mention the problem you're asking about. The docs use the term "shared state" a lot, implying that a promise and a future share a (heap-alloca...
72,402,850
72,403,015
If I declare the 'val' variable inside the loop then the code is not showing the desired output but when i put it outside loop it works fine. Reason?
In the below code, If I declare the variable val inside the loop then the code is not showing the desired output but when I put it outside the loop it works fine. What can be the Reason? #include <iostream> using namespace std; int main(){ int n ; cin>>n ; int row=1; char val = 'A'; while(row...
Your variable gets recreated in every iteration for while loop. The scope of the variable is local inside the loop so whenever another iteration starts it creates a new copy. In your case, if you put variable val inside the loop, it will be getting recreated with A as its value every time. But in global scope it only g...
72,403,492
72,403,609
Why passing a string literal to a template calling std::format fails to compile?
The following code snippet fails to compile on the latest version of MSVC (Visual Studio 2022 17.2.2). The same snippet seemed to work just fine on previous compiler versions. #include <iostream> #include <format> template <typename First, typename... Args> inline auto format1(First&& first, Args&&... args) -> decltyp...
After P2216, std::format requires that the format string must be a core constant expression. In your case, the compilation fails because the function argument First is not a constant expression. The workaround is to use std::vformat, which works for runtime format strings template<typename First, typename... Args> auto...
72,403,729
72,403,924
Why text.size() returns std::size_t and not std::string::size_type
I am studying c++ and currently reading C++ Primer (5th ed). I am on the topic about std::string. The size member returns the length of the string. The book says (p. 88) auto len = line.size(); // len has type string::size_type But Visual Studio Code identifies len as having the type std::size_t. Why is it different?
identifies len as having the type std::size_t. Why is it different? From microsoft's basic_string documentation: typedef typename allocator_type::size_type size_type; Remarks it's equivalent to allocator_type::size_type. For type string, it's equivalent to size_t. (emphasis mine) Thus, as can be seen from the abov...
72,403,979
72,404,277
Writing a clock(loop) that is triggered in the mhz consistently and effeciently for an emulator in modern C++
I'm currently developing an emulator for an old CPU (intel 8085). Said CPU clock is 3.2mhz. I'm trying to be as accurate as possible, and as cross-platform as possible To me, that means I need a clock that gets called with a frequency of 3.2mhz. I don't care about it being too accurate, anything within 10% accuracy is ...
The important thing to recognize is that nobody can notice if some things happen at the wrong time. You have a CPU talking to some peripherals. Let's say the peripherals are GPIO pins. As long as the CPU turns the GPIO pins on and off at the right time, nobody can actually notice if the CPU is running too quickly in be...
72,404,136
72,405,335
Read vector from file
I have a large vector of length 650 million. I wish to store this vector on disk (5 GB), then load the entire vector into memory so that various functions can quickly access its elements. Here is my attempt to do this in Rcpp on a smaller scale. The following code simply causes my R session to crash, with no error mess...
Over the years I have implemented something like the above a few times for quick and dirty data story. These days I no longer recommend it as we have fabulous packages such as fst and qs who do this better, with parallelisation, and compression, and other whistles. But as you asked, an answer follows. I have found the...
72,404,916
72,411,340
Reacting to each tick events from the websocket
I would like to design my trading system reacting to each tick events from the websocket stream i subscribed to. So basically i have two options : void WebsocketClient::on_write(beast::error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); ws_.as...
There would be no tangible difference, unless // signal generation and sending http request to place new orders here // first before calling async_read() below either takes significant amount of time (design smell on IO threads) exits the function by return/exception That's because async_read by definition always re...
72,404,944
72,409,615
C++ exit code 3221225725, Karatsuba multiplication recursive algorithm
The Karatsuba multiplication algorithm implementation does not output any result and exits with code=3221225725. Here is the message displayed on the terminal: [Running] cd "d:\algorithms_cpp\" && g++ karatsube_mul.cpp -o karatsube_mul && "d:\algorithms_cpp\"karatsube_mul [Done] exited with code=3221225725 in 1.941 se...
There are several issues: The exception you got is caused by infinite recursion at this call: kara_mul(a + b, c + d) As these variables are strings, the + is a string concatenation. This means these arguments evaluate to n and m, which were the arguments to the current execution of the function. The correct algorithm...
72,405,012
72,405,396
Is it safe to pass this pointer in the initializer list in C++?
Edit: Code compiling now. Also added more detailed code to depict exact scenario. Is it safe to pass this pointer in the initializer list ? Are there any chances of segmentation fault in case object methods are called before object is constructed? Or better to pass this pointer in constructor ? following are the exampl...
If the first variable, in ThirdClass's constructor is not used, only stored for future use, then this is safe and well defined. If you attempt to use/dereference the pointer in the constructor, then it would be undefined behaviour, since the FirstClass object has not been constructed yet. In your example, you wrote: r...
72,405,122
72,405,619
Creating an Iterator with C++20 Concepts for custom container
C++20 introduces concepts, a smart way to put constraints on the types a template function or class can take in. While iterator categories and properties remain the same, what changes is how you enforce them: with tags until C++17, with concepts since C++20. For example, instead of the std::forward_iterator_tag tag yo...
By and large, the C++20 way of defining iterators does away with explicitly tagging the type, and instead relies on concepts to just check that a given type happens to respect the iterator category's requirements. This means that you can now safely duck-type your way to victory while supporting clean overload resolutio...
72,405,350
72,405,537
Error while printing structure array contents
Below code is not printing after 1st element of array. After printing first structure content the subsequent values are containing garbage values #include <iostream> using namespace std; #define SMALL_STRING_LEN 20 #define TINY_STRING_LEN 10 enum data_item_type_t { TYPE_FLOAT, TYPE_INT, TYPE_UINT }; enu...
I think there is problem while calculating the ptrTemp value. You presume right: your pointer arithmetic is incorrect: to get a pointer to the i-th entry, just use: ptrTemp = ptrLocal + i; or ptrTemp = &ptrLocal[i];
72,405,712
72,414,275
Unreal Engine 5 - C++ Classes disappear after exiting the editor
Whenever I exit the Unreal Engine 5 editor, I've noticed that when I open it up again, my various C++ classes disappear. Fortunately, all I have to do is re-compile and they will be added back in again. However, it does become a serious inconvenience since I will have to re-attach it to any actors it was a component of...
I managed to find out that this is a rather common bug with live coding. Fortunately, the Unreal Engine course I've been taking actually has a video earlier in the course catalog that deals with this, and I can report that the solution provided worked for me. Close the editor immediately but leave the IDE open. Build ...
72,406,065
72,406,332
Counter and ID attribute of class stored in vector
I have a dilemma regarding my removing database function code. Whenever I remove the database in vector with unique, I cannot think of writing the code that could fill the gap with the removed number (like I removed database ID3 and I want that the IDs of further databases would increment to have a stable sequence, so ...
The thing you're doing here is called a design anti-pattern: Some structural idea that you could easily come up with in a lot of situations, but that's going to be a lot of trouble (i.e., bad). It's called a singleton: You're assuming there's only ever going to be one DbMain, so you store the length of that in a "globa...
72,406,475
72,406,610
'cd ..' is not working in system("") in c++ code running in ubantu environment
Currently I am in test directory and I am trying to change directory from test to src and run another .so file below is the code system("cd .."); system("cd src"); system("./shapessenderros2"); folder structure is test and src folders are in same directory
Each system call creates a new sub shell and whatever you do to the envionment of such a shell will not affect any other sibling shells. Each process inherits the environment from the parent process. You could get around the problem by running all the commands in the same shell: system("cd ../src;./shapessenderros2"); ...
72,406,614
72,406,718
Passing the address of an array into a function in C++
I'm new to c++ and I am confused by the idea of passing a pointer array into a function. Here's the function void func(int *a){ a[0]=999;} which is used by the main int main() { int a[5]={1,2,3,4,5}; func(a); std::cout << a[0]<< std::endl; } I understand this works perfectly as the name of an array is jus...
Case 1 I understand this works perfectly as the name of an array is just the address of its first element. The above statement is not technically correct. The first example worked because in many contexts(including when passing an array as an argument by value to a function) the array decays to a pointer to its first...
72,406,830
72,407,185
How to correctly forward and use a nested tuple of constexpr struct with standard tuple operations
I want to store passed data via constexpr constructor of a struct, and store the data in a std::tuple, to perform various TMP / compile time operations. Implementation template <typename... _Ts> struct myInitializer { std::tuple<_Ts...> init_data; constexpr myInitializer(_Ts&&... _Vs) : init_data{ std...
In addition of the forwarding problem denoted by Barry, there's a different reason why you cannot have constexpr on init. This is because you contain a reference to a temporary inside data_of_t. You see, you are containing a type obtained from overload resolution from a forwarding reference: template<typename T, typena...