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
74,402,231
74,402,348
summation of elements of a 2D vector into a 1D vector. C++
Help me please. Tell me how to sum each vector in a two-dimensional vector and write the result into a one-dimensional vector. On C++. Input: std::vector<std::vector<double>> a = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; Required Output: b = { 9, 12 } I found how to sum all the elements in a 2D vector, but I don't know how ...
From your example I assume that in the sums vector that you require, element in index i, is the sum of all elements in index i in the vectors in a. This requires that all elements in a have the same size. You can do it in the following way: Traverse the elements in a. For each element: traverse the element (which is a...
74,402,911
74,402,978
error use of deleted function when trying to pass rvalue to a tuple
Original context: I am trying to pass a tuple of (object, expected_value_of_some_property) to a test function I created a simple class to reproduce the error I am facing: template <typename T> class Vector { private: size_t m_size; std::unique_ptr<std::vector<int>> m_vector; public: Vector(); Vector(co...
Since your Vector class has a unique_ptr member, that means your class itself has the copy-assignment implicitly deleted. Therefore this assignment will fail std::tuple<Vector<int>, int> vector_test; vector_test = std::make_tuple(Vector<int>{}, 0); // <--- this Instead you can just directly initialize in one step st...
74,403,740
74,403,788
How to accept empty input in C++
Accepting user empty input and passing default value from the constructor I just start learning C++. Now I was trying creating a simple requestion header. What I was expected is the "ABC Industries" should be used as a default value for the purchaser name and "XYZ Supplier" should be used as a default for the vendor na...
cin into a string will read, effectively, one token. The exact rules are complicated, but it basically pulls content until a space or newline. If you don't input any content, it waits until there's something. You're looking for getline, which reads until the next newline and returns whatever it finds, even if what it f...
74,403,780
74,404,368
Reading from file with special characters into a string
I have an c++ program that should read a text from a file named "Pontaje.txt" and store it into a string. The problem is that in that file is an special character and the program can't use it properly. Pontaje.txt [604] Dumy | 17501 — Today at 12:01 AM Note that "—"(is a special character) is not "-"(from the keyboard...
ΓÇö is a tell-tale sign: it's three characters instead of one. That happens when the input is encoded using UTF-8 (a multi-byte character set) but the output is done with a single-byte character set. I can't directly eyeball what character set contains all of ΓÇö, though. IOW the problem is not the input or the output,...
74,403,792
74,403,839
Code::Blocks builder error: undefined reference to `WinMain'
How to fix the following error message when trying to compile C++ console application project on Code::Blocks? undefined reference to `WinMain' All other questions on Stack Overflow are about "WinMain@16", which is not the case here.
WinMain is linked to in windows when you want to create a windows application. https://learn.microsoft.com/en-us/windows/win32/learnwin32/winmain--the-application-entry-point For the complier to look for the main function you will have to change at the linker stage that it is a console application and not a windowed on...
74,403,919
74,404,000
C++ - issues with writing sorting function
I have a problem with sorting function. I have following struct: struct Object { int value, height; Object(int v, int h) { this->value = v; this->height = h; } }; I am storing vector of this objects: std::vector<Object> v And I'd like to sort it such that if the height is greater than some ...
It seems you want something like: std::sort(v.begin(), v.end(), [ & ](const Object& lhs, const Object& rhs) { return std::make_pair(lhs.height > i, rhs.value) < std::make_pair(rhs.height > i, lhs.value); });
74,404,106
74,404,685
pointer to pointer of vector yields 3D vector?
I have been looking through some legacy code and found this little snippet: std::vector<int>** grid = new std::vector<int>*[10]; for (int k = 0; k < 10; k++) grid[k] = new std::vector<int>[10]; And then later on, the original developer is calling this command here: grid [i][j].push_back(temp); I was under the im...
grid[i][j] is a reference to a std::vector<int>. Rewriting things may clarify what you have. [Demo] #include <fmt/ranges.h> #include <vector> int main() { using line_t = std::vector<int>; // line is a vector of ints using matrix_t = line_t*; // matrix is an array of lines using grid_t = matrix_t*; // gr...
74,404,314
74,404,846
Is there a way to express fraction in MOSEK c++?
I am trying to make objective function by MOSEK c++. But there is a problem. When I try to make function like below, there is no dividing function in MOSEK. a is variable and b,c are parameter. I made a (numerator) and b+ac (denominator) respectivley, but I don't know how to divide them. So I made code like below. Va...
You are using Fusion which means you have to state the problem in conic form. You can read about that in https://docs.mosek.com/modeling-cookbook/index.html But I suggest you first consider whether the function a/(b+a*c) is convex. (I kind of doubt that.) If it is not convex, there is no hope to express it in conic for...
74,404,545
74,404,599
I don't understand the logic of a working program class
All, being brief as possible, I’m working on an exercise from C++ Primer Plus Sixth Ed. by Stephen Prata. Chapt 10 Ex 6 for those playing along at home. I wasn’t sure what the exercise was asking. I found someone online who had done the exercises. I thought seeing the program in action, I’d understand the requirement ...
How does the constructor of move4 know to extract the x and y from newMove of class move2. Your class does not explicitly define or delete its copy constructor, and all of its fields can be copied, so you get a copy constructor for free. Effectively, you get a constructor that does Move(const Move& that) : x(that.x),...
74,404,977
74,405,543
Why wouldn't a C++ compiler implement <cstdint>?
I am porting some C++ code to SHArC processor, and I noticed the SHArC C++ compiler doesn't implement <cstdint>. What's the reason for this, and how do I port numerous #include <cstdint> from the original code?
There's nothing tricky about <cstdint>, a valid version is as follows: #pragma once /* or include-guard macro */ #include <stdint.h> namespace std { typedef ::uint64_t uint64_t; typedef ::uint64_fast_t uint64_fast_t; typedef ::uint64_least_t uint64_least_t; typedef ::int64_t int64_t; /* similar f...
74,405,029
74,405,995
How to use RtAudio as a CMake dependency
I am trying to use RtAudio in my project. I installed it by executing : git clone ... cmake -B target -D CMAKE_PREFIX_PATH=$HOME/.local cmake --build target cmake --install target PKG_CONFIG_PATH=$HOME/.local/lib/pkgconfig pkg-config --cflags --libs rtaudio returns -pthread -I$HOME/.local/include/rtaudio -D__UNIX_JAC...
The call find_package(RtAudio) actually creates the IMPORTED target RtAudio::rtaudio, so you could simply link with that target: find_package(RtAudio REQUIRED) ... target_link_libraries(${PROJECT_NAME} RtAudio::rtaudio) Not sure why they don't mention that in their documentation. Alternatively, it is possible to us...
74,405,108
74,405,208
Compile-time check for existence of a template specialization of a function using C++20 requires expression
I am developing a sort of event system where the event listeners are determined at compile-time. To achieve this, I need a function which can tell me whether the parameter class T implements a specific specialization of the OnEvent() function. My current attempt uses a C++20 requires expression: template<class T> class...
There is no reason to require OnEvent to be implemented as a template. This feels like being overly-controlling of the user's code. Concepts are not for telling the user how exactly to implement something. You are going to call an interface in a certain way, and users should implement their code such that that call syn...
74,405,116
74,405,196
Method of referencing each row of 2d array with for loop in C++
I was practicing array problems and I stuck by this one: Given a declaration of 2D array: int a[][2] = { {2,2}, {3,3}, {4,4} }; write a nested for loop to print all the values of a. First, since 2D array is an array of rows (means each element of this array is a row vector), I tried a for loop like this: for (int& x[]...
In for (int& x[] : a) x is an array of references. Arrays of references are not legal C++. The type is int[2]. You can avoid auto by writing for (int (&x)[2] : a). The extra parentheses around &x are crucial, without the parens you have an array of references (not legal), with the parens you have a reference to an a...
74,405,122
74,442,398
Factory method pattern with multiple constructors having various sets of arguments
I am trying to make a factory function that will be able to create objects derived from a base class using different constructors based on the given parameters. With some help from other posts here I have been able to make an example that works for a constructor that takes no parameters, but I cannot find a solution fo...
Inspired by the answer by @numzero, I finally adopted a solution that uses less magic/templates and thus it looks more elegant to me. This solution works for constructors having fields of complex types, on the other hand it is limited by a requirement of all BaseObject descendants to have the same set of constructors (...
74,405,184
74,405,262
C++ error: expression cannot be used as a function (find_if)
The essence of the program: get a map, where the values are char from the passed string, and the key is the number of these values in the string using namespace std; map<char, int> is_merge(const string& s) { map<char, int> sCount {}; for (auto lp : s) { if (find_if(sCount.begin(), sCount.end(), lp) !=...
std::find_if takes a predicate not a value. Hence the error that lp is not a callable. To find a key in a map you should use std::map::find because it is O(logn) compared to O(n) for std::find/std::find_if (as a rule of thumb you can remember: If a container has a member function that does the same as a generic algorit...
74,405,519
74,405,675
Is there a way to assign a templated type to a defined class structure?
I am trying to create a simple binary tree capable of holding data of multiple types. The binary tree will be hard coded with data (compile time could work for this). Here is my code: class BTree { template <typename T> struct Node { Node* left_ = nullptr; Node* right_ = nullptr; T data_; explicit...
You can solve the immediate problem of being able to build the tree of pointers by using inheritance. struct NodeBase { NodeBase* left = nullptr; NodeBase* right = nullptr; }; template <typename T> struct Node : NodeBase { T data; explicit Node(T value) : data(value) {} }; NodeBase* root = nullptr; N...
74,406,229
74,552,824
"undeclared identifier" with MSVC++ 17.34 (VS 22) within decltype-based SFINAE expression
We are trying to update a C++17 project from VS 19 to VS 22, and all of a sudden, our code does not compile anymore. The problem in question arises in two headers of the foonathan/memory libraries, pretty far from our code. The library's own tests compile fine with VS 22. With my limited MSVC++ skill, I was unable to g...
A minimal example for the issue is (live on godbolt; thanks to Maciej Polański on whose original reproduction attempt this code is based) template <class StoragePolicy> struct allocator_storage { template <class OtherPolicy> allocator_storage( allocator_storage<OtherPolicy> const & other, decltype(n...
74,406,506
74,446,669
const and non-const parameter function overloads with a single definition
I have the following 2 function overloads: template<typename F, typename T> void func(F f, std::vector<T>& v) { ... } template<typename F, typename T> void func(F f, const std::vector<T>& v) { ... } The body of both of them is the same. Is there an easy way to define them both with a single definition to avoid code d...
I found another solution but it still adds a little bit of overhead: template<typename F, typename VecT> auto func_vec(F f, VecT& vec) { //actual code } template<typename F, typename T> auto func(F f, std::vector<T>& vec) { return func_vec(f, vec); } template<typename F, typename T> auto func(F f, const std::vector...
74,406,743
74,408,766
how to get around const size value when initializing char arrays in c++
I am very new to C++, and for a project I am working on, I am trying to initialize a char array buffer with the following code: const int nodeCount = pList->getNumNodes(); const size_t bufferSize = sizeof(Node) * nodeCount; char buffer[bufferSize]; and gets an error saying the size must be constant. I understand that...
You can create any size buffer in heap memory at run-time char* buffer = new char[sizeof(Node) * pList->getNumNodes()];
74,407,336
74,407,937
CMake run custom command with externalproject's target
I have a subproject in my project for generating code used in the project, however i want to include it using ExternalProject so it can be built and ran regardless of the toolchain i use for the main project. It mostly works except i can't figure out how to use it in add_custom_command, since i want it to use the targe...
ExternalProject_Add will add the codegen target. However, CMake has no idea what that target is doing and what output it will provide, as that info is now hidden away in the external CMake run. So the outer CMake run has no idea about the codegen binary produced by that step and where it will be located. You need to pr...
74,407,858
74,407,967
Why is the value not transferred?
First time using GRPC. I am calling my Stat function, which should return info on a File I am interested in. When I call the Stat function from within the parent Fetch function, I get a response value of 0. Here is what my code looks like: StatusCode DFSClientNodeP1::Stat(const std::string &filename, void *file_status)...
file_status = &response; will result in the outer response to be a dangling pointer when called in Fetch since you are taking the address of a function-local variable that does no exist outside the scope of the Stat function Instead you should modify the pointer that was passed into Stat StatusCode DFSClientNodeP1::Sta...
74,407,994
74,408,067
How to transform a unix timestamp in nanoseconds to seconds without losing precision [C++ 17]
I need the unix time in nanoseconds for calculation purposes in seconds, but dont want to lose "precision". So I tried to transform the integer variable to double and expected a 128 divided by 10 to be a 12.8. But in this example I lost precision and only got 12. What am I doing wrong, or where is my understanding prob...
count returns an integral type, because std::chrono::nanoseconds::rep (the representation type) is an integral type with at least 64 bits. You can use std::chrono::duration<double>, which supports fractional seconds. No need to do the math yourself, duration_cast knows about std::chrono::duration::period.
74,408,105
74,408,286
error: cannot convert ‘int (*)[4]’ to ‘int**’ | SWAPPING ARRAYS
I am trying to write a function that swap two arrays in O(1) time complexity. However, when i try to write the function parameters, I get the error: error: cannot convert ‘int (*)[4]’ to ‘int**’ Here is my code: #include <iostream> using namespace std; void swap_array_by_ptr(int* a[], int* b[]) { int* temp = *a;...
You can not swap two arrays with O( 1 ). You need to swap each pairs of corresponding elements of two arrays. In the first program int fr[] = {1,2,3,4}; int rv[] = {4,3,2,1}; swap_array_by_ptr(&fr, &rv); the expressions &fr and &rv have type int( * )[4] while the corresponding function parameters in fact has the type...
74,408,727
74,409,005
Is there a way to store functions in a vector?
I'm attempting to create a menu system within my C++ program and I'm having trouble implementing past the initial main menu. I want to have multiple Menu objects that I pass to my function called showMenu() that calls the function that pairs with the respective menu item. Should I be storing function pointers in the ve...
You have to provide template parameters for std::function: struct Menu { vector<string> items; vector<function<void(void)>> functions; }; And than you can pass lamdas to it: Menu incomeOptions = { {"Add Income", "Edit Income"}, {[]{ addIncome(); }, []{ editIncome(); }} }; Menu expenseOptions = { {...
74,408,773
74,408,863
Can't call function from .dll created in C++
I'm able to call function from DLL created in C (.c file), but i can't do it from DLL created in C++ (.cpp file). I want to find out why it doesn't work in .cpp file. I'm trying to call function printword() from a simple DLL, created with Visual Studio 2022: // FILE: dllmain.cpp BOOL APIENTRY DllMain( HMODULE hModule,...
The exported function's name will get mangled when the DLL is compiled. You must use the mangled name in GetProcAddress() in order for it to work. For example, the mangled name in MSVC is: GetProcAddress(dll, "?printword@@YAXXZ"); Or, you could add this to the function's body to tell the compiler not to mangle it: __d...
74,409,226
74,409,261
How to restrict a class template parameter to a certain subclass?
This is what I am trying: C is a template parameter that is either SomeClass or SomeDerivedClass: class SomeClass { protected: int ProtectedBaseClassMember; virtual void SomeFunctionFromBaseClass(); }; class SomeDerivedClass : public SomeClass { }; How to restrict C to subclasses of SomeClass? template<class C> ...
This is one way to do it: template<class C> class SmuggleInBetween : public C { static_assert(std::is_base_of_v<SomeClass, C>, "C must be a descendant of SomeClass"); /* ... */ }; Of course, in general you could also use std::enable_if_v<std::is_base_of_v<SomeClass, C>, ...> if you need SFINAE; here I think st...
74,409,230
74,409,233
How can i output "\" in console. C
I want to write some symbols in the console, but I have troubles with the output of the \ character. I know it is reserved by C for formatting inside printf(), but I really want to output it. printf(" __ __ __ __ ____ \n"); printf(" ||\ /|| || // ||/\\ \n"); printf(" ||\\//|| ||// ||\// \n"); printf(" ...
Backspace is a special escape character in C/C++, so that you can type, e.g., '\n'. You can use \\ to have a \ in your string.
74,409,572
74,409,808
How do I address the screen on a linux terminal?
I am teaching myself C++ and currently run the latest Fedora. On a Windows command prompt you can address the screen location. I am led to the believe that a Linux command terminal works, effectively, like characters printed to a piece of paper. i.e. You can't go "up" from where you are. However, when you install in Li...
On a basic level, there are two things that enable these kinds of things on a Linux (or other POSIX) terminal: ASCII control characters and ANSI escape codes. For a simple progress bar, it's enough to know how wide the screen is and to have a way to get back to the beginning of the current terminal line. This can be on...
74,409,988
74,410,044
Send A Message Across The Internet Using UDP And C++
I created a simple client/server program in which the client is able to send messages to the server. This works on my local computer, and even works when running it on different computers on the same network when I modify the IP_ADDRESS in my client program to be that for the server's IP address. However, this does not...
Nowadays, with common usage of WiFi and multiple devices per location needing Internet access, most devices get their Internet access via a local network router. It is increasingly rare for a computer to be connected directly to an Internet modem anymore. As such, using a router would prevent outside clients from being...
74,410,149
74,454,452
How to procedurally generate LODs of a triangle mesh
I am looking for an algorithm that can generate level of details of a given mesh. Meshes have a vertex and index buffers. Each LOD number of vertices may be computed as following: LOD0 -> 1 / 2^0 -> 1 * <mesh_number_of_vertices> LOD1 -> 1 / 2^1 -> 1/2 * <mesh_number_of_vertices> ... LOD8 -> 1 / 2^8 -> 1 / 256 * <mesh_n...
I found that the problem is known as Mesh simplification. Here great papers about it: https://www.cs.cmu.edu/~garland/Papers/quadric2.pdf https://cragl.cs.gmu.edu/seamless/ Open source implementations can be found here: https://github.com/cnr-isti-vclab/meshlab https://github.com/cnr-isti-vclab/vcglib/
74,410,531
74,410,705
There is a list whose contents are type of vector<T>
What should I do to get any vector of the list? I use following code to do it currently: list<vector<T>> alist; list<vector<T>>::iterator iter = alist.begin(); vector<T> vec(*iter); is there any other way by which I don't need to copy the data?
If you need to access all vector of list and modify individual values, you can write as descried below. for (auto& v : alist) { for (auto& i : v) { i = 13; } }
74,410,626
74,410,650
Getting Segmentation violation signal error on copying vector elements?
I have the following code for doing a http post request. I am getting the response in const std::vector<json> value ...The below code works correctly Ttran<std::vector<Lar>> get() const { const std::vector<json> value = res["value"]; std::vector<Lar> account; for (const json &account : value) { account.push...
reserve does not resize the vector, it just pre-allocates the space so push_backs are cheap and never invalidate any iterators but they are still required. std::copy assumes (like most <algorithm>s) the output iterators are valid, i.e. point to existing location. In this case they do not. What you need is std::back_ins...
74,410,850
74,410,880
What are reasons for infinite inputs?
A lot of the times when I code lets say I have only one cin>> I run my code it compiles but I can do infinite inputs even though in my code I have one input. What is the reason for this? I checked for infinity loops found none for the specific test case I was working with. Here's the code if you want to see. #include <...
The problem lies down here, you are re-assigning values of a and b with some unassigned variables. if(b >= a){ b = mx; a = mn; } if(a > b){ a = mx; b = mn; } Rather you may want to initialize max and mn with newly assigned values a, b if(b >= a){ mx = b; mn = a; } if(a > b){ mx = a; m...
74,411,266
74,411,303
How to directly specify some values as an argument in C++ instead of specifying an array name or a pointer to an array
Can I write a function in C++ to accept an array of values like this: void someFunction(/*the parameter for array*/){ //do something } someFunction({ 1, 2, 3 });
There are various ways of doing this. Method 1 Using initializer_list as parameter type. void someFunction(std::initializer_list<int> init){ } int main() { someFunction({ 1, 2, 3 }); } Method 2 Using std::vector<int> as parameter type. void someFunction(const std::vector<int> &init){ } int main() { ...
74,411,342
74,411,471
Will moving from released pointers leak memory?
I have the following code: std::unique_ptr<T> first = Get(); … T* ptr_to_class_member = GetPtr(obj); *ptr_to_class_member = std::move(*first.release()); Will this behave as expected with no copies, 1 move and without memory leak?
*ptr_to_class_member = std::move(*first.release()); just calls the move assignment operator of T with the object pointed to by first as argument. This may properly transfer some data, but delete is not called or the object so neither T::~T is executed nor does the memory of the object get freed. In the example of T = ...
74,411,495
74,411,608
My st.show on stack cannot be display for some reason
My problem on my code is when i run it, it says the error no matching function call to stack::show() which i have. i dont know whats causing the error, did some research that it should be on the public class which already there. I used switch case 1 is to input 2nd is to show or to display the user inputs which I cant ...
The error is that your show function has a parameter but when you call it there is no parameter. Seems reasonably likely that show should be written without a parameter. Like this void show() { cout<<"Stack contains --"<<endl; for (int ctr=top; ctr>=0; ctr--) { if (ctr==top) cout<<"\t\t"...
74,411,695
74,411,735
uint8_t and int8_t conversion
Consider the following program: using namespace std; int main() { uint8_t b = 150; int8_t a = -10; if (a>b){ cout << "greater" << endl; } else{ cout << "less" << endl; } return 0; } In Online C++14 Compiler it prints less. The same result I get in Compiler Explorer w...
You forgot about integral promotion. From https://en.cppreference.com/w/cpp/language/operator_arithmetic : If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promot...
74,411,804
74,411,876
How to change values of private variables for all objects from under the same class?
How to make the variable m_i have its own value for each object, and when a certain function is called, the value of m_i for all objects should be set to zero, no matter how many objects of the class CMyClass were created? #include <iostream> using namespace std; class CMyClass { public: static int m_i; }; int CMy...
Save each instance in a static list like so: #include <iostream> #include <vector> using namespace std; class CMyClass { public: CMyClass(int i): m_i{i} { instances.push_back(this); } // ~CMyClass() { // ... handle removal if nessesary. check out std::remove(...) // } int m_i = 0; ...
74,412,226
74,413,484
How throw a GCC error, if a global variable with the same name gets declared twice in a C/C++ file, but not static, extern, nor volatile?
I did run into the situation, that I declared two (separate) global variables with the same name in two separate files, but without using static, volatile nor extern on them. One file was a .c and the other a .cpp file. The compiler and build environment (GCC) was the ESP IDF and even the data types were different on t...
esp_mqtt_client_handle_t client; is a tentative definition. In spite of its name, it is not a definition, just a declaration, but it will cause a definition to be created at the end of the translation unit if there is no regular definition in the translation unit. The C standard allows C implementations to choose how t...
74,412,625
74,413,685
How to write iterator wrapper that transforms several values from base container
I have algorithm that uses iterators, but there is a problem with transforming values, when we need more than single source value. All transform iterators just get some one arg and transforms it. (see similar question from the past) Code example: template<typename ForwardIt> double some_algorithm(ForwardIt begin, Forwa...
With C++23, use std::views::pairwise. In the meantime, you can use iota_view. Here's a solution which will work with any bidirectional iterators (e.g. points could be a std::list): auto distances = std::views::iota(points.cbegin(), std::prev(points.cend())) | std::views::transform([](auto const &it) { return *std...
74,412,851
74,413,169
C++ No instance of overloaded function matches the argument list when calling std::replace()
I am doing my custom image file format to display images in CLI but i need to convert size_t to std::string: namespace csfo { class Res { public: char* BLANK_DATA = "..."; }; ... inline char* generate(int COLOR, size_t x, size_t y, bool verbose) { csfo::Res RES; ... std::string dimenssions[2] = { ...
Your error means that your compiler didn't find any matching "variant" (overloading) of std::string::replace method. To replace given text in std::string, you should: Find the text position and determine the text length. Check if found. Replace if found. E.g: #include <iostream> #include <string> //! Replaces the f...
74,412,962
74,414,303
SDL2 Window Only Shows Black Background
I'm starting a new project in SDL2 and as I'm still trying out different architectural approaches I usually start out by bringing up a white window to confirm that the new approach I'm trying out satisfies at least the bare minimum to get started with SDL2. This time, I wanted to try wrapping my application into a sepa...
SDL has both a CPU rendering API and a GPU one. Everything that works with a SDL_Renderer belongs to the GPU API. For example, you can make a SDL_Texture and use SDL_RenderCopy to render it. The final step is to call SDL_RenderPresent so that everything that was rendered gets displayed. SDL_UpdateWindowSurface is part ...
74,413,041
74,413,104
C++ raw pointers using this for operator overload results in segmentation fault when freeing memory
I am trying to build a Tree of operations for a Tensor application in c++. When I write c = a + b I would like c to have as children two pointers a and b. I pass the "this" of a to the constructor of c and then I free the memory in the destructor. template<typename T> struct ObjectPointers { const ObjectPointers<T>...
What's the problem? This is not a sound design, because it does not respect the usual properties of +, for example that (x+y)+z is the same than x+(y+z). If you nevertheless want to make it work, you'd need to extract the operator+ of the class, and use an overload of the binary operator+. In addition, you have to wo...
74,413,099
74,413,190
std::ostream operator implementation for a type
Why is the reason of almost always, declare the ostream operator as a friend function, and not as a member function or as a free function? What benefits have to choose to implement it as a friend compared with the alternatives?
A member function doesn't work here, because it requires the lhs to be of the enclosing class type, while you need it to be ostream. A free function would work, but it opens you up to some confusing overload resolution. A friend function behaves the same way regardless of whether caller is in the same namespace as the ...
74,413,185
74,413,253
How to correctly pass a function with parameters to another function?
I have the following code to demonstrate a function been called inside another function. The below code works correctly: #include <iostream> int thirds() { return 6 + 1; } template <typename T, typename B> int hello(T x, B y , int (*ptr)() ){ int first = x + 1; int second = y + 1; int third = (*pt...
If you want add to pass a value to hello, to be passed to the function given by the pointer ptr, you have to add a separate parameter. In c++ it is usually advised to use std::function instead of old c style funtion pointers. A complete example: #include <iostream> #include <functional> int thirds(int a) { retu...
74,413,819
74,448,569
In C++, how do you read a file that is embedded in an executable?
I had a photo named photo.jpg. I used xxd -i to generate a C++ file for my image file. And the output is something like this: unsigned char photo_jpg[] = {     0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01,     0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x84,...}; unsi...
At first, I converted my zip file to a string which was with this command: xxd -p archive.zip > myfile.txt Then I used this code to generate a multiline string in C++ of the hex dump of my zip file: #include <fstream> #include <string> int main() { std::ifstream input("file.txt"); std::ofstream output("string.t...
74,414,215
74,414,531
How to template creating a map for custom types
In my code I have a number of places where I need to take an std::vector of things and put it into a std::map indexed by something. For example here are two code snippets: //sample A std::map<Mode::Type, std::vector<Mode>> modesByType; for( const auto& mode : _modes ) { Mode::Type type = mode.getType();...
have a pointer to a member fn as an extra parameter template<typename T, typename V> std::map<T,std::vector<V>> getMapByType( const std::vector<V>& items, T (V::*fn)()const) { std::map<T,std::vector<V>> itemsByType; for( const auto& item : items ) { T index = (item.*fn)(); auto it = itemsByType.find( ind...
74,414,406
74,415,072
I cannot access a C++ class attribute using ctypes
I am using ctypes to develop a kind of Python API for a C++ library. So far, everything has been working fine. However, I upgraded my OS from Ubuntu 20.4 LTS to 22.04 (now with Python3.10.6 and g++ 11.3.0, but even with g++ 9.x.x, the following problem occurs). The problem I have now is that I get a core dumped error w...
Set .argtypes and .restype for the functions called by ctypes. The 64-bit pointer returned by CreateTest is being truncated due to the return value defaulting to a c_int (a 32-bit integer). Working code: test.cpp #include <stdio.h> #ifdef _WIN32 # define API __declspec(dllexport) #else # define API #endif class t...
74,414,472
74,414,505
Prevent templated class from using itself as instance
Suppose I have a class template template<class T> class Foo{}; Is it possible to prevent T from being an instantiation of Foo. That is, this should not compile: struct Bar{}; Foo<Foo<Bar>> x;
Another option: #include <type_traits> template <typename T> struct ValidFooArg; template <typename T> requires ValidFooArg<T>::value class Foo { }; template <typename T> struct ValidFooArg : std::true_type {}; template <typename T> struct ValidFooArg<Foo<T>> : std::false_type {}; int main() { Foo<int> x; // o...
74,414,632
74,414,798
How do I build a Visual Studio project from inside a C++ program, using system() to access command line?
I'm trying to make a Visual Studio project build/compilation from the command line, but from inside a C++ program. I can get this working if I use the command line directly and running the following: cd C:\Program Files (x86)\My Project Folder "C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\\IDE\devenv...
You need to make a couple of changes: Each system() call is new, so you will need to use && to do multiple commands You need to escape quotation marks with \" otherwise the quotations will be used to denote a string instead of being passed to cmd You need to use 2 backslashes in the path \\ Eg. system("cd \"C:\\Progr...
74,414,827
74,415,174
Print the largest corner element in a 2-D matrix
I am trying to write a program which prints the number of the largest corner element in 2d array.So far I have written a code, it works with many different imputs, but I'm really stuck with this one and I'm not sure how to fix it. The code: #include <iostream> #include <iomanip> #include <cmath> using namespace std; in...
I believe you don't need the whole second part of your code. I mean, assume that being a 2D array, the angles are always 4. You just load them into a vector and find the maximum element. I hope I have not misunderstood the problem. Below, find the code. #include <iostream> #include <vector> #include <algorithm> using ...
74,414,850
74,414,907
Only first UDP packet sent, then connection refused
I managed to make a reproducible example (All includes from my large original source code remain). The thing is that only the first letter a is sent. Then, I get send() failed: Connection refused. I don't know what to do, this is literally the smallest code that should work. I should say that the code does not work onl...
UDP does not provide a real reliable connection. connect just sets the destination address. A send will only put the data into the send buffer and will only fail if there was a previous error on the socket. The first send will not fail, since no previous activity was done on the socket and thus not error could have hap...
74,415,131
74,415,276
Undo -Werror for a particular warning
I use -Werror ... -Wno-unknown-pragmas compiler flags (cause I don't need unknown pragmas to cause an error). However, this silences all unknown pragma warnings. Is there a way to produce -Wunknown-pragmas warnings while not turning them into errors, and to apply -Werror to all other warnings.
-Werror -Wno-error=unknown-pragmas should do the trick.
74,415,260
74,415,304
I cannot understand the compiler C++ switch, invalid operand error
#include <iostream> #include <cmath> using namespace std; int main() { float Litr; int opcja; cout << "Konwerter" << endl; switch(opcja){ case 1: cout << "Litr na barylke amerykanska i galon amerykanski" << endl; cin >> Litr; cout << Litr << " litrow to " << Litr * 159 << " barylek i " <<...
In this case, they are simple syntactic errors. When you have to express a decimal number in C ++ you have to use the "." and not the ",". There was also the problem that the command to execute was not asked in input and a simple cin was inserted. #include <iostream> using namespace std; int main() { int opcja; ...
74,416,100
74,416,123
find the biggest number in 2D array, except one element
I have a task to find the biggest number in 2D array, except the a[2][1] element. The input is: 4 4 2 3 4 8 5 9 6 3 9 8 4 6 4 2 3 The output should be: 9 Im getting the output 8 Since there are two 9's in the array, I dont know how to fix it. #include <iostream> #include <iomanip> using namespace std; int main() {...
You are ignoring the value of a[2][1] you should ignore the index pair (2,1) instead: #include <iostream> #include <iomanip> using namespace std; int main() { int n; int a[10][10]; cin>>n; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>a[i][j]; } } in...
74,416,249
74,416,989
Is flat_map an STL container?
In the current draft of C++23s flat_map design, the type flat_map::reference is defined as pair<const key_type&, mapped_type&>, i.e. it is not a reference to flat_map::value_type = pair<key_type, mapped_type>. (This seems to be mandatory, since the keys and values are stored not as pairs, but in two separate containers...
The standard defines what a "container" is in [container.reqmts]. Among these requirements is: typename X::reference Result: T& So yes, std::flat_map is not a container. But it never claims to be; it is a "container adapter": A flat_­map is a container adaptor... Note that like std::stack/queue/priority_queue, st...
74,416,337
74,416,452
CPP file compile in visual studio
I have a single CPP file which contains my code, however when I try to compile it specifically with build feature I can't find how and were to do it. I tried building through solution explorer but there was no option for build
Go to the Visual Studio's File Menu and choose: File Menu -> New -> Project -> Select C++ from the filter dropdown list -> Select Empty Project from the list below -> Click the Next button -> Enter the Project Name - > click the Create button. In the Solution Explorer project tree: Right-click on the Source Files leaf ...
74,416,345
74,416,568
Writing a sequence of numbers like: 1 22 333 4444 55555 via recursion c++
I have to write a code in c++ without loops, which would display a monotonic sequence of numbers like 1 22 333 to the number I input, so number k is repeating k times. It's like i input 6, the code would display 1 22 333 4444 55555 666666. It has to be via recursion. For now, if i cin >> 15 output is a row of numbers f...
There you go: #include <iostream> int x{0}; void another_func(int n, int counter) { if (counter-- > 0) { std::cout << n; another_func(n, counter); } } void func(int n) { if(n>=1){ func(n-1); another_func(n, n); //for (int i = 0; i != n; ++i) // std::co...
74,417,085
74,417,292
How to sort a char vector that is inside a struct
I'm looking for some guidance here. I have a project and I'm looking to sort a char vector inside a struct. I have the next struct and the main: struct employee { long Id; char name[20] }; int main () { employee data[5] for(int i=0; i<5; i++) { for(int x=i+1; x<5; x++) { if(data[i].name[0]> dat...
You can use std::sort with a custom comparison function, as commented. The comparison function: receives two employees, and returns true if the first name is alphabetically "smaller" than the second (i.e. strcmp returned < 0). [Demo] #include <algorithm> // sort #include <cstring> // strcmp #include <fmt/core.h> s...
74,417,728
74,422,719
How to define a custom mock allocator?
I'm trying to define a custom std::basic_string specialization with a mock allocator to log all memory operations that basic_string performs. struct MockAllocator : std::allocator<char> { char* allocate(size_t n); void deallocate(char *p, size_t n); }; using CustomString = std::basic_string<char, std::char_tra...
The following assumes C++11 (and later) allocator semantics, which older compilers (even if they did otherwise implement C++11) may not have implemented fully yet. Your type doesn't satisfy the allocator requirements because it doesn't rebind properly and so there is no guarantee how the code will behave. A minimal st...
74,418,043
74,418,109
Using the built-in C++ function to make parameter variable "seat" upper case
Am trying to make the parameter variable "seat" upper case but I keep getting errors I don't want to include bits/stdc++.h header file but am stuck trying to figure it out. I need guidance on how to make it work Error states 'transform': identifier not found these are the includes i have in the code #include <iostream>...
Did you include <algorithm>? std::transform is found in <algorithm> so if you didn't include it C++ doesn't know what std::transform is, hence the error. Edit: I see you don't have <algorithm> included, so just add #include <algorithm> to the top of your code and the error should disappear. Edit 2: Just iterate over ea...
74,418,172
74,418,313
Is there a way to remove reference, cv qualifiers, and pointerness of a type to make it plain?
Take the following code: struct Foo {} template<typename T> void passFoo(T t) {} I would want the domain of passFoo to be restricted to Foo objects, but I don't mind if they are references, pointers, or cv qualified. Is it possible to somehow remove all those aspects of a type to get down to the "plain" type, when us...
Combination of std::remove_cvref_t and std::remove_pointer_t would work: template<typename T> concept Foo_C = std::is_same_v<Foo, std::remove_cvref_t<std::remove_pointer_t<T>>>;
74,418,448
74,418,587
Why is a rvalue string stream working in this context but not an lvalue?
I noticed that I could do some quick and dirty translation of a narrow to a wide string by doing the following: #include <iostream> #include <sstream> int main() { using namespace std; wcout << (wstringstream{} << "This works.\n").str(); wstringstream ss{}; wcout << (std::move(ss) << "This works too.\n...
In the working examples the type is std::basic_stringstream which has a str() method and comes form an rvalue template of the << operator: std::__cxx11::basic_stringstream<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >&& std::operator<< <std::__cxx11::basic_stringstream<wchar_t, std::char_traits<wchar_t>...
74,418,884
74,420,237
Creating a 3D vector. C++
Help me please. I have a 3d vector. I need to make a new vector from this using existing internal indices. I hope the input and output information will be clear. Input: a = { { {1,1,1,1}, {2,2,2,2}, {3,3,3,3}, {4,4,4,4}, {5,5,5,5}, {6,6,6,6} }, { {10,10,10,10}, {20,20,20,20}, {30,30,30,30}, {40,40,4...
You can solve this matrix transpose more succinctly. for(const auto& a1 : a){ b.resize(a1.size()); auto b1 = b.begin(); for(const auto& a2 : a1){ b1->push_back(a2); b1++; } } output is {{1,1,1,1,},{10,10,10,10,},{100,100,100,100,},}, {{2,2,2,2,},{20,20,20...
74,418,999
74,419,709
Templated template function as input parameter to function in C++
I have several classes which all receive raw data on the form of an uint8 buffer, and the underlying datatype of the data in the buffer is decided at runtime. The buffer needs to go through a converter function that's templated, and decided in a big switch statement at runtime, depending on the received data type which...
You cannot pass function templates to your template. You could however pass an object providing a template function: template <typename O, typename Converter, typename I> O applyFunctionForDataType(const uint8_t* const input_data, const DataType data_type, Converter&& converter, const I& input_params) { ...
74,419,992
74,420,151
Can't print cyrillics cahracters in terminal
I have an labaratoly work from my university - I have to print ASCII table with ukrainian symbols, then make transliteration from ukrainian to english but I have met problems that I expalined here. I think than I have tried everething I could and it wont work. Please help me.
This is a rtf for Ukrainian Character Set KOI8-U : https://www.rfc-editor.org/rfc/rfc2319.html .... You can map your std ascii table to the required cyrillic characters. Another option is to look at something like yandex. https://yandex.com/dev/translate/ it is an api for translating but I think its a service that cha...
74,420,848
74,420,882
How does Name lookup work when using multiple inheritance in C++?
Why does the following work(I know it would not work when d.f(5)): #include <string> #include <iostream> struct A { int f(int a) { return a*a; } }; struct B : A { std::string f(std::string string) { return "Hello " + string; } }; struct Derived : B {}; int main() { Derived d; std::cout << d.f("5") << std::endl;...
In the former case the class does not have a method whose name matches the method name getting called. Next, the class is derived from a class, and the derived-from class has a method with the matching name, which satisfies the name getting looked up. In the latter case the class is derived from two other classes, and ...
74,420,853
74,420,913
Vector of object pointers recursive function using next object pointer in vector
I have a vector (vector<Spell *> spells;) and I want to be able to call the cast() function on the first element of the vector and have the spells cast the Spell* in the vector but the program will reach me->cast(me, pos, 0.0f, capacity-1, draw); and run into a segmentation fault, crashing the program. My code: #inclu...
me++ increments the pointer but me isn't a pointer to an array so your code has undefined behaviour. Each pointer in your vector is unreleated to the rest and you can't use pointer arithmetic to traverse between them. You'd be better of using iterators instead: #include <iostream> #include <vector> using namespace std...
74,421,150
74,424,685
Why does std::basic_string have two separate template parameters _Elem (char type) and _Traits (char traits)?
The problem is I don't understand why those should be separate. Why not use one class, like CharType, that would contain both the logic of char traits and char type. I mean replace that: template <class _Elem, class _Traits = char_traits<_Elem>, class _Alloc = allocator<_Elem>> class basic_string { /*...*/ }; with tha...
I think it makes more sense to separate the character type from the Traits object. Traits is an additional class for character comparisons and such, which is inherently different from the character type. Your method would work, but the equivalent would be like combining two completely different functions into the same ...
74,421,315
74,421,459
How to i get my Array to output its random generated values from 0 - 99
I wanted to make a function called fillArray to set up random values to the Array. Then i wanted the function to output all the values but i kept getting values way above 99. This is what i have written so far: #include <ctime> #include <iostream> using namespace std; void fillArray(){ srand(time(NULL)); con...
So, your error is simple: You have declared a function in the main function like this: int main() { void fillArray(int a[10], int random); } But it should have been int main() { fillArray(int a[10], int random); } Which is calling the fillArray function Also there are a few other things that i would like to add, ...
74,421,337
74,421,658
The program's structure is different from the output
I decided to write the code in such a manner where both inputs are from the user and the system adds the value to give the sum of the 2 values provided by the user. but the out is different from what I expected it to do. please refer to the respective attached block of the result *I really hope that someone could help ...
If you take a good look of both your codes, you can see where the main problem is; The difference (beside cout comments) are into these lines: cin >> nm1, nm2; and cin >> nm1; cin >> nm2; And the reason you got a big surprise is that you misread(incorrect syntax) multiple integers from the input stream; You can use co...
74,422,217
74,422,260
Vector of an array of structs resets strings to be blank. C++
So I'm having a very confusing issue where I'm attempting to print a string from a vector of arrays of structs to the console. Integers print just fine however strings stored within these structs get set to "". I have no idea what's going on here but after setting up a test as shown bellow this issue is still persistin...
This surprised me. The following code is legal (syntactically at least) testStruct testArray[1] = { testArray[0] = {"String works", 69} }; but if you replace it with the sensible version testStruct testArray[1] = { {"String works", 69} }; then your program works as expected. I expect your version has undefine...
74,422,385
74,422,579
Delete Even Numbers From A Linked List C++
I can't seem to understand what am I missing, I've spent hours and hours looking at this and everything I tried doesn't work. My thought process to check if the second node of the list is even, if it is then to link the first and third node and delete the second but it doesn't work... I've been stuck at this for a week...
There are several things wrong with this code. Your use of curent->next invokes undefined behavior when curent is pointing at the last node in the list, since next will be NULL in that case. It is are causing you to skip the 1st node in the list. You never assign aux to point at anything, so calling delete on aux is a...
74,423,083
74,423,142
Determining the return type of a class method without warning on gcc
I would like to alias a return type for a templated class method, on clang I use template <class R, unsigned int BlockSize> struct block { using KeyType = decltype(((R*)nullptr)->getKey()); } This works fine on clang, but on gcc 11.3.0 I get a warning: warning: ‘this’ pointer is null [-Wnonnull] My question is w...
To be able to use member functions in unevaluated contexts such as decltype expressions one should use std::declval: template <class R, unsigned int BlockSize> struct block { using KeyType = decltype(std::declval<R>().getKey()); }
74,423,293
74,423,305
Creating a public variable from another class (C++)
If you have two classes, class a and class b, could you create a variable in class a from class b? main.cpp class A { public: A() {} }; class B { public: B() { test = A(); test.<variable name> = <variable value>; } }; The code above is just an example. It will p...
No, C++ is not Javascript. Types are strict and, after you define a type, there's no way to modify it. You can, however, create a local type in a function: class B { public: B() { struct A_extended : A { int i; }; auto test = A_extended(); test.i = 1; } };
74,423,550
74,423,575
How to remove the last \n from a file?
I write a table to a file, using simple: ofstream myfile; myfile.open("file.txt"); myfile << "rho P \n"; for (j = 0; j < blocksize; j++) { myfile << rho[j] << " " << P[j] << "\n"; } myfile.close(); The problem is the last "\n" that creates a new line I don't like. how to remove it?
ofstream myfile; myfile.open("tabulated/QEOS.txt"); myfile << "rho (g/cm^-3) P (GPa); T="<<T<<"\n"; for (j = 0; j < blocksize; j++) { myfile << rhoiterp[j] << " " << Piterp[j]; if(j < blocksize - 1) myfile << "\n"; } myfile.close(); We are printing "\n" exactly before the last e...
74,423,660
74,423,921
While loop will only terminate if I use CTRL + C on the terminal
The prompt of the question is: Write a program that prompts the user to input the name of a text file and then outputs the number of words in the file. You can consider a “word” to be any text that is surrounded by whitespace (for example, a space, carriage return, newline) or borders the beginning or end of the file....
Your outer loop is reading words from the file and counting them just fine (operator>> handles the whitespace for you). However, your outer loop is also running an inner loop that is reading user input from stdin (ie, the terminal). That is where your real problem is. You are waiting on user input where you should not ...
74,423,675
74,424,787
terminate called after throwing an instance of 'std::length_error' what(): basic_string::_M_create
The problem is to reverse words in a string ... Eg. - This is Nice Output -Nice is This so here's the error terminate called after throwing an instance of 'std::length_error' what(): basic_string::_M_create Here's my actual code, don't know where it went wrong I just started c++, but I'm sure I'm trying to access ...
Your approach is inefficient. Also you are not reversing the source string but building a new string in the reversed order. The compound statement of the if statement if(isspace(s[i])) { v.push_back(x); x=""; v.push_back(" "); } does not make great sense when the source string contains adjacent spaces...
74,424,110
74,424,220
My VS Code is showing wrong error messages
Have no idea what is wrong, any thoughts and answers will be helpful. The compiler is showing errors when there aren't any.
left and right are variables of the class called Node: Node * left; Node * Right; You used a variable as a function, which causes the error. To solve the error use: Line 30 a.setLeft(b); Line 31 a.setRight(c); Also, on line 18, you’re trying to setRight() but you change the variable of left. It must be right = &n.
74,424,386
74,424,516
How to play gif in qt cpp?
I want to show a gif on the screen until an action is finished. As far as I understand from the examples, I tried something like this, but the gif does not appear on the screen. How can I do that? QMovie *movie=new QMovie(":/images/loading.gif"); if (!movie->isValid()) { qDebug()<<"Movie is not val...
You need an event loop. Bracket your code with a QApplication creation and exec... QApplication app(argc, argv); QMovie movie(":/images/loading.gif"); if (!movie.isValid()) { qDebug() << "Movie is not valid"; } // Play GIF QLabel label; label.setMovie(&movie); movie.start(); app.exec();
74,424,854
74,425,317
Pass private variable to non-member function on separate thread
I am passing a private variable from a class function to a thread executing a function not part of the class. The function call works without problems when executed normally, but when I try to execute it using a separate thread, I get the error message "static assertion failed". Does anyone know what I'm doing wrong he...
All values passed to the constructor of std::thread are moved or copied. You can find this in the documentation. The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with std::ref or std::cref). If you think a...
74,425,128
74,425,476
Trying to understand: clang's side-effect warnings for typeid on a polymorphic object
This question is not about how to avoid the described warning. (Store in a reference beforehand; Or use dynamic_cast instead of typeid) I'm trying to understand why the warning exists in the first place. What is it trying to protect from? Consider the following code example: #include <memory> #include <iostream> struc...
You already explain the purpose of the warning correctly, so I will just go through the list to explain why it does or does not apply in each case: //1) warning: will be evaluated std::cout << typeid(*pa1).name() << '\n'; pa1 is not a pointer, it is a class type, a std::shared_ptr<A>. It is true that the dereferencing...
74,425,494
74,425,648
How make template member function specialization from inherited class?
Need some help about template member function specialization as following code; class Base { public: template <int> void MyFunc(); }; class Object : public Base { public: //template <int> void MyFunc(); // with this works !!! template <> void MyFunc<3>() { } }; Th...
You can't. The reason is that when the compiler sees the declaration of Object, it doesn't know anything about Base's template functions. So it can't generate a specialization of MyFunc for Object. The only way to make this work is to declare the specialization of MyFunc in the Base class. Member function templates are...
74,425,959
74,425,974
C++ Code outputs two characters when I only desire one output (Fix found!) <3
As simple as it sounds. I'm a newb when it comes to c++, but I have been following cpp reference and some online tutorials to write code. My code should output a string as "SuCh", but instead it outputs something as "SSuuCChh". Is there a practical error I'm missing? #include <cctype> #include <iostream> using namespa...
You're calling putchar and using cout, so you're printing each character twice in two different ways. Eliminate either the call to putchar(), or the cout <<, and you will only get each character once.
74,426,092
74,431,294
How to have C++ call overridden method after a conversion to the base class
I have a class A with method Hello: class A { public: void Hello(){ std::cout << "Hi from class A!" << std::endl; } }; I then have a class B that inherits class A and has its own Hello method: class B : public A { public: void Hello(){ std::cout << "Hi from class B!" << std::endl; } }; I create a ...
You should use reference and can call Hello() B myB; A& myA = static_cast<A&>(myB); myA.Hello(); oupput: Hi from class A! If you add "virtual" to Hello() of class A, virtual void Hello() { you can get output below. Hi from class B!
74,426,141
74,426,210
Using a custom value as a local variable
What I want to do is to use a custom value as a local variable (in code this looks something like this): #include <iostream> #include <iomanip> #include <cmath> #include <fstream> using namespace std; int main() { fstream someFileStream; someFileStream.open("RandomFileName.txt"); double a0; double a1; double a2; ...
Since using a counter value in the name for an assignment seems to be impossible in c++, the next closest thing to solving this problem was hard-coding a switch into the while loop: for (int counter = 0; counter <= 3; counter++) { getline(someFileStream, SomethingString, '\n'); double SomethingDouble = stod(Som...
74,426,229
74,427,152
Why does the == operator of std::unordered_multiset<T> returns wrong result when T is a pointer type?
Is this a bug, or am I doing something wrong? I already tried providing hashing and equality functors for the pointer type, but it doesn't seem to work. I even tried creating my own miniature template container just to test the functors. Hashing functor: class CharPtHash { private: using pChar = char*; public: ...
Supplying your own KeyEqual only change the behavior internally, i.e. inserting new items. However it has no effects on operator==. According to operator==(std::unordered_multiset), the behavior of it is as if each equivalent equal_ranges were compared with std::is_permutation. You can potentially specialize the behavi...
74,426,266
74,426,381
C++, getting gibberish from const unisgned char array
I am trying to write a program with a simple login interface for school in C++. I am new and still learning but I am getting a strange error with the following snippet of code. Inside the loop it outputs the username,password and name just as intended but if I try to access the array later it outputs gibberish. Any hel...
According to the documentation: The pointers returned are valid [...] until sqlite3_step() or sqlite3_reset() or sqlite3_finalize() is called. Since you are calling sqlite3_step on each iteration, the pointer you saved into the arrays became invalid right afterward. Solution Either manually invoke malloc and strcpy ...
74,426,674
74,436,138
Can switch default statement be optimised out for enum
If I have a switch statement that handles all enum cases explicitly, is the compiler allowed to optimise away the default case statement? enum MyEnum { ZERO = 0, ONE = 1, TWO = 2, THREE = 3, }; bool foo(MyEnum e) { switch(e) { case ZERO: case ONE: case TWO: case THREE: return true; default: // Could a c...
Yes, I guess in theory they could. There is no standard-sanctioned way to reach the default. As mentioned on the cppreference page, the standard essentially says in [dcl.enum]/8 that the possible values of an enumeration without fixed underlying type are zero to, exclusive, the smallest power of two able to fit all of ...
74,426,867
74,426,980
C++20 <chrono>: How to calculate difference between year_month_date?
Using C++20's <chrono>, how can I find the days difference of two year_month_day objects? int main() { using namespace std::chrono; const auto now = system_clock::now(); const year_month_day today = floor<days>(now); const year_month_day xmas = today.year() / month(12) / day(25); const days days_ti...
You can use std::chrono::sys_days to convert to std::chrono::time_point. For example, auto diff = std::chrono::sys_days(xmas) - std::chrono::sys_days(today); std::cout << "diff days: " << std::chrono::duration_cast<std::chrono::days>(diff).count() << "days\n";
74,427,054
74,428,668
Put .conan folder with cache to the current project folder
Is there any way to create .conan folder in the root of the current project on building stage?
You can define CONAN_USER_HOME environment variable to point to your current folder, that will put the Conan cache there. However this doesn't have many advantages, one of the reasons of having the cache separated is that it is way more efficient to have the packages installed in a common place, and they can be used in...
74,427,605
74,427,766
How can I fix C++ error C2672 in my code with threads?
When I'm trying to compile program with threads, C2672 error ('invoke': no matching overloaded function found) is occuring. My code: #include <iostream> #include <thread> // the procedure for array 2 filling void bar(int sum2) { for (int i = 100000; i < 200000; i++) { sum2 = sum2 + (i + 1); std::cou...
You need to pass a value to the thread you're creating, std::thread thread(bar, N); where N is the integer value, as you've defined in your void bar(int) function. #include <iostream> #include <thread> // the procedure for array 2 filling void bar(int sum2) { for (int i = 100000; i < 200000; i++) { sum2 = ...
74,427,737
74,428,867
How to get angle between two vectors in 3D
I have two objects one sphere and a cone. I want cone to always face the sphere as shown in the images. we have constructed the cone in local coordinate system in such a way, that the tip of the cone points upward the y-axis and the center is at the origin (0,0,0). The angle between two 3D vectors would be float fA...
First, you need the vector where the cone should point to: direction = center_cone - center_sphere; Then, we assume, that you've constructed your cone in the local coordinate system in such a way, that the tip of the cone points upward the y-axis and the center is at the origin (0,0,0). The axises to rotate are: x_axi...
74,429,257
74,429,594
Compare string array1 with string array2 and return entries that are not present in array2
I have two arrays in my C++ code. array1 has all elements but array2 has the same elements but with a few missing. I am trying to find out the elements that are missing in array2. Instead of showing the missing elements, it is showing elements which are also present in both the arrays and multiple times. string array1[...
You implemented the logic of your code a little bit wrong. So, first iterate over all elements from array1. Then, check, if the current element is in the array2. For this you can use a flag. If it is not in, then print it. There are even standard functions in the C++ algorithm library availabe. But let's ge with the be...
74,429,465
74,432,464
Synchronization problem with std::atomic<>
I have basically two questions that are closely related and they are both based on this SO question: Thread synchronization problem with c++ std::atomic variables As cppreference.com explains: For memory_order_acquire: A load operation with this memory order performs the acquire operation on the affected memory locati...
Your linked question has two atomic variables, your "cppreference" quote specifically mentions "same atomic variable". That's why the reference text doesn't cover the linked question. Quoting further from cppreference: memory_order_seq_cst : "...a single total order exists in which all threads observe all modification...
74,429,905
74,438,895
Large interval upper bound of a CGAL lazy number
I have an example of a sum of the form s = a_1/b_1 + a_2/b_2 + ... where the a_i and the b_i are CGAL lazy numbers, such that the interval returned by s.interval() is very large. Its lower bound is close to the expected value (and close to CGAL::as_double(s)) but its upper bound is huge (even infinite). But if I use my...
You are computing factorials and similar products. Once they exceed the maximum value for a double, there isn't much an interval represented as a pair of double can do. At least it gives you a safe answer, and you can still get the true answer using exact() at the end. Your division would be simpler as return exact(x1/...
74,429,998
74,430,207
Declaration of a String of Dynamic Length Using Pointer
I wanted to declare an array with a pointer in character type, and the length of the array can be determined by my input string. I wrote it in this way: char *s; cout << "Enter a string: " << endl; cin >> s; I expected that I can initialize the string by the cin operation, but an error showed up when compiling. The er...
You should use std::string. It is a class that represents a string of characters. It is different than an old c style array of characters (although internally might contain one). In your case: #include <string> #include <iostream> std::string s; std::cout << "Enter a string: " << endl; std::cin >> s; Using std::strin...
74,430,850
74,430,921
I have Question about class overriding in C++
When I study about override keyword, I found some strange thing like below code. #include <iostream> template <class T> class A { public: virtual void some_function(const T a) { std::cout<<__PRETTY_FUNCTION__<<std::endl; std::cout<<"Base"<<std::endl; } }; class Deri...
The function prototypes are not the same. For T=int* const T a: a is a const pointer to an int, while const int *a is a pointer to an const int. For one the pointer is const, for the other the int is const. int * const a would be the same as const T a, or you can make T=const int*. https://godbolt.org/z/WEaEoGh58 Also ...
74,431,090
74,444,578
Qt Folder organization
I am learning Qt6 in Qt Creator 8.0.2 (Community) with C++ on Windows. I have a project( Qt Widgets Application) with Qmake as the build system. When I open the project in Creator it is well organized, that is, the headers(.h files) are in a header folder, sources(.cpp files) are in sources folder, etc. Like so: Learni...
Yes, you can reorganise file locations. It is still unclear from your question what problems you have with it. You just have to mimic whatever the changes you made on your storage directories in your *.pro file as well. QtCreator will usually understand what you did on the fly. If it does not then you erase or empty it...
74,431,093
74,433,892
How to check a valid boost asio CompletionToken?
I'm writing Boost.Asio style async function that takes CompletionToken argument. The argument can be function, function object, lambda expression, future, awaitable, etc. CompletionToken is template parameter. If I don't restrict the argument, the function could match unexpected parameter such as int. So I want to writ...
If you have c++20 concepts, look below. Otherwise, read on. When you want to correctly implement the async-result protocol using Asio, you would use the async_result trait, or the async_initiate as documented here. This should be a reliable key for SFINAE. The template arguments to async_result include the token and th...