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,148,653
74,148,673
Implementation of stable_sort in python
In c++ there is a function stable_sort() function (It preserves the order ) .Is there any function in python like this ?
list.sort() is stable. From the documentation: The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
74,148,958
74,149,018
How do i access private data members of a class in C++
#include<iostream> using namespace std; class item{ int a,b; void getdata(int x,int y){ x=a; y=b; } public: void here(int a,int b) { void getdata(); } void display(); }; void display() { printf("a is %d",a); printf("\nb is %d ",b); ...
You've implemented a free function called display. The declared member function display does not have an implementation. It should be: void item::display() { std::printf("a is %d\n", a); std::printf("b is %d\n", b); } You should also #include <cstdio> to use std::printf. Also note that the getdata function doe...
74,149,482
74,149,645
Find Extreme Value in Integers Given
I'm trying to find the highest value in a given list, but in an input list like this 7 385 -390 305 470 -145 255 30 my output is wrong, 385 instead of 470. Could anyone please guide me towards my error! Task description: Read in an input value for variable numIn. Then, read numIn integers from input and output the lar...
First of all, your list has negative numbers. You can't set the default value of high to 0 since a list with all negative numbers won't work if you do this. The error in your loop occurs because you overwrite numIn. Use a different variable for the number of input numbers. cin >> numIn; // numIn is the number of input ...
74,149,490
74,149,549
Pointer to a member function does not contain the information of the instance?
(This is a question after reading this answer) I tried this code: #include <iostream> class A { public: int a; A(int val) : a{val}{} int f(int); int (A::*p)(int); }; int A::f(int in) { return in + a; } int main() { A a1(1000); A a2(2000); // Without these two lines, segmentation fault. a1.p = &A::f; // no...
Non-static member functions have a "hidden" first argument that becomes the this pointer inside the function. So instance is not part of the function itself, but rather passed as an argument. Note the quotes around "hidden", because it's only hidden in the function signature. When using other ways to call e member func...
74,149,523
74,149,649
Is it possible to use X-Macro with std::variant (or with template in general)?
I hope to do the following using X-macro with c++17, but since template parameter does not support trailing comma, it does not work for the std::variant part. Is there someway around it? #define LIST_OF_TYPES(X) \ X(Type1) \ X(Type2) \ X(Type3) #define MAKE_TYPE(name) class name {}; L...
Yes, there's a workaround: #define EMPTY(...) #define IDENTITY(...) __VA_ARGS__ #define IDENTITY2(...) __VA_ARGS__ std::variant< #define MAKE_VARIANT(name) (,) name IDENTITY IDENTITY2(EMPTY LIST_OF_TYPES(MAKE_VARIANT) () ) #undef MAKE_VARIANT > Without IDENTITY2(...) this expands to EMPTY(,) Type1 IDENTITY(,) Type2 I...
74,149,760
74,149,839
c++ using range based to access the vector wrapped in a shared_ptr gives unexpected result
I have the following code, why is the range based output is not what is stored in the vector? #include <iostream> #include <memory> #include <vector> using namespace std; shared_ptr<vector<double>> get_ptr() { vector<double> v{1, 2, 3, 4, 5}; return make_shared<vector<double>>(v); } int main() { auto vec...
Every time you call get_ptr() you create a new and unique copy of the vector. And that object will be destructed as soon as the full expression involving the call is finished. So in the case of for (auto v: (*get_ptr())) As soon as *get_ptr() is finished, the object will be destructed. And due to how ranged for loops ...
74,149,928
74,150,085
defining constexpr variable by checking string condition
int run(std::string type, std::string interval) { if(type == "ST"){ if(interval == "SEC"){ constexpr unsigned int N = 10; Runner<N> data(); data.parse(); } else{ constexpr unsigned int N = 20; Runner<N> data(); data.parse(); } } else if(type == "JST"){ constexpr...
run as you are showing can't work, even in principle, because you want N to be runtime-dependent. N can't be constexpr. Alternative approach: template<auto V> inline constexpr auto constant = std::integral_constant<decltype(V), V>{}; template<typename F> void apply_with_arraysize(F&& f, std::string type, std::string i...
74,150,310
74,150,707
Sending JavaScript Object QML signal parameter
I am trying to connect a QML signal to a Qt slot with following parameter types: in QML side: signal Sig(var info) in Qt side: QObject::connect(topLevel, SIGNAL(Sig(QVariantMap)), &mObj, SLOT(mSlot(QVariantMap))); Which gives me the following: QObject::connect: No such signal QQuickWindowQmlImpl_QML_24::Sig(QVariantM...
The parameters are QVariants on C++ side, so you need to do QObject::connect(topLevel, SIGNAL(Sig(QVariant)), &mObj, SLOT(mSlot(QVariant))); Note that you also need to change mSlot parameter type, because QVariant can't be implicitly converted to QVariantMap. To get the map in the slot, use QVariant::toMap() method, i...
74,150,327
74,151,047
string size() returns 1 too large value in evaluation system
if I have very simple part of code like: string myvariable; getline(cin, myvariable); cout << myvariable.size(); and if I run that program locally it returns appropriate value (so exactly number of characters including spaces in the given string). But if I upload that program to the programs evaluation system (sth lik...
After the discussion in the comments, it is clear that the issue involves different line ending encodings from different operating systems. Windows uses \r\n and Linux/Unix use \n. The same content may be represented as "Hello World!\n" // in a Linux file or "Hello World!\r\n" // in a Windows file The method getline ...
74,150,480
74,150,685
How does structure padding work in ESP32's compiler
I was talking with a friend and trying out different structure configurations. And looking at the outputs has me confused as to how the structure is being padded. I'm using wokwi's online esp32 compiler for this. The structure configurations that have me confused are: struct bruh{ short int aK; short int a; char ...
Padding is not to bring the size up to the next multiple of 4, it is to ensure every member is always on the correct alignment. Different types have different alignment requirements, and these are all implementation-defined. You can use the alignof operator to look at the alignment of a type. Here's one compiler report...
74,150,499
74,150,879
my class has no suitable copy constructor - depending if the argument of the constructor is const or not
Question: I am learning c++, and i created a class to represent complex numbers. I created a copy constructor with the format complex(const complex &c); and the program worked fine. Then, i removed the const (so it became: complex( complex &c); ) and the program doesn't work. It gives me this error: "message": "class ...
Before C++17, the following line return complex( re + c.re, im + c.im); actually includes two object creations. First an unnamed temporary object is constructed using two double parameters. Then a copy of this object is made to where the return value is stored. This second copy is the reason for your compiler error. A...
74,150,614
74,150,687
Error when trying to output element of a standard array that is a struct member
I'm trying to run the following code: #include <iostream> #include <array> struct newperson { std::array<char, 20> name{}; int age; }; int main() { newperson nicolas = { "Nicolas", 21 }; newperson martin = { "Martin", 45 }; std::cout << nicolas.age << std:...
There is no overloaded << (stream output) operator for the std::array container, whatever the element type. However, that array container does have a .data() member, which yields a pointer to the first element; in your case, that will be a char* and the relevant specialisation for outputting a char* (assuming that poin...
74,150,709
74,152,675
Should two programs compiled with -O0 and -O2 each produce identical floating point results?
Short example: #include <iostream> #include <string_view> #include <iomanip> #define PRINTVAR(x) printVar(#x, (x) ) void printVar( const std::string_view name, const float value ) { std::cout << std::setw( 16 ) << name << " = " << std::setw( 12 ) << value << std::endl; } int ma...
The question is - should we expect the identical result with -O0 and -O2 on the same platform? No, not in general. C++ 2020 draft N4849 7.1 [expr.pre] 6 says: The values of the floating-point operands and the results of floating-point expressions may be represented in greater precision and range than that required b...
74,151,009
74,151,118
Erasing element in std::vector of std::pair of std::string
I have a std::vector of std::pair of std::string where the language and translation are the values. These are the values in my vector of pair 0. {English, Love}, 1. {Spanish, Amor}, 2. {Tagalog, Mahal}, 3. {English, Love} What I wanted to do is to only remove the index 3, but in my code if I try to remove th...
To delete by index you can do something like this: language_translation.erase(std::next(language_translation.begin(), index));
74,151,198
74,151,367
C++ Concurrency in Action joining_thread implementation in listing 2.7
I am reading the second edition of C++ Concurrency in Action book and I have a question concerning chapter 2. In listing 2.7, a joining_thread class is provided. I was wondering why the second constructor copies pass the thread argument by value? I understand that it is meant to call it like: joining_thread jt{std::thr...
Since you write about copying of threads, I suppose you meant: std::thread t(fct); joining_thread jt(t); instead of: std::thread t(fct); joining_thread jt(fct); The first one simply does not compile because threads are non-copyable. In particular, std::thread has a deleted copy constructor: https://en.cppreference.co...
74,151,559
74,152,498
Why does this std::enable_if only have the first parameter, and how does static_array match?
Here is a piece of code // check if type of static array template <class T> struct ABIStaticArray : std::false_type //#1 { }; // stringN type => bytesN template <std::size_t N> struct ABIStaticArray<std::array<char, N>> : std::false_type //#2 { }; // a fixed-length array of N elements of type T. template <class T, ...
Let's see what is happening step by step. When you wrote: Length<std::array<int, 5>>::value Step 1) The template parameter T for Length is std::array<int, 5> Step 2) Now there are two options that can be used. Either the primary template template <class T, class Enable = void> labeled as #4 or the specialization for s...
74,152,355
74,153,013
CUDA and openCV (CPU) Matrix Addition Performance constant with increasing numels
I compare the performance of Matrix Addition using a simple CPU function, CUDA and openCV (on CPU) by increasing the number of elements consecutively and measuring the runtime. I have plotted the data below. Note that it is one plot per datatype, where CUCV_8U is a macro for unsigned char, CUCV_16U=unsigned short, CUCV...
I have noticed that the runtime of openCV and CUDA does not increase until the matrices have roughly 2^12 elements. Starting a kernel take some time since it requires an interaction with the OS (more specifically the graphic driver) and the target device with is generally a PCI device (requiring a PCI communication)....
74,152,542
74,152,849
Error in LLVM IR or runtime library produces SEGV
I'm writing a programming language called PPL. In PPL integer literals are arbitrary width by default. This is archived with using pointer to GMP's mpz_class for integers. However, when compiling -1, there is an error from address sanitiser: ==92833==ERROR: AddressSanitizer: SEGV on unknown address 0x000100000006 (pc 0...
I solved the problem with removing load of function arguments. Instead of: define ptr @"- <:Integer>"(ptr %a) { %1 = load ptr, ptr %a, align 8 // This is wrong for some reason. // Looks like arguments aren't pointers themself %2 = call ptr @_MinusInteger(ptr %1) ret ptr %2 } Compiler now generates: define pt...
74,153,853
74,153,929
Why isn't the source std::map for std::map::merge const?
Is there a reason why template<class C2> void std::map<Key,T,Compare,Allocator>::merge( std::map<Key, T, C2, Allocator>& source ); takes source as a reference, rather than a const reference? Perhaps I'm having a senior moment here, but I don't see how source is changed in any way by the function, plus it's less than h...
merge() does, in fact, modify the source map. It's an optimized operation that executes the merge by relinking both maps' innards, transplanting the merged values from one map to another without actually copying either the key or the value, only by fiddling the internal pointers. Hence, at the end, the source map will ...
74,153,872
74,154,664
Accessing embedded resource as "a file"
I'm trying to glue together two libraries where lib1 is providing scripts to lib2. The libraries are used in c++11 code I'm writing. I can't modify those libs. Scripts in lib1 are embedded into the shared object with https://github.com/vector-of-bool/cmrc. The content of each script can be accessed with an iterator, li...
While named pipes are usually used for inter-process communication, they also work intra-process. And on many Operating Systems, including Windows, they have a name that's part of the file system namespace. Hence you can usually pass a pipe name to libraries which expect file names.
74,154,181
74,154,344
Why isn't this abstract class working with circular dependency?
When I compile my code, I get: "src/gameObject.cpp:8:13: error: expected unqualified-id before 'class' GameObject::class Component& getComponent(const std::string &name)" alongside several other errors of a similar type. I'm not sure if the problem has to do with the abstract class or the forward declaration of the c...
First things first, you don't need to added the class key class everywhere a class name is expected. Often it is optional in C++ unlike C. Problem 2 Next, you're actually defining a free function named getComponent instead of a member function. For defining the member function outside the class, we first have to be in ...
74,154,268
74,212,004
Is it possible to create a service at runtime using gRPC C++ from a descriptor set?
I'm attempting to create some test drivers for some C++ applications that communicate over gRPC. Most of these test drivers simply use grpcurl to fire off some messages to the applications under tests and verify the responses. Some of our apps, however, connect to streaming RPCs. It would be trivial to write a test dri...
There are a couple of ways to achieve this and one of which would be using gRPC C++ GenericService. By doing so, you can handle all methods without pre-declaring them.
74,154,484
74,154,550
`constexpr vector` still fails, while there's stated to be supported in cppreference
On https://en.cppreference.com/w/cpp/compiler_support, cosnstexpr vector is stated to be supported. But when I wrote #include <vector> constexpr std::vector<int> vec{2, 3, 3, 3}; int main() { } and compiles it using -std=gnu++2b flag, it still triggers a error In file included from /usr/include/c++/12/vector:61, ...
std::vector being constexpr-friendly means that it can be used inside a constant expression evaluation. It does not mean that a variable of that type can be declared with constexpr specifier. (Talking about constexpr std::vector in that context is maybe a bit misleading.) Because std::vector uses dynamic allocation, it...
74,154,552
74,154,846
Structuring a project with circular dependencies using C++ modules
I have an existing C++ project, and although I'm being pretty experienced with C++ itself, I haven't dony anything with modules yet and I thought it was time to finally bite that bullet. I have a small library which is currently structured in several source and header files, where each header describes a major class an...
What you need to do is make sure that the interface partition module json:array does not contain any code that requires JsonValue to be defined. Definitions of member functions or any other code which accesses it should not be part of that partition. They should be defined in an implementation unit, or a later interfac...
74,154,595
74,154,817
Modifying a data of type "static const int* const" from a member function
TLDR Question: class MyClass { public: void Modify() { //How can I modify MyData here } public: static const int* const MyData; }; Lore: I have a class like this: class Window { public: const int* GetKeyboard() { return m_Keyboard; } private: const int* const m_Keyboa...
Either an object is const or it isn't. If it is const it must be given a value in its initialization and any attempt at changing it later will cause undefined behavior (if it isn't ill-formed to begin with). There is no way to make an object const after a certain other point in the execution flow. Of course you can jus...
74,155,446
74,155,466
void function parameter and overload resolution/template argument deduction
I am developing a system where users register their functions with a framework that calls the functions on the users' behalf. The framework accepts user functions that have at least one function parameter, which helps discourage functions with too many side effects. The number of input parameters to a function is thu...
In what way does the C++(20) standard somehow specify that a void function parameter should be ignored? From https://eel.is/c++draft/dcl.dcl#dcl.fct-4 : A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.
74,155,493
74,166,152
How can I resize frameless window in QML?
How can I return resize logic of borders in Frameless Window? The frame windows has this logic: Code in QML: import QtQuick import QtQuick.Controls 2.5 import Qt5Compat.GraphicalEffects import NR 1.0 Window { id: mainWindow width: 640 height: 720 visible: true title: qsTr("Hello World") flags:...
Since Qt5.15, we have startSystemResize, which performs a native resizing and is recommended against using methods like comparing the click position to the current position. The function is very simple; once you pass an edge, the window begins to resize. An example of a frameless window is shown below: CustomWindow.QML...
74,155,721
74,157,243
timer for measuring function execution time not working
I'm writing a cuda library and I need to check the differences in performance between the option CPU and GPU. So I created a simple class called Timer to measure the time required to execute first a GPU function and then the CPU version. class Timer { public: Timer() { _StartTimepoint = std::chrono::ste...
You declare a local variable _ms with the same name as your member variable. During the stop function the local variable takes precedence over the member variable, so you never actually store a value in the member. You can show this by initializing the member to some value in the class definition and you will see that ...
74,155,956
74,174,392
Use OpenSSL in Unreal Engine 4.25
I’m trying to use the OpenSSL library included with the engine. I am using 4.25 In my searches I see people saying to add OpenSSl as a dependency to my project’s build file. I have seen couple different lines to add to the build file, every one of them causes errors - usually about the the function not being in the cur...
My problem is that I kept trying to do things in the target file, not the build file - as mentioned in a comment above by Strom. To enable OpenSSL in an unreal c++ project (I'm using Visual Studio): Open up your project build file. Add OpenSSL to the PublicDependencyModuleNames: using UnrealBuildTool; public class MyP...
74,156,096
74,158,117
Eigen tensor reshape then broadcast results in gibberish numbers when going from rank 0 to rank 1 tensor
I have the following code that seeks to find the maximum element of a rank 1 tensor, which shrinks to a rank 0 tensor, and then broadcast it back out to the full length of the rank 1 tensor so I can use it in further computations involving the original rank 1 tensor. //reduces a rank 1 tensor to a rank 0 tensor. Tensor...
It appears to be a bug in Eigen 3.4.0 related to tensors of dimension zero. Reproducible example (godbolt): #include <iostream> #include <Eigen/../unsupported/Eigen/CXX11/Tensor> int main() { Eigen::Tensor<double, 3> MaxTest(4, 4, 4); MaxTest.setRandom(); Eigen::Tensor<double, 0> columnmaximum = MaxTest.maximum(...
74,156,130
74,156,254
How do I use concepts to constrain the argument types for variadic functions?
I have a variadic function that can take any combination of input arguments, as long as each one of those arguments is convertible to bool: #include <concepts> #include <cstddef> // internal helper functions namespace { template <typename T> constexpr std::size_t count_truths(T t) { return (bool)t; ...
You can simply use C++17 fold expression to do this #include <concepts> template<std::convertible_to<bool>... Args> constexpr bool only_one(Args... args) { return (bool(args) + ... + false) == 1; } static_assert(only_one(true, false, true, false, true) == false); static_assert(only_one(true, false) == true); static...
74,156,310
74,164,771
C++ - What are virtual methods?
Based on this, the following code should print "Running derived method", but when I run it, it prints "Running base method": #include <iostream> using namespace std; class Base { public: Base() {} virtual void run() {cout << "Running base method" << endl;} virtual ~Base() {} }; class Derived : public Bas...
There is an answer in the comments, but I have to post it as an answer to close it. Before reading it, I found it out myself by comparing the example code with my code, but the comment was helpful because I now know it's called object slicing. When I assign the value to a variable or field that has the base type, it fo...
74,156,448
74,156,468
How to use pointer to member inside a class object (right syntax)?
In this example i'm trying to return x, y or z from get_by_ptr function, but can't unedrastand rigth(legal) syntax to do it. I understand that this pointer holds base address of object and pointer to member holds "address shift" and I can calculate address. But is there legal syntax way? class foo { public: size_t ...
You likely want to write: size_t get_by_ptr(size_t foo::*ptr) { return this->*ptr; }
74,156,479
74,156,590
Cannot execute int function in menu
I wrote program which use menu to execute function. #include <iostream> #include<conio.h> #include <stdio.h> #include <cstring> using namespace std; int menu(); void zad1(); void zad2(); int main(){ switch(menu()){ case 1: zad1();break; case 2: zad1();break; default: cout<<"blank"; ...
After this input cin>>wybor; the input buffer contains the new line character '\n'. So the next call of fgets printf("Enter the string you want encrypted\n"); fgets(string, sizeof(string), stdin); reads an empty string that contains only this new line character. You need to clear the buffer before calling the functio...
74,157,038
74,173,059
Create custom reporter for Catch2 in single header version
There is already a section in Catch2 documentation about how to create custom reporters. The problem is that this seems to work only for the non-single header version of Catch2. Using single header version of Catch2, the two base classes for reporters ( Catch::StreamingReporterBase and Catch::CumulativeReporterBase) ar...
It depends on the version of the library you are using. Versions 2.x were based on the single header catch.hpp and had numerous additional macros to configure what is included from that header. In particular, you would need #define CATCH_CONFIG_EXTERNAL_INTERFACES #include "catch.hpp" to access the reporter definition...
74,157,060
74,196,934
Microsoft Graph - CompactToken parsing failed with error code: 8004920A
I am requesting access token from Microsoft Graph using this procedure: I request access to the following scopes: User.Read.All openid profile email offline_access https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All https://outlook.office.com/SMTP.Send After the consent s...
As @Nikolay has stated, the tokens for Graph and Outlook can't be mixed. And Microsoft has designed it poorly so that IMAP.AccessAsUser.All for example can't be used for IMAP access - the access_token simply won't work unless the https://outlook.office.com/ prefix is added. But - I found another way, which works for ju...
74,157,171
74,157,266
C++ struct in a class with error: expected an identifier
Here is the simplest I think I can get this code: class MyFrame : public wxFrame { public: MyFrame(const wxString &title, const wxPoint &pos, const wxSize &size); private: struct controlChoice { wxChoice *choice; int prevChoice; }; wxPanel *panel; controlChoice *profileChoice; ...
The code does compile. That is not valid C++ syntax and any conformant C++ compiler should reject it as controlChoice is a typename while this->profileChoice is a qualified name and C++ grammar rules doesn't allow such an usage. You can instead use the member initializer list for initialization of those members: cla...
74,157,640
74,158,217
Is there an easy way to implement C++ queries like the ones from ODB?
I am working with filters in C++ and I would like to create a query like ODB does: db->query (query::age > 30) I don't know what kind of data is being passed there. I have been reading about filters in C++ (with functors, lambda expressions, ...) but it is not as simple and compact as ODB queries. In addition, these qu...
You want expression trees. You might start with: template<auto Member> struct member_query_t; template<class T, class V> struct member_query_t< V T::* M > { V const& operator()(T const& t) const { return t.*M; } }; template<auto Member> constexpr member_query_t<Member> member_q = {}; now member_q<&Model::id> is a C...
74,157,781
74,183,319
Cause of difference in performances of default pmr allocator and default std allocator
I am trying to investigate the cause of the difference in performance between the two allocators, as shown in https://en.cppreference.com/w/cpp/memory/monotonic_buffer_resource. What I have found so far: In GCC, it seems that the default pmr allocator uses monotonic_buffer_resource but not the std allocator, according...
It does indeed use new_delete_resource. (which from std::pmr::get_default_resource()) you can check it by list.get_allocator().resource()->is_equal(*std::pmr::new_delete_resource()); // true https://godbolt.org/z/qGTG57MfY Not sure about what the benchmark is, but type erasure comes with it's own penalty, pmr one wo...
74,158,371
74,170,421
VCPKG and CMAKE not using static libraries when compiling a .exe
I have a project that uses gRPC and I have gRPC installed on Windows with VCPKG. I have the -x64-windows-static triplet installed and I have the target triplet set in my CMakePresets.json file as shown below: "name": "windows-base", "hidden": true, "generator": "Visual Studio 17 2022", "binaryDi...
Delete your CMakeCache and retry. You probably had VCPKG_TARGET_TRIPLET not set on first configure which defaults to x64-windows and makes find_library|file|path|program already find the x64-windows stuff. Since these are all cache variables they won't be found anew on subsequent runs! Also consider setting VCPKG_HOST_...
74,158,506
74,158,921
Time complexity of lookup and then insertion in a std::map<std::string, std::set<std::string>>
So I have a graph (std::map) that stores strings as the keys and the values are sets of strings (adjacency lists for each node in a graph): std::map<std::string, std::set<std::string>> graph My insertion code is simply: graph[from].insert(to) where from and to are both strings. So I insert to in the set of strings ass...
Time complexity is in terms of something, for example key comparisons. Finding a key in a std::map or std::set is in O(log n) key comparisons. If your key comparison function compares two strings character by character, then you can say that finding a key in this case is in O(s log n) with s the average size of the key...
74,158,577
74,158,638
C++ pass a child as a parent to a function
so here's a simplified version of my setup: class GenericSensor{ public: int read(){ return something; } }; class SpecialSensor : public GenericSensor{ public: int read(){ return somethingElse; } }; and I have a function: void someFunction(GenericSensor s){ printf("value is: %d\n",...
You should declare read() as a virtual function which SpecialSensor, or any other derived class, can override. Moreover, you should not pass GenericSensor around by value, otherwise you will slice the caller's object. Rather, pass it around by pointer or reference instead. So have someFunction() receive s by GenericSen...
74,159,354
74,159,422
Why does this need auto?
auto data = new char[480][640][3](); char data = new char[480][640][3](); First works. Second doesnt. Why? Isn't auto supposed to just replace itself with the type of the initializer?
Because the type isn't char. The type is char(*)[640][3] and the declaration would be written as char (*data)[640][3] = new char[480][640][3]();
74,159,372
74,161,745
nvprof - Warning: No profile data collected
On attempting to use nvprof to profile my program, I receive the following output with no other information: <program output> ======== Warning: No profile data collected. The code used follows this classic first cuda program. I have had nvprof work on my system before, however I recently had to re-install cuda. I have...
As per the documentation, there is currently no profiling support in CUDA for WSL. This is why there is no profiling data collected when you are using nvprof.
74,160,067
74,160,099
Lambda cannot be implicitly converted to std::function
I am attempting to create a wrapper around an std::function for reasons not explained here. I know that the following code works. std::function<void()> function = [&]() -> void {}; The following is my wrapper around the std::function, however, it does not work when I try to construct it with a lambda. template<typena...
It's one too many implicit conversion steps. Generally speaking, C will let you get away with one level of indirection. So we could call a function that expects a double and pass it an int, and things will work fine, because there's an implicit conversion from double to int. Now let's look at your code. custom_function...
74,160,279
74,160,317
Comparing "Hello 4" to input in C++
I'm trying to use something like strcmp to compare a command like "Hello 4" and keep the 4 as a variable Something like this: if(strcmp(c, "Hello %d") == 0){ int num = %d; }
You're looking for sscanf, which uses the scanf-style percent encoders you're using and takes a string to parse as its argument (as well as pointers to store the successful parses into). It returns the number of arguments successfully stored, or a negative number in the case of an EOF error. In your case, we'll conside...
74,160,621
74,160,638
Multithreading in a for loop misses the first iteration
I am writing an application requiring a variable number of threads, which I would like to create within a vector over which I could iterate. The application consistently skips the first iteration of the for-loop but instead performs an unintended operation at the end of the loop. I would like not only to solve the issu...
Your lambda: [&](){print_func(i);} captures the int i by reference, so when the thread started, i is no longer the same value, and for the last iteration, i goes out of scope, therefore it has garbage value from the stack. Capturing by value instead of reference will solve your problem: [i](){print_func(i);}
74,160,971
74,163,026
Declaring a variable and assigning with move assignment operator in one statement on Clang causes seg fault
I've got this trivial example of what I thought was calling the move assignment operator of this Test struct. Running it, it calls the move constructor and then seg faults on destruction on Clang. On MSVC, it works fine. I'm a bit confused by that behavior cause i would expect it to construct with the parameterless con...
The move constructor is going to be called, because that is exactly what the code you wrote is designed to do: Test newTest = std::move(test); There is no move assignment happening here, since a new object, newTest, is being constructed from the value on the right side of the =. Since your move constructor has a call ...
74,161,049
74,161,200
How to save excess user inputs? C++
As you know in C++ one is able to have variables assigned based on a user input via std::cin. When using std::cin ,if I recall correctly, when there are too many inputs that what is required, then the extra inputs are ignored. int main(){ int a, b; std::cin >> a >> b; std::cout << a << " " << b << endl; ...
answer: The data stream is not lost, cin still holds the unused data stream. explain You can understand cin like this way, it has a stream of date, and each time cin was called, it would check the target variable type and pour (or consume) the date to fill the variable until success or read delimiters or use out the d...
74,161,145
74,161,316
storage of mipmaps in OpenGL
OpenGL version 450 introduces a new function which can be used to allocate memory for a texture2D: glTextureStorage2D(textureObj,levels,internal_format,width,height); //here, parameter 'levels' refers to the levels of mipmaps //we need to set it 1 if we only want to use the original texture we loaded because then there...
What do you mean by "reserve extra memory"? You told OpenGL how many mipmaps you wanted when you used glTextureStorage2D. When it comes to immutable storage, you don't get to renege. If you say a texture has width W, height H, and mipmap count L, then that's what that texture has. Forever. As such, glGenerateTextureMip...
74,161,794
74,161,879
Can a friend class object access the methods of the host class?
Suppose we have a class A: class A{ int a_; public: friend class B; A(int a):a_(a){} int getA(){ return a_;} void setA(int a){a_ = a;} void print(int x){cout << x << endl;} }; and another class B: class B{ int b_; public: B(int b):b_(b){} void setB(int b){b_ = b;} int getB(){ret...
How to use a method of class A like print() using an object of class B? B isn't related to A in any way so you can't. The only thing you've done by adding a friend declaration is that you've allowed class B(or B's member functions) to access private parts of class A through an A object. Note the last part of the prev...
74,162,104
74,162,293
C Preprocessor Stringify enter\newline characters
So like many that have dealt with OpenGL Shaders in the past being able to write them without an extra program to convert them into a string has always been a want. So what I am looking for is a way to replace enter presses\newline characters in the source code with "\n" for example: const char *sShaderSrc = ConvertTex...
A Macro Solution (and why it doesn't work for your purpose) This can be implemented as a variadic macro so that it actually compiles. #define ConvertTextToString(...) #__VA_ARGS__ Unfortunately, there are two problems preventing this from being useful in the scenario. It still doesn't preserve the newlines, as the ne...
74,162,633
74,168,316
Problem compiling from source OpenCV with MVSC2019 in 64 bit version
I was compiling openCV for windows with Qt using MSVC in the 2019 64 bit version. At the time of launching the first configuration I get a bit list of errors like this: Check size of size_t CMake Error at C:/Program Files/CMake/share/cmake-3.25/Modules/CheckTypeSize.cmake:147 (try_compile): Cannot copy output executa...
I had the same problem, it is the CMake-3.25.0-rc2 fault, change it to 3.24.2 and it will work.
74,162,863
74,162,900
Does std::string class handle clean up if the assignment operator fails due to length_error or bad_alloc?
Does std::string class handle clean up if the assignment operator fails due to length_error or bad_alloc? Does it give me back my intact string I provided? UPDATE: SOLVED: YES OPERATOR= IS SAFE PER MY REQUIREMENTS. THE CODE BELOW ADDS NO VALUE TO EXCEPTION SAFETY given this reference from https://cplusplus.com/referenc...
Since C++11 it leaves the string intact. If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11) cppreference
74,163,013
74,166,829
ShellExecuteA cannot find file
I'm trying to open a file with a c++ program using ShellExecuteA in Windows10. (I'm also using VisualStudio2019 in case that's relevant.) ShellExecute itself is working (I can use "explore" and "find" as it is intended), however it seems to be unable to find the file even though it exists in the directory. I have trie...
Ok, it turned out it was a spelling mistake, causing my file to be named "MyTextFile.txt.txt" Thank you to everyone who tried to help me find the answer.
74,163,649
74,163,812
Does std::optional contain a value during construction?
Check out the following code for an example: #include <iostream> #include <optional> class A { public: A(); ~A(); }; std::optional<A> a; A::A() { std::cout << a.has_value(); } A::~A() { std::cout << a.has_value(); } int main() { a.emplace(); std::cout << a.has_value(); } I ended up with something s...
As far as I can tell, the current draft of the standard (as provided by https://timsong-cpp.github.io/cppwp/) is not explicit, but the MSVC behaviour is for me the specified one (whever it is the desirable one during destruction is dubious): First emplace contains the following text Effects: Calls *this = nullopt. The...
74,163,821
74,163,973
Qt: QDesktopWidget file not found
So I'm trying to use this class just to resize a window and its the main class I found to get the geometry of a users screen. I couldn't find many others with this problem besides adding : QT += widgets in my .pro file and running qmake. Unfortunately this did not work, if anyone has any advice Thankyou!
From the Qt documentation: QDesktopWidget was already deprecated in Qt 5, and has been removed in Qt 6, together with QApplication::desktop(). QScreen provides equivalent functionality to query for information about available screens, screen that form a virtual desktop, and screen geometries.
74,164,180
74,164,830
c++ constexpr typed as nested class
This works: (A) class Foo { public: const bool b; constexpr ~Foo() = default; constexpr Foo(const bool b) : b(b) {}; }; class Bar { public: static constexpr Foo tru { true };//Foo is complete type }; This fails to compile: (B) class Bar { public: class Foo { public: const bool b; constexpr ~Foo() ...
The problem with (B) is distinct from the one with (C). In (B) the completeness of Foo is not in question. Foo is complete as soon as the closing } of its definition is reached and since the member declaration of tru is placed after that, Foo is complete for its purpose. There is also no problem in (B) with Bar being i...
74,165,235
74,165,268
Is it possible to use a macro defined value in C/C++?
In the LLVM codebase, I see this lines: class LLVM_EXTERNAL_VISIBILITY Function : public GlobalObject, public ilist_node<Function> { My LSP (clangd) tells me that LLVM_EXTERNAL_VISIBILITY refers to /// LLVM_LIBRARY_VISIBILITY - If a class marked with this attribute is linked /...
One idea is that it acts as a conditional: if something happens, then the preprocessor substitutes some text; if not, it simply doesn't substitute anything, but prevents the compiler from complaining about some undefined LLVM_LIBRARY_VISIBILITY token. Is this correct? Pretty much. Some build environments, it'll have ...
74,165,292
74,529,850
How to compute the mel spectrogram on STM32?
I'm working with a STM32F4Discovery board, and I'm trying to run a neural network on it for sound classification. I want to create the mel spectrogram directly on board from the sound recorded from the built-in microphone, which I already converted to PCM, and than give it as input to my neural network (trained with te...
It is possible to compute the mel spectrogram on STM32 boards by using CMSIS DSP Library provided by ARM alongside with the STM32_AI_AudioPreprocessing_Library included in the FP-AI-Sensing package. In the FP-AI-Sensing library there is also an example for the mel spectrogram computation.
74,166,718
74,171,436
thread::detach during concurrent thread::join in C++
In the following program, during one thread (main) is performing thread::join, another thread (x) calls thread::detach: #include <thread> #include <iostream> int main(void) { auto t = std::thread([] { std::this_thread::sleep_for( std::chrono::milliseconds(1000) ); } ); auto x = std::thread([&t] { ...
Neither join nor detach are const-qualified and therefore the implementation is allowed to modify internal memory of the thread object without having to provide any guarantees of write/write or write/read data race avoidance on unsynchronized calls to these member functions per the default data race avoidance requireme...
74,166,778
74,172,649
Can relaxed stores be reordered before a compare_exchange across the loop iterations?
Consider the following code. #include <atomic> #include <cassert> #include <thread> struct foo { std::atomic<foo*> _next = nullptr; }; foo dummy = {}; foo a = {}; std::atomic<foo*> b = nullptr; void thread_0() { auto* old = b.load(std::memory_order_acquire); // (1) do { a._next.store(old, std::me...
I think two separate questions are being conflated here. First, to answer the title question, loops are irrelevant to memory ordering. All that matters is program order - "sequencing" in the language of the C++ standard. You will not find any mention of looping in the memory model sections of the standard. And at the...
74,167,516
74,168,032
How to create a template that can use different arguments from the same base class
I'm trying to create a Threshold template class that allows me to compare numeric values against a threshold value. I want to easily change the comparison function to use greater_equal or less_equal so I create the following template: template<typename T, typename comp_func = std::greater_equal<T>, typename std::enabl...
You specifically declared foo as a function that only takes a Threshold<T>, i.e. an instance of a template where the comparator is the default. Just include both template arguments in your definition: template<typename T, typename comp_func, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr> ...
74,168,266
74,168,267
std::format pointer error C3615: consteval function 'std::_Compile_time_parse_format_specs' cannot result in a constant expression
How to fix (stdC++20 mode VS2022) #include <format> #include <string> auto dump(int *p) { std::string resultstring = std::format(" p points to address {:p}", p); resulting in: error C3615: consteval function 'std::_Compile_time_parse_format_specs' cannot result in a constant expression
Cast the pointer to void like this: std::string resultstring = std::format("{:p}", (void *)p); The problem is not with the format string itself, but rather that the templated type checking on the variable arguments FAILS for any non-void pointer types, generally with a confusing error in the header .
74,168,405
74,168,493
understanding std::is_base_of possible implementation from cppreference
Here we have is_base_of template implementation taken from cppreference.com: namespace details { template <typename B> std::true_type test_pre_ptr_convertible(const B*); //1 template <typename> std::false_type test_pre_ptr_convertible(const void*); //2 template <typename, typename> ...
Overload resolution ignores accessibility for the purpose of deciding which candidates are viable and for choosing the best candidate. If D is a derived class of B (irregardless of accessibility), then //1 is always viable and a better candidate for overload resolution than //2 (which is also viable) and overload resol...
74,168,488
74,168,543
Difference between const method and method with const attributes
What is the difference between const at the beginning: const int MyClass::showName(string id){ ... } And : int MyClass::showName(const string id) { ... } And : int MyClass::showName(string id) const{ ... }
const modifies the thing it's next to, like a word like "little". "A little yard with a shed" is different from "a yard with a little shed". Let's look at your code examples: const int MyClass::showName(string id) { The returned integer is const. This has no effect because the caller receives a copy and had no abili...
74,168,490
74,168,563
How to correctly implement producer consumer problem
I tried to implement producer consumer problem in C++, but I found that my implementation has a problem that it will produce until the size reaches the capacity and then start the consume process. I wonder what's the problem with my implementation. #include <iostream> #include <mutex> #include <thread> #include <queue>...
You need to unlock the mutex while you sleep. Just introducing a new block (curly braces) is all you need to do. Such that the unique_lock destructor will run before the sleep call. You could also manually invoke lk.unlock before the sleep call. Instead of this: void producer(){ while(true) { unique_lock<m...
74,168,788
74,169,014
how to check repetition of a certain number of zeroes following by an equal number of ones in a string?
If user enters a string, i want to make a function to check if a repetition of a certain number of zeroes follows an equal number of ones. Example: 001101 (correct), 01(correct),001010 (incorrect). I've tried to store the string in 2 separate strings and compare the size but my 2nd while loop isn't stopping. void check...
Here you are testing the elements from left to right and you're adding to st0 the last elements from num string. For example: "111010": after the first while num = "111" and st0 = "010" while (num[i] == num[i+1]) { st0.push_back(num.back()); num.pop_back(); k++; i+...
74,168,804
74,168,823
Password requirements
I'm trying to declare this string as Invalid but in an input like this: 59G71341 or 8pjf7h14sx13 or 60s1v344 My output is getting approved through my string if statement and is getting listed as Valid. Could anyone guide me to why its passing through my if statement and labeling Valid!! I haven't learned how to use a d...
if ((secretStr[i] >= 0) && (secretStr[i] <= 9)) should be if ((secretStr[i] >= '0') && (secretStr[i] <= '9')) 0 and 9 are integers, but you are comparing characters, so you need to use the characters '0' and '9', or you could just use the isdigit function. if (isdigit(secretStr[i])) isdigit is declared in #include <...
74,169,044
74,170,790
Cant Overflow The Buffer For Shell Coding
I have this shell code which is suppose to open a MessageBox. It works when testing it with https://github.com/NytroRST/ShellcodeCompiler, however when I create a new console application using c and try to compile this #include <stdio.h> #include <Windows.h> unsigned char rc[] = "\x31\xC3\x89\x64\xE2\x80\xB9\x41\x30\x...
Use VirtualProtect, DWORD oldProt = 0; VirtualProtect(rc, sizeof(rc), PAGE_EXECUTE_READWRITE, &oldProt);
74,169,189
74,169,259
Difference in finding a number inside an unordered_map in C++ STL
In the case of unordered_map in C++, what is the main difference between: if(map.find(n) != map.end()) if(map.count(n) > 0) if(map[n] > 0) Consider map is an unordered_map of type <int,int>.
These lines: if(map.find(n) != map.end()) if(map.count(n) > 0) Are mostly equivalent. map::count will never return more than 1. This line: if(map[n] > 0) Loads the value associated with the key, n and compares if it's value is greater than zero. Not the same thing as the first two. map[n] also has a side effect. If...
74,169,243
74,169,553
unwanted implicit cast makes overload ambiguous
Consider the following code sample: void my_print(bool is_red, const char* format, ...){ va_list args; va_start(args, format); if(is_red) print_red(format, args); else print_normal(format, args); va_end(args); } void my_print(const char* format, ...){ va_list args; va_start...
You could rename both overloads of my_print to functions named differently and introduce a template names my_print instead, which allows you to add a check, if the type of the first parameter is char const* in an if constexpr to resolve the ambiguity. void print_red(char const* format, va_list lst) { printf("red ...
74,169,313
74,169,421
Template deduction depends on another template deduction
Since std::format isn't supported everywhere, and I didn't want another large dependency like fmt, I wanted to quickly roll my own to_string solution for a number of types. The following is the code. #include <ranges> #include <string> #include <concepts> template<typename Type> constexpr std::string stringify(const T...
The order of declarations of your template overloads results in template<typename Type> requires std::ranges::range<Type> constexpr std::string stringify(const Type& data) noexcept; being for the overload, when specializing template<typename Type> requires std::ranges::range<Type> constexpr std::string stringify_inner...
74,169,479
74,169,496
What's wrong with the space for an array declaration in c++?
I have long been declaring a lot more space for arrays during competitive programming. int pr[100010]; //for example However, when I was trying to declare an array for a smaller space this morning, things went wrong. #include <iostream> using namespace std; int main() { int n; cin >> n; int pr[100]; //seems ...
The problem is here: int pr[100]; //seems enough for(int i = 1; i <= n; i++) { int x; cin >> x; pr[i] = pr[i-1] + x; // uninitialized read of pr[0] } Reading an uninitialized variable is undefined behavior. In this case you read some garbage value, but your program could also crash or produce other unexpecte...
74,169,543
74,169,560
Why i am getting a zero total amount of money?
This code should accept three inputs represent the money: "cent", "paper" and "coins", then calculate the total amount of the money: int coins = 0; int paper = 0; int cents = 0; int transaction = 0; int total_money = coins + paper + cents; cout << "Do you want to fill your piggy bank?"; cin >> transaction; while (tra...
You need to do the addition after you get the values from the user, not before. Like this (for example) if (transaction == 2) { int total_money = coins + paper + cents; cout<<"total in piggy bank" <<total_money<< endl; } A program is a set of statements that are executed in a particular order. Variables in tha...
74,169,933
74,175,025
How to embed a youtube video?
I'm trying to embed a youtube video in a QWebEngineView widget, however, the video is not playing and I'm getting this msg: "Video indisponible Watch on YouTube" I tried with different videos and in all I got the same error, I also tried setting some settings up like: QWebEngineView* view = new QWebEngineView(); ...
I didn't use HTML and I test this way and it shows me the Video: I add this code in MainWindow: QWidget *wgt = new QWidget(this); QGridLayout *gridLayout = new QGridLayout(wgt); wgt->setStyleSheet(QString::fromUtf8("border: 1px solid black;\n" "border-radius: 25px...
74,170,473
74,173,819
Is it possible to load an extra helper .so during current gdb session?
Is it possible to load an extra helper .so during current gdb session? // point.h class Point { public: int x; int y; Point(int x1, int y1) {x = x1; y = y1;} }; // main.cpp #include "point.h" #include <stdio.h> int main() { Point p(3, 4); printf("%d\n", p.x); return 0; } g++ -g -c main.cpp -o main.o g++ -...
When debugging, I need to add a helper function to dump the Point object. The "normal" way to do this to write a custom pretty printer in Python. One advantage of doing that is that the pretty printer will also work for a core dump, whereas dump_point() solution will not (regardless of whether it's linked in or loade...
74,170,676
74,170,767
In c++ Why and how classname::member syntax can be used for an instance member?
class Human { public: Human(string name); string getName() { return Human::name; } void setName(string name) { Human::name = name ; } private: string name; }; Human::name in getName and setName funcs. work perfectly although name is not a static variable. Why is this ha...
First things first, you're missing a return statement inside setName, so the program will have undefined behavior. Now, Human::name is a qualified name that refers to(or names) the non-static data member name. For qualified names like Human::name, qualified lookup happens which will find the data member name. On the o...
74,170,753
74,170,903
Is there a difference in undefined behaviour in C and C++ when accessing different members of different type in a union for write and read operations?
Let's start immediately with the example code: #include <stdio.h> #include <stdbool.h> typedef union { bool b; int i; } boolIntUnion; int main(void) { boolIntUnion val; val.i = 0; printf("i = %d; %s\n", val.i, ((val.b) ? "true" : "false")); val.i = 1; printf("i = %d; %s\n", val.i, ((...
In C++, using a union member other than the last-stored member is undefined behavior, with an exception for structures with common initial layouts. C++ 2020 draft N4849 [class.union] (11.5) 2 says “… At most one of the non-static data members of an object of union type can be active at any time…” with a note there is a...
74,171,051
74,171,119
Warning in visual studio in simple sfinae code
I am writing a simple code for learning sfinae. However, it generates a warning only in Visual Studio (not when using g++). The code is: #include <iostream> #include <type_traits> template <class T, typename std::enable_if<std::is_integral<T>::value, nullptr_t>::type = nullptr> void f(T t) { std::cout << "Integer"...
I want to know why this flag is needed. From msvc's exception handling model: Arguments c When used with /EHs, the compiler assumes that functions declared as extern "C" never throw a C++ exception. It has no effect when used with /EHa (that is, /EHca is equivalent to /EHa). /EHc is ignored if /EHs or /EHa aren't sp...
74,171,185
74,171,318
Two different outputs from functions
#include <iostream> #include <iomanip> #include <ctime> using namespace std; char* InitializingMatrix(char start, char end) { char matrix[9]; //Initializing random symbols to char massive srand((unsigned)time(0)); for (int i = 0; i < 9; i++) matrix[i] = (int)start + rand() % (int)end; //...
The issue that you return a Pointer but you allocate a Value. Allocation: char matrix[9]; Return value: char* InitializingMatrix(...) Type char matrix[] is a compiled time array. If you wish to use arrays you'll need to use new char() instead to dynamically allocate a new array. The C++ OOP way is to use a class: Us...
74,171,340
74,173,736
Can't able to static compile QT 6.4.0 using Mingw
When I was trying to compile QT 6.4.0 static with Mingw I had and error with fxc, after spending time found it was an error because it couldn't able to find fxc.exe so I added fxc to path from windows kits (10), after adding it fixed that error but now I'm getting different errors. Configure: configure.bat -release -st...
To fix __uuidof error with mingw follow the steps from this link: https://forum.qt.io/topic/128587/build-failure-_uuidof-was-not-declared-in-this-scope/7 To fix QT DirectX issue follow this steps: Download Windows SDK from https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/. (I downloaded SDK for wind...
74,171,347
74,171,579
How to print a whole pair by just a key value in map c++?
Let's say I'm having a map of integer key value! map<int,string>a={{1,"one"},{2,"two"}}; How can I print a whole pair by just supplying a key value? Let's say user entered 1; I want my code to print 1,one then,How can i do so?
I've a map and user has to supply a key value,If that key value is present in that map,Then I've add that whole "pair" in different map, Is it possible to do so? Yes this is possible. You can use std::map::find to check if your input map contains a given key and then std::map::insert to add the key value pair into th...
74,171,648
74,172,133
Is it possible to "overload" the type deduced by auto for custom types in C++?
Not sure whether "overloading" is the proper term, however I am curious whether it is possible to make expressions of a given type to automatically convert to other type? Possible motivation: template <typename T> Property { // implement the desired behavior }; class SomeClass { // ... Property<SomeType> someProperty;...
No, that is not possible. auto will deduce to the (decayed) type of the right-hand side and there is no way to affect this deduction. You can however of course write a function template X such that auto someVariable = X(someInstance.someProperty); will result in the type you want, basically without any restrictions on...
74,171,933
74,172,170
hierarchical_mutex: are spurious exceptions possible?
In his book, C++ Concurrency in Action, A. Williams introduces the concept of a lock hierarchy as a deadlock-avoidance mechanism. Below, I report a stripped down version of a HierarchicalMutex implementation (taken from the book): class HierarchicalMutex { private: std::mutex Mutex_; unsigned const Level_; ...
At this point, thread B: Calls mutex.lock(); Evaluates check (1) to true. No it won't. current_level is declared as a thread_local object. If you are unfamiliar with what that means, see your C++ textbook for a more complete discussion, but it boils down that current_level is a separate, discrete object in each execu...
74,172,117
74,172,339
OpenMP: are variables automatically shared?
We already know that local variables are automatically private. int i,j; #pragma omp parallel for private(i,j) for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { //do something } } it is equal to #pragma omp parallel for for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { //do somethin...
They are shared by default in a parallel section unless there is a default clause specified. Note that this is not the case for all OpenMP directives. For example, this is generally not the case for tasks. You can read that from the OpenMP specification: In a parallel, teams, or task generating construct, the data-sha...
74,172,199
74,172,432
When resizing a std::vector of std::queue. Compile error; static assertion failed: result type must be constructible from value type of input range
I got the following class: class Buf { const uint8_t *data; size_t size; public: Buf() : data(nullptr), size(0) {}; Buf(const uint8_t *data_, size_t size_) : data(data_), size(size_) { }; Buf(Buf&& other) noexcept : data{std::exchange(other.data, nullptr)}, size{other.size} {}; Buf& o...
std::queue is a container adapter; that is, it forwards all of its actual operations to an internal container of a type specified by a template argument. By defualt, this container is std::deque. However, std::deque<T> is not noexcept moveable. Therefore, when vector<T> attempts to resize itself, it cannot use the move...
74,172,825
74,173,057
match c++ constructors with regex
I'm trying to create a regular expression to match constructor functions in C++ code. For instance, given a file that has the following content: Foo::foo // 1 Foo::Foo // 2 Foo::~Foo // 3 Foo::Foo(std::string) // 4 Logger::removeAppender(PLogAppender*) // 5 Logger::error(std::string&) // 6 I'd like the expression to...
Just use \s to make sure there are spaces ahead of the definition, also match for the arguments as well: (?<=\s|^)(\w+)::\1\s*(\((?:.|\n)*?\))* Try it on regexr
74,172,859
74,172,892
How to do a logical 'or' of requirements in a single concept?
I have the following case template<typename Class> concept has_member = requires (Class t) { // How can I write only either of the following conditions be satisfied? {t.isInterface() }->std::same_as<bool>; // or {t.canInterface() }->std::same_as<bool>; // or // ... more conditions! }; struct ...
Is it possoble to combine into one? Yes, it is possible. You can write the conjunction of two requires as follows: template<typename Class> concept has_member = requires (Class t) { {t.isInterface() }->std::same_as<bool>; } || //---> like this requires (Class t) { {t.canInterface() }->std::same_as<bool>;...
74,173,217
74,173,592
How does c++ decide which namespace to pick if it is omited
Why was the last A picked from ns1 namespace instead of ns2? (Bar is of type ns1::A<ns1::A<ns2::A, ns2::B>, ns2::B>) namespace ns1 { template <typename T, typename U> struct A {}; } namespace ns2 { struct /*ns2*/ A : ns1::A<int, /*ns2*/ A> { typedef ns1::A<int, /*ns2*/ A> Foo; }; struct B : ns1::A< /*ns2...
C++ classes have an injected class name available in class scope, which refers to the class itself. For example, for ns1::A<T, U>, the name A refers to ns1::A<T, U> in class scope . This injected class name can also be accessed in derived classes, so in ns2::B, the name A refers to the base class which is ns1::A<ns2::A...
74,173,414
74,173,931
Does std::cout guarantee to print a string if it doesn't end with a newline?
I've heard that the following program isn't guaranteed to print the string on every platform and to actually do it you need to add \n to the end or flush the buffer by other means. Is that true or does the standard guarantee the expected output anyway? #include <iostream> int main() { std::cout << "Hello, world!";...
[ios.init]/1 The class Init describes an object whose construction ensures the construction of the eight objects declared in <iostream> (29.4) that associate file stream buffers with the standard C streams provided for by the functions declared in <cstdio> (29.12.1). [ios.init]/3 Init(); Effects: Constructs and initia...
74,173,642
74,174,596
Linker command failed. CMAKE_INSTALL_RPATH not working
Trying to build a simple application with EASTL lib and having an error while building cmake --build . I don't know where is my mistake. Getting error: /usr/bin/ld: warning: libc++.so.1, needed by /home/user_name/.conan/data/eastl/package/lib/libEASTL.so, not found (try using -rpath or -rpath-link) /usr/bin/ld: warni...
Find the solution. The problem was is missing package libc++-dev So, the solution is to install it: sudo apt install libc++-dev
74,174,248
74,174,533
c++ can't pass an argument with CreateProcess
i have to pass a string into my process, but for some reason i can't i've tried to pass a path and an argument in function, i've tried to put a \0 after the argument, i've tried to pass an argument or space + an argument but it doesn't passes. could you please help me? #include <stdio.h> #include <tchar.h> #include <io...
Are you compiling in Unicode or Multibyte (MBCS)? Assuming you are compiling in Unicode you can avoid the use of string objects and use wstring objects instead. To initialize a wstring you have to prefix the double quoted string with an L, i.e. wstring first(L"C:\\Users\\User\\source\\repos\\1\\x64\\Debug\\1.exe"); So...
74,174,382
74,174,406
why don't we deallocate memory after allocating memory for object in heap in C++?
#include<iostream> using namespace std; class car { string name; int num; public: car(string a, int n) { cout << "Constructor called" << endl; this->name = a; this->num = n; } void enter() { cin >> name; cin >> num; } void display...
Most operating systems will free all memory associated with a program when it ends, so in this case, delete p; can be extraneous. This gets a bit more uncertain the lower level you go, especially in embedded systems. Best to get in the practice of using delete everytime you use new. Or don't use new/delete at all when ...
74,174,625
74,174,684
Why reference to array's object returns the object's address, not the value itself?
I've been studying arrays for a while and I struggle to grasp the idea behind these lines of code: int array[] {1, 2, 3, 4}; std::cout << "The address of the first element is " << &array[0]; Why reference in this case prints the address and not the value? As far as I know reference access the value of the object being...
int a = 24; int& r = a; // <- when is part of a type (e.g `int&` here) `&` denotes a reference type int* p = &a; // <- as an operator `&` is the address of operator
74,174,626
74,174,739
std::generate_n cannot generate my objects
I have a very simple class, which has an x, y and z values. Like so: class Individual { public: static std::unique_ptr<Individual> Spawn(std::mt19937& rng); Individual(double x, double y) : x(x), y(y) { SetZ(); } double GetZ() const { return z; } ...
generate_n()'s last argument is meant to be a function, not a value. That function will be called n times, once for each element to generate. You are giving it a std::unique_ptr. Wrap your Spawn(rng) call in a lambda expression instead. Additionally, std::generate_n() requires an iterator to the start of a range that i...
74,174,928
74,174,969
What is a difference between *iterator.fun() and (*iterator).fun()
I have simple code #include <iostream> #include <set> using namespace std; class Example { string name; public: Example(string name) { this -> name = name; } string getName() const {return name;} }; bool operator<(Example a, Example b) { return a.getName() < b.getName(); } int main() { ...
C++ has rules for operator precedence. According to these rules, the member access operator . has higher precedence than the dereference operator unary *. Therefore, the expression *itr.getName() Is interpreted as though it had the parentheses: *(itr.getName()) That is, it tries to evaluate itr.getName() and then der...
74,175,159
74,175,217
How to write a macro to convert member function to a string of its name?
I want to write ProgressFunction.BindUFunction(this, NAMEOF(&MyActor::HandleProgress)); instead of ProgressFunction.BindUFunction(this, "HandleProgress"); where BindUFunction's second parameter can only accept TCHAR*. Question How to define NAMEOF macro to convert &Whatever::FunctionName to "FunctionName"?
You could stringify the argument and find the last : in it. #include <cstring> #include <iostream> #define NAMEOF(x) (strrchr(#x, ':') ? strrchr(#x, ':') + 1 : #x) int main() { std::cout << NAMEOF(&MyActor::HandleProgress); } This is very similar to https://stackoverflow.com/a/38237385/9072753 .
74,175,542
74,175,569
error: call to implicitly-deleted copy constructor of <T> unique_ptr
I'm trying to create a unique pointer to a <Node> type variable: #include <memory> struct Node { int val; std::unique_ptr<Node> next; Node(int value, std::unique_ptr<Node> nextNode) : val(value), next(std::move(nextNode)){}; } int main() { Node headNode = Node(1, nullptr); std::unique_ptr<Node> h...
std::make_unique<Node>(headNode); This constructs a unique Node by attempting to copy-construct it from another Node. std::unique_ptr is not copyable, by definition (that would be due to the "unique" part of "unique_ptr"). This means that any class that contains a std::unique_ptr is not copyable by default, and its de...
74,175,661
74,175,697
My recursive display function is not going to the next value of the array
I have a recursive display function, meant to go through the values of array b and print the details. My function is successful in looping the correct amount of times, but only prints out the value at index 0. For example, if I have 3 books, it prints out the first book 3 times and is not going to the other values. I a...
I believe that you are not printing out each index of the "b" variable you need to access the index of each one. You need to have b as an array of pointers then access the index of that variable like b[n]->someProperty(); You can create the array like this: Obj* b[HOWMANY];