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
71,888,354
71,888,427
Why don't we have to declare static functions the same way we need to declare static variables in c++?
Consider the following struct: struct Toto { static int a; static void Print() { std::cout << a; } }; And the following main function using the struct in the same cpp file (main.cpp): int main() { Toto::Print(); } Building this gives the following error: Error LNK2001 unresolved external symbol "public: static int Toto::a" I understand from https://en.cppreference.com/w/cpp/language/static that Static members of a class are not associated with the objects of the class And thus, I've been told we have to define the variable Toto::a outside the struct, in the translation unit as follow: int Toto::a; From the same source it says that Static member functions are not associated with any object. And that Static data members are not associated with any object. Why do I have to define static variables but not static functions?
Static member functions are ordinary functions at the assembly level. The difference is only the hidden pointer 'this' that does not exist in them. They are basically global functions that exist like any other non static or non member (and not inline) function within the C++scope of a class name. Function scopes are C++ thing, they are not there at the CPU level. Static variables are different. They exist before any class object is created. They are not created when a class instance is created. They are there as globals. Perhaps it's done the way it's done to emphasize that difference.
71,888,462
71,892,261
Doxygen: document a class in the cpp file with separate source and header directories while using macros to define namespaces
I'm trying to document a library with the following files: include/mylib/mylib_global.h include/mylib/SomeClass.h source/SomeClass.cpp Doxyfile include/mylib/mylib_global.h: #pragma once #define MYLIB_NAMESPACE_BEGIN namespace mylibns { #define MYLIB_NAMESPACE_END } include/mylib/SomeClass.h: #pragma once #include "mylib_global.h" MYLIB_NAMESPACE_BEGIN class SomeClass { public: SomeClass(); }; MYLIB_NAMESPACE_END source/SomeClass.cpp: #include "mylib/SomeClass.h" MYLIB_NAMESPACE_BEGIN /*! * \class SomeClass * This is a sample class. */ /*! * This is a constructor. */ SomeClass::SomeClass() { } MYLIB_NAMESPACE_END Doxyfile: PROJECT_NAME = mylib INPUT = . RECURSIVE = YES MACRO_EXPANSION = YES Doxygen produces the following warning: Doxygen version used: 1.9.3 (c0b9eafbfb53286ce31e75e2b6c976ee4d345473) [...] include/mylib/SomeClass.h:7: warning: Compound mylibns::SomeClass is not documented. *** Doxygen has finished If I do any of the following, it works: Move the cpp to include/. But I don't want it there. Move the documentation to the header. But I'd like to keep it short. namespace mylibns { instead of the macro in the cpp. But I want the namespace to be configurable. MACRO_EXPANSION = NO. But that would also remove the namespace from the documentation. Explicitly state the namespace in the doxygen comment: \class mylibns::SomeClass. However that only helps with this specific issue (doxygen also fails to resolve overloaded functions). Things that don't help: Specifying any combination of longer paths for the INPUT parameter. EXTRACT_ALL = YES CLANG_ASSISTED_PARSING = YES How do I do this properly?
In the file source/SomeClass.cpp you have: #include "mylib/SomeClass.h" but the file SomeClass.h is located in include/mylib so you have to tell doxygen where to find the include file. This can be done by means of the setting: INCLUDE_PATH = include (analogous what you probably have done for the compiler with the setting like -I include)
71,889,509
71,892,076
How do I show the function parameter names in function calls (not as tooltips but actually written) or declarations
In the Image a good example is the InitAbilityActor info function call or the Binds declaration. For the info you'll see "InOwnerActor: this", so the "InOwnerActor" label placed there is what I'm asking about. I was watching an Unreal Engine tutorial and saw the author casually doing this, and I didn't know that it existed. I'm including a screenshot of what I mean. As you can see, it's not a tooltip or intellisense related (I don't think). Is it a Visual Studio feature (I have VS2019), a new option in the language, or some VS add-on that lets you do that? I do like that feature in Python, so if it's possible in C++, that would be great.
The screenshot is most likely showing the inlay hints feature of the Resharper C++ addin. I am not aware of any other readily available addin or built-in option that allows this for C++. Note that Visual Studio supports it out-of-the-box for C# and Visual Basic since VS 2019 v16.8, but not for C++. EDIT: As noted in the comments, the 2nd preview of Visual Studio 2022 17.2 contains this as an experimental feature, too.
71,889,512
71,889,861
Is there a shortcut to write a function with the same definition but different prototypes?
I have a method of a class which basically looks like this: void MyClass::method() { // Here I'm just doing something with parameters which are class attributes parameter_3 = parameter_1 + parameter_2 } I need another method which would have exactly the same body, but now I want the parameters to be passed in with the function call: void MyClass::method(type1_t parameter_1, type2_t parameter_2); I do not want to repeat the same code in another definition. What are possible solutions? The less ugly the better.
I need another method which would have exactly the same body, but now I want the parameters to be passed in with the function call: This can be solved using delegation. Simply call one overload from the other. Example: void MyClass::method(type1_t parameter_1, type2_t parameter_2) { parameter_3 = parameter_1 + parameter_2; } void MyClass::method() { method(parameter_1, parameter_2); }
71,890,075
71,891,337
Difference between passing value in function by int ** a and int & a
Is there any difference if i pass int **a in any function and at same place i pass int& a, will both create any difference?. Ex Bool issafe(int**arr, intx, int y) Bool issafe(int& arr, intx, int y)
There is a lot of difference between the '*' notation and '&' notation. Let us have a look at what both mean, in a general sense and little bit of technical detail. Reference Operator (&) &x simply means Address of x. It will be a an address value, often represented in hexadecimal notation. It is often used to pass by reference in functions: func(int &x, char a); This will pass x by reference, but a by value. Dereference Operator (*) *p means Pointer to a memory address. We may assign an address to this pointer using the following format: int *p = x or int *p; p = &x Once the pointer is pointing to an address, *p and x can be used interchangeable through the rest of the program. Double Dereferencing Usage of ** occurs when we need a pointer to a pointer. For example, if we need to make a a 2D Array, we can use the ** notation. One pointer points to the first element of the first row in the matrix, while the other pointer points to the first row in the list of rows. Thus, to answer your question in a few conclusive words: Yes, there is a big difference in int ** a and int & a, so much so that they go one level beyond being opposites like * and &.
71,890,241
71,890,682
Restoring a C++ stream's exception mask for caller
I am writing a C++ function that takes a std::istream as an argument and reads from it to decode an image. When decoding the image, I want the stream to throw exceptions if some error occurs during reading. That way, I don't have to intersperse checking the error flags with the rest of my decoding logic, making my code simpler. Because the caller might pass a stream without exceptions enabled, my function will enable them. I would like to restore the stream's initial exception mask when the function exits. I am just learning C++ and am trying to wrap my head around the idiomatic way to handle situations like this - where I'd normally toss cleanup code in a finally block: Image::Image(std::istream& stream) { std::ios_base::iostate originalExceptionSettings = stream.exceptions(); try { // Enable exceptions. stream.exceptions( std::ios_base::badbit | std::ios_base::failbit | std::ios_base::eofbit); // Do some stuff that might cause stream to throw... } finally { // If only! // Restore settings that the caller expects. stream.exceptions(originalExceptionSettings); } } I've seen people say that finally-type cleanup code should be handled like RAII. I guess I could create a little class to wrap this responsibility, which saves a pointer to the stream and the original exception mask. Its destructor would restore the original exception mask to the stream. // Something like this... StreamExceptionMaskMemo::StreamExceptionMaskMemo(std::istream* stream) { this->originalExceptionSettings = stream->exceptions(); this->stream = stream; } StreamExceptionMaskMemo::~StreamExceptionMaskMemo() { // Could throw! this->stream->exceptions(this->originalExceptionSettings); } While that will work in my case, it would be problematic to use this class to store an exception mask that specifies exceptions should be thrown for use in a function that disables exceptions. If the class was used that way, the destructor would reenable the exceptions, which immediately throws whatever exceptions are implied by the current state. I realize this is a bit contrived - probably the caller won't use a messed up stream anymore - but I am still confused about how I'd address the following problems: How do I write code that uses a stream supplied by a caller, knowing that the stream could have totally different behavior depending on what the exception mask is? How do you write cleanup code that could throw? If I was using a finally I could catch an exception thrown from within in the finally block and do something appropriate. But if I am spinning off the responsibility for cleanup to another class to allow RAII, I have to either let its destructor throw exceptions, or swallow them.
If the caller doesn't want stream exceptions, the old mask will not enable exceptions, so the restoration of the old mask will not throw any exception. Not a problem. If the caller does want stream exceptions, then the restoration will throw an exception if the stream state matches what the caller wants an exception for. Again, not a problem. So, the only real problem is the possibility of throwing an exception from inside an RAII destructor, which is generally very bad (but can be done with care). In this case, I would suggest just not using RAII. A simple try/catch will suffice (try/finally is not portable), eg: Image::Image(std::istream& stream) { std::ios_base::iostate originalExceptionSettings = stream.exceptions(); try { // Enable exceptions (may throw immediately!) stream.exceptions( std::ios_base::badbit | std::ios_base::failbit | std::ios_base::eofbit); // Do some stuff that might cause stream to throw... } catch (const std::exception &ex) { // error handling as needed... // if not a stream error, restore settings that // the caller expects, then re-throw the original error if (!dynamic_cast<const std::ios_base::failure*>(&ex)) { stream.exceptions(originalExceptionSettings); throw; } } catch (...) { // error handling as needed... // Unknown error but not a stream error, restore settings // that the caller expects, then re-throw the original error stream.exceptions(originalExceptionSettings); throw; } // restore settings that the caller expects (may throw what caller wants!) stream.exceptions(originalExceptionSettings); }
71,890,413
71,891,017
How to understand "well formed when treated as an unevaluated operand"
As per the document, which says that[emphasis mine]: template <class Fn, class... ArgTypes> struct is_invocable; Determines whether Fn can be invoked with the arguments ArgTypes.... Formally, determines whether INVOKE(declval<Fn>(), declval<ArgTypes>()...) is well formed when treated as an unevaluated operand, where INVOKE is the operation defined in Callable. How to understand the statement in bold? What's "an unevaluated operand"? Maybe, a simple example helps to fully understand this matter.
How to understand the statement in bold? What's "an unevaluated operand"? An unevaluated operand is an operand that is not evaluated. Maybe, a simple example helps to fully understand this matter. void g(auto) requires false; void f(auto x) { g(x); } static_assert(is_invocable_v<decltype(f<int>), int>); f(0); // ill-formed Considering the above example, since is_invocable is not evaluated, g(x) in f will not actually be invoked either, so the static_assert will pass. Since f(0) is actually evaluated, which will fail because g(0) fails to satisfy the constraints.
71,890,415
71,890,468
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) on vector insert
I am trying to insert an element into a vector using the .insert(<#const_iterator __position#>, <#const_reference __x#>) This is my code: hpp: typedef int elementType; class Heap{ private: std::vector<elementType> myVecrtor; int mySize = 1; //The minimum size is 1 since the first element is a dummy. public: Heap(); void insert(elementType const item); }; cpp: void Heap::insert(elementType item){ typename std::vector<elementType>::iterator it; for(int i = 0; i <= mySize; i++){ it++; } myVecrtor.insert(it, item); mySize++; } When calling the method inside the main: #include <iostream> #include "Heap.hpp" int main(int argc, const char * argv[]) { Heap h; h.insert(10); } The debugger gives me a successful run then gives me an error inside the vector hpp file: void __construct_backward_with_exception_guarantees(_Alloc&, _Tp* __begin1, _Tp* __end1, _Tp*& __end2) { ptrdiff_t _Np = __end1 - __begin1; __end2 -= _Np; if (_Np > 0) _VSTD::memcpy(__end2, __begin1, _Np * sizeof(_Tp));//The error is given here } error:Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) I have no idea why I am getting this. Any help would be appreciated.
typename std::vector<elementType>::iterator it; This statement declares a vector iterator. As you can see here, it is completely uninitalized. It is not initialized to anything. for(int i = 0; i <= mySize; i++){ it++; } And this sequence increments the iterator some unspecified number of times. Since it is not initialized, this is undefined behavior. myVecrtor.insert(it, item); Attempting to insert something into a vector using an iterator that has never been initialized, and after being not-initialized it gets incremented an unspecified amount of times, is not going to go very far. Heap's constructor is not shown, so it is unclear if its constructor initializes the vector's contents, in any form or fashion. But that seems unlikely and this mySize appears to be initialized to 1. Therefore this for loop will iterate at least once, and most likely not once but twice. If the vector is, indeed empty, then even if it is correctly initialized, its only possible valid value will be either begin() or end() (with both being equivalent for a completely empty vector). As such, incrementing the iterator, even if it's properly initialized, will be undefined behavior. To summarize, there are multiple conceptual flaws in the shown code: All iterators must be initialized before they can be used in any way, incremented or decrementing, dereferenced, or in any other way. The only possible valid iterator for a completely empty vector cannot be incremented or decremented. If insert()'s goal is to append a new value to a vector, nothing of what the shown code is doing is needed, in any form or fashion. That's because this just happens to be exactly what std::vector's very own push_back() does! No iterator, or incrementing is required!
71,890,509
71,890,527
Why does creating an object in a function and returning it call copy construct and move assignment operator?
#include <iostream> class MyClass { public: MyClass() = default; MyClass& operator=(const MyClass& other) { std::cout << "copy\n"; i = other.i; return *this; } MyClass& operator=(MyClass&& other) noexcept { std::cout << "Move\n"; i = other.i; return *this; } MyClass(const MyClass& other) { std::cout << "copy construct\n"; i = other.i; }; int i = 10; }; MyClass function() { MyClass c{}; return c; } int main() { MyClass c1; MyClass c2; c1 = function(); } Why does the line c1 = function(); call copy constructor and move assignment operator? Where exactly does copy construction happen? I can understand that the contents of local variable c gets moved since it's in a local scope and it's going to be destroyed anyway. But where does copy construction happen? And if I change function to: MyClass function() { return MyClass{}; } It only calls move constructor.
I can understand that the contents of local variable c gets moved This is incorrect. The declared class does not have a move constructor, so it cannot be moved, only copied into the caller's context. Which is what happens. That's step 1. Step 2 invokes the move-assignment operator, in the caller's context, to move the temporary into c1. Note that even if the class has a move constructor, this is a named return value, which does not have guaranteed copy elision. So the object might still end up moved, and assigned. And if copy elision takes place the object will still be move-assigned.
71,890,570
71,890,582
Why is my pow function returning 0 when it's being called as a variable?
I'm new to coding and have been learning on youtube and one of the functions im learning is the pow function. When i call the function in a cout directly, it outputs the correct value, but when i use a variable to call it, it outputs 0 as the value. Am i missing a step in the declaration of the function? #include <iostream> #include <cmath> using std::cout; using std::endl; using std::cin; int main() { int base, exponent; double power = pow(base, exponent); cout << "What base do you have? " << endl; cin >> base; cout << "What exponent do you have? " << endl; cin >> exponent; cout << power << endl; return 0; }
Call double power = pow(base, exponent); after base, exponent are assigned values cin >> exponent; double power = pow(base, exponent); cout << power << endl;
71,890,603
71,890,741
How do I redirect stderr to /dev/null in C++?
#include <cstddef> #include <iostream> #include <fstream> #include <string> using namespace std; int main() { //read the lines from the piped file using cin string response; int i = 0; while (getline(cin, response)) { //if the response is empty, stop if (response.empty()) { break; } //Write each odd line (1,3, etc..) to stderr (cerr) //Write each even line (2,4. etc..) to stdout (cout) if (i % 2 != 1) { //send odd to stderr cerr << "err: " << response << endl; } else { //send even to stdout cout << "out: " << response << endl; } i++; } return 0; } I want to redirect stderr to /dev/null, how would I go about doing so? I'm new to C++ and trying to learn by practicing, however, I'm not easily able to find an answer that fits my existing program.
Besides the excellent commentary above, it is pretty easy to make a “null” streambuf sink in C++. #include <iostream> struct null_streambuf: public std::streambuf { using int_type = std::streambuf::int_type; using traits = std::streambuf::traits_type; virtual int_type overflow( int_type value ) override { return value; } }; To use it, just set the rdbuf: int main() { std::cerr.rdbuf( new null_streambuf ); std::cerr << "Does not print!\n"; } If you wish to be able to turn it off and on, you will have to remember the original and restore it, not forgetting to delete the new null_streambuf. int main() { std::cerr << "Prints!\n"; auto original_cerr_streambuf = std::cerr.rdbuf( new null_streambuf ); std::cerr << "Does not print.\n"; delete std::cerr.rdbuf( original_cerr_streambuf ); std::cerr << "Prints again!\n"; } This does have the objective effect of being compiled to code, which I suspect is the advantage you are looking for: the ability to dynamically enable and disable diagnostic output. This is, however, the usual function of a debug build, where you use the DEBUG macro to decide whether or not to compile something (such as error output operations) into the final executable. Keep in mind that this does not disable output on standard error via other means, but only through cerr.
71,891,002
71,891,075
Template instances with different return types
As per this document, which says that[emphasis mine]: The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here. It's amazing that this code snippet works! #include <type_traits> #include <iostream> template <typename T> T foo(){return T{};} template<> int foo(){std::cout << "int" << std::endl; return int{};} template<> double foo(){std::cout << "double" << std::endl; return double{};} int main() { foo<int>(); foo<double>(); foo<bool>(); } You see, the code snippet below does not compile indeed(If you have a question in it, please see the quotation at the beginning of the post): #include <type_traits> #include <iostream> int foo(){std::cout << "int" << std::endl; return int{};} double foo(){std::cout << "double" << std::endl; return double{};} int main() { }
In the first snippet, you're providing two specializations of the more general primary function template foo<T>. In particular, you have provided specializations for T=int and T=double meaning we'll have foo<int> and foo<double> which are different from each other. So in the 1st snippet there is no function overloading since the name are not the same in the first place. One is foo<int> and other is foo<double>. From function overloading 11.3.5.5 A single name can be used for several different functions in a single scope; this is function overloading. More importantly, note that specializations instantiate a template; they do not overload it. As a result, specializations do not affect function matching. Consider the following examples to illustrate the point: Example 1 template <typename T> T foo(T a, T b){return T{};} template <> int foo(int a, int b){return 4;} int main() { foo(5, 7.0); // error: no matching function for call to ‘foo(int, double)’ } Example 2 template <typename T> T foo(T a, T b){return T{};} int foo(int a, int b){return 4;} int main() { foo(5, 7.0); // works fine } On the other hand, in the 2nd snippet since the name of the function is the same, thus it is function overloading and we can't overload ordinary function just on the return type. From Overloadable declarations Function declarations that differ only in the return type, the exception specification, or both cannot be overloaded.
71,891,113
71,891,153
prefix operator behaviour in c++ when used multiple times in a statement
I am not able to understand prefix operator behaviour in scenario when it is used multiple times in a statement . Here is an example code to illustrate my problem #include<iostream> using namespace std; int main() { int a=2,adup=2; int b = (++a) * (++a); cout<<endl<<"square of "<<a<<" is "<<b<<endl;//i get 16 int c = (++adup) * (++adup) * (++adup); cout<<endl<<"adup is "<<adup<<" and c is "<<c<<endl;// i get 80 return 0; } Save above file as code.cpp and run 'gcc code.cpp -lstdc++' to verify. It seems that in first case 2 was incremented twice then b = 4x4 But in second case I was hoping 5x5x5 on the lines of above but we ge 4x4x5 . How can that be explained ? Thanks. BTW , I found that postfix operator seems logical . it simply updates value and uses it next time variable is used even when in same statement . After reading answers my conclusion is - Can it be said that using pre or post operation on same variable more than once in a statement will be undefined behaviour regardless of anything on LHS of expression ?
Earlier iterations of C++ (and C for that matter) had the concept of sequence points, where it was guaranteed all previous "things" (like the i++ side effect of evaluating that expression) would have completed. This was replaced at some point with more tightly described "sequencing" along the lines of: if A is sequenced before B, A will be fully done before B starts. if A is sequenced after B, A will be not start until B is fully done. if A and B are indeterminately sequenced, one will complete fully before the other starts, but you won't necessarily know which one went first. if A and B are unsequenced, either may start first, and they may even overlap. From C++20, [intro.execution], point 10 applies to your code: Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. That means that the individual bits of that full expression may happen in any order, and even overlap, resulting in differing results to what you may think is correct. In other words, if you want deterministic code, don't do that. And, despite your findings that the "postfix operator seems logical, it simply updates [the] value and uses it next time [the] variable is used, even when in same statement", that is actually incorrect. While that may happen in a particular case, the expression (a++) * (a++) is equally as non-determinstic as (++a) * (++a). If you want to guarantee the sequencing of your operations, you can use more explicit code like: // int b = (++a) * (++a); // with pre-increment immediately before EACH use of a: int b = (a + 1) * (a + 2); a += 2; // or: int b = ++a; b = ++a * b There are always ways to achieve the same effect with code that isn't subject to indeterminate results, in the same number of lines of code if you concern yourself with that sort of metric, albeit with two statements on a single line :-)
71,891,197
71,891,270
c++ type trait to detect if any function argument is reference
I need a type trait to detect if any of the function parameters of a template argument is a reference. This code is working, the trait is "is_any_param_reference" and the static_assert is trigged the signature of foo is changed form void foo( std::string s, int i) to void foo( std::string& s, int i) (first parameter converted to reference). But id did not work with lambdas... It does not compile if I use: int main() { auto foo2 = [](std::string s, int i){ std::cout << s << " " << i << std::endl; }; some_function( foo2, s, i ); } Any idea of how to generate a type traits that works also for lambda? Thanks!! #include <iostream> #include <string> #include <type_traits> using namespace std; template<typename ... A> struct any_is_reference : std::false_type {}; template<typename A, typename ... P> struct any_is_reference<A, P...>: std::conditional_t< std::is_reference<A>::value , std::true_type, any_is_reference<P...> >::type{}; template<typename Sig> struct is_any_param_reference; template<typename R, typename...Args> struct is_any_param_reference<R(*)(Args...)>: any_is_reference<Args...>{}; template< typename Sig > inline constexpr bool is_any_param_reference_v = is_any_param_reference<Sig>::value; template< typename F , typename ... Args> void some_function( F f, Args... args) { static_assert(!is_any_param_reference< F >::value, "FUNCTION MUST NOT HAVE PARAMETERS BY REFERENCE"); f(args...); } void foo( std::string s, int i) { std::cout << s << " " << i << std::endl; } int main() { const std::string s = "Hello"; int i = 0; some_function(foo, s, i); }
template<typename T> struct is_any_param_reference : is_any_param_reference<decltype(&T::operator())>{}; template<typename R, typename...Args> struct is_any_param_reference<R(*)(Args...)>: any_is_reference<Args...>{}; template<typename T, typename R, typename...Args> struct is_any_param_reference<R(T::*)(Args...)>: any_is_reference<Args...>{}; template<typename T, typename R, typename...Args> struct is_any_param_reference<R(T::*)(Args...) const>: any_is_reference<Args...>{}; Demo. The primary template assumes that its argument is a class providing operator() (e.g. a lambda). Then there are specializations for a plain function pointer as well as a pointer-to-member-function. The primary template effectively delegates to this last specialization.
71,891,633
71,892,779
In C++ why is it when I reassign a reference variable to a different reference variable it creates a copy of that variable instead?
struct configfs { int & foo; configfs(int & foo_) : foo(foo_) {} void set_foo(int & foo_) { foo = foo_; } }; int main() { int a = 1; configfs conf(a); a = 3; std::cout << conf.foo; // 3 std::cout << a; // 3 int b = 2; conf.set_foo(b); b = 9; std::cout << conf.foo; // 2 std::cout << b; // 9 return 0; } When I initialize configfs with int a and then alter a in the main function it also alters configfs.foo . But when I reassign configfs.foo to a new reference and alter that reference in the main function, the behavior is different. Why? Is there a way so that when I run conf.set_foo(b) and then alter b in the main scope, it also alters conf.foo as well?
When you wrote: conf.set_foo(b); The following things happen: Member function set_foo is called on the object conf. Moreover, the reference parameter named foo_ is bound the the argument named b. That is, b is passed by reference. Next, the statement foo = foo_; is encountered. This is an assigment statement and not an initialization. What this does is that it assigns the value referred to by the parameter foo_ to the object referred to by the data member foo(which is nothing but a here). You can confirm this by adding std::cout<<a; after the call to set_foo as shown below: int b = 2; conf.set_foo(b); std::cout<<a<<std::endl; //prints 2 This is because operations on a reference are actually operations on the object to which the reference is bound. This means that when we assign to a reference, we are assigning to the object to which the reference is bound. When we fetch the value of a reference, we are really fetching the value of the object to which the reference is bound. Note: Once initialized, a reference remains bound to its initial object. There is no way to rebind a reference to refer to a different object.
71,891,653
71,891,685
Copy lambda which captures moved object
Why this code snippet does not compile? #include <functional> #include <iostream> #include <memory> int main() { std::unique_ptr<int> uniq_ptr(new int{6}); auto foo_a = [&uniq_ptr]{std::cout << *uniq_ptr << std::endl;}; std::bind(foo_a)(); //works foo_a(); //works auto foo_b = [up = std::move(uniq_ptr)]()mutable{*up = 5; std::cout << *up << std::endl;}; foo_b(); //works; #ifdef CHOOSE_1 auto foo_b1 = foo_b; //Surprised! I think `up` could be copied.But the compiler complains: Error: use of deleted function 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)' #else std::bind(foo_b); //Same error! #endif } For auto foo_b = [up = std::move(uniq_ptr)]()mutable{//...}, I think foo_b could be copied since up a rvalue, and it could be copied by move constructor.
[up = std::move(uniq_ptr)] just moves uniq_ptr to a member variable of the lambda. std::bind will internally construct a copy of foo_b. Since foo_b contains a unique_ptr that is not copyable, foo_b itself is not copyable. You should move foo_b into std::bind: std::bind(std::move(foo_b)); Or move foo_b into foo_b1 auto foo_b1 = std::move(foo_b);
71,891,761
71,892,785
what is the difference between vector.push_back() and inserting element like Vector[index]?
class Solution { public: vector<int> getConcatenation(vector<int>& nums) { int n=nums.size(); vector<int> ans(2*n); for(int i=0;i<2*n;i++) { if(i<n) { ans.push_back(nums[i]); } else { ans.push_back(nums[i-n]); } } return ans; } }; This above code is not giving appropriate ans. while below code is working fine. class Solution { public: vector<int> getConcatenation(vector<int>& nums) { int n=nums.size(); vector<int> ans(2*n); for(int i=0;i<2*n;i++) { if(i<n) { ans[i]=nums[i]; } else { ans[i]=nums[i-n]; } } return ans; } };
When you create the vector you have specified a size already (usually not done with vectors) so your vector already filled with ints that have been set to 0. So when you use ans[i] = nums[i]; you are simply editing one of the already existing elements stored in the vector. Usually when you create a vector you create it as an empty one by doing vector<int> ans; or vector<int>* ans = new vector<int>(); (if you want to create it on the heap) and then add a new element to it using ans.push_back(value); which will add the element to the back/end of the vector.
71,892,458
71,892,512
static class member not recognised but only for new versions of C++ compile
The static class member static_member not recognised in the following code. However, it works on older versions of the compiler. The compiler I use is based on clang. class my_class { public: static int static_member; }; int main() { my_class::static_member = 0; } To reproduce the error, save above file as c1.cpp and run: VER_TAG=latest # or VER_TAG=3.1.8 docker run --rm -v $(pwd):/src emscripten/emsdk::$VER_TAG emcc /src/c1.cpp Leads to error: wasm-ld: error: /tmp/emscripten_temp_o3wmmq8k/c1_0.o: undefined symbol: my_class::static_member However, if I use VER_TAG=2.0.22 (earlier release of the compiler), it works fine. Is there anything wrong with my code? Or is it related to compiler implementation?
From static data member's definition's documentation: The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared. So we have to first provide an out-of class definition for the static data member as shown below: class my_class { public: static int static_member;//this is a declaration }; int my_class::static_member = 0;//this is a definition int main() { std::cout<<my_class::static_member<<std::endl; } From C++17 onwards we can use inline keyword so that we'll not need an out-of-class definition for the static data member anymore: class my_class { public: inline static int static_member = 0; // this is a definition }; //nothing needed here int main() { std::cout<<my_class::static_member; // use the static_member here }
71,892,557
71,910,614
WHY Qt reports **_resource_res.o Error 1?
I was using Qt Creator on my Windows11 virtual machine,and I cloned my team's repository from github.I did no changes to it at all, and when I tried to build it reports error. I asked my teammates to try building it, and they all finished the build without any problem. Confusingly I uninstalled the Qt and install it again. This time it works, but when I pulled the latest version with git, It reports the error again. `:-1: error: [Makefile.Debug:102: debug/ChineseCheckers_resource_res.o] Error 1` I wonder what on earth was wrong. More info: My teammates are using windows11 too. Their Qt Creator reports no error. I have tried to delete build-ChineseCheckers-Desktop_Qt_6_2_4_MinGW_64_bit-Debug folder, or simply delete ChineseCheckers.pro.user, but none of these worked. The files are stored in an USB device. It reports error after I pulled from github and build.
I have solved it by myself. I had a missing resource file: "logo.ico". It seems that my teammates forget to upload that image, so it can be built on their machine, but mine failed. :/ Besides, I moved the file from USB device to the desktop, but I think that's not the point. Anyway, at least one of these works.
71,892,807
71,893,041
"no matching function for call to" when having a function pointer with template arguments as a template argument
I'm writing a template wrapper function that can be applied to a functions with different number/types of arguments. I have some code that works but I'm trying to change more arguments into template parameters. The working code: #include <iostream> int func0(bool b) { return b ? 1 : 2; } //There is a few more funcX... template<typename ...ARGS> int wrapper(int (*func)(ARGS...), ARGS... args) { return (*func)(args...) * 10; } int wrappedFunc0(bool b) { return wrapper<bool>(func0, b); } int main() { std::cout << wrappedFunc0(true) << std::endl; return 0; } Now I want int (*func)(ARGS...) to also be a template parameter. (It's for performance reasons. I want the pointer to be backed into the wrapper, because the way I'm using it prevents the compiler from optimizing it out.) Here is what I came up with (The only difference is I've changed the one argument into a template parameter.): #include <iostream> int func0(bool b) { return b ? 1 : 2; } //There is a few more funcX... template<typename ...ARGS, int (*FUNC)(ARGS...)> int wrapper(ARGS... args) { return (*FUNC)(args...) * 10; } int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); } int main() { std::cout << wrappedFunc0(true) << std::endl; return 0; } This doesn't compile. It shows: <source>: In function 'int wrappedFunc0(bool)': <source>:9:55: error: no matching function for call to 'wrapper<bool, func0>(bool&)' 9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); } | ~~~~~~~~~~~~~~~~~~~~^~~ <source>:7:5: note: candidate: 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)' 7 | int wrapper(ARGS... args) { return (*FUNC)(args...) * 10; } | ^~~~~~~ <source>:7:5: note: template argument deduction/substitution failed: <source>:9:55: error: type/value mismatch at argument 1 in template parameter list for 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)' 9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); } | ~~~~~~~~~~~~~~~~~~~~^~~ <source>:9:55: note: expected a type, got 'func0' ASM generation compiler returned: 1 <source>: In function 'int wrappedFunc0(bool)': <source>:9:55: error: no matching function for call to 'wrapper<bool, func0>(bool&)' 9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); } | ~~~~~~~~~~~~~~~~~~~~^~~ <source>:7:5: note: candidate: 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)' 7 | int wrapper(ARGS... args) { return (*FUNC)(args...) * 10; } | ^~~~~~~ <source>:7:5: note: template argument deduction/substitution failed: <source>:9:55: error: type/value mismatch at argument 1 in template parameter list for 'template<class ... ARGS, int (* FUNC)(ARGS ...)> int wrapper(ARGS ...)' 9 | int wrappedFunc0(bool b) { return wrapper<bool, func0>(b); } | ~~~~~~~~~~~~~~~~~~~~^~~ <source>:9:55: note: expected a type, got 'func0' Execution build compiler returned: 1 (link to the compiler explorer) It looks like a problem with the compiler to me, but GCC and Clang agree on it so maybe it isn't. Anyway, how can I make this template compile correctly with templated pointer to a function? EDIT: Addressing the duplicate flag Compilation issue with instantiating function template I think the core of the problem in that question is the same as in mine, however, it lacks a solution that allows passing the pointer to function (not only its type) as a template parameter.
This doesn't work because a pack parameter (the one including ...) consumes all remaining arguments. All arguments following it can't be specified explicitly and must be deduced. Normally you write such wrappers like this: template <typename F, typename ...P> int wrapper(F &&func, P &&... params) { return std::forward<F>(func)(std::forward<P>(params)...) * 10; } (And if the function is called more than once inside of the wrapper, all calls except the last can't use std::forward.) This will pass the function by reference, which should be exactly the same as using a function pointer, but I have no reasons to believe that it would stop the compiler from optimizing it. You can force the function to be encoded in the template argument by passing std::integral_constant<decltype(&func0), func0>{} instead of func0, but again, I don't think it's going to change anything.
71,893,029
71,893,129
How can I assign the integers in an input like 1.2.3 to variables in C++?
Here is an example of what I mean. Input: 10.20.50 a = 10 b = 20 c = 50
you will need to store the input in a string or char[] and then iterate over the string or char[] and write some code that will identify the separate parts of the input and convert them to ints using stoi(). this would work but just an example (and i think it will not print the final number unless the input is ended with "." but this should give you an idea of what you could do. std::string i = ""; std::cin >> i; std::string buffer = ""; for (auto c : i) { if (c != '.') { buffer += c; } else { int num = std::stoi(buffer); buffer = ""; std::cout << num << ", "; } }
71,893,273
71,893,321
First input number turns 0 after the executing the codes
I'm writing a program to generate a line equation using given slope and y-intercept, below are the codes i extracted from my program: int m,c; cout<<"m >>"; cin>>m; cout<<endl; cout<<"c >>"; cin>>c; cout<<endl; if (m=0){ cout<<"y= "<<c; } else if(m>0){ if (c>0){ cout<<"y="<<m<<"x+"<<c; } else if (c<0){ cout<<"y="<<m<<"x"<<c; } else { cout<<"y="<<m; } } else { if (c>0){ cout<<"y="<<m<<"x+"<<c; } else if (c<0){ cout<<"y="<<m<<"x"<<c; } else { cout<<"y="<<m; } } When I input 8 8, the output is as follow: y=0x+8 When I input 8 -8, the output is as follow: y=0x-8 When I input 0 5, the output is as follow: y=0x+5 Even when I try adjust the front part of my codes to cin>>m>>c; It doesnt seem helping, which part of my codes has given such error ?
You are setting m to 0 in the first if check. Should be using == not =.
71,893,308
71,893,684
MinGW undefined reference libcurl
So i have written an app in c++ to download mp3s from the web using a list. It uses libcurl to download them. I am on linux. Compiling with g++ main.cpp -lcurl -o word2mp3 works fine. I need an windows executable, but running x86_64-w64-mingw32-g++ main.cpp -o wordtest returns the undefined reference to `__imp_curl_easy_init' followed by the other curl functions. Adding -lcurl to the command also gives an error saying that curl isn't found. I've tried and searched everywhere, no luck, I'm a beginner. Link to my github repo: https://github.com/sharpclone/Word2Mp3
You need to compile libcurl with MinGW, or find a precompiled one. The one you installed to compile your app on Linux was compiled with a Linux compiler, and wouldn't work with MinGW. MSYS2 repos have a bunch of precompiled libraries for different flavors of MinGW. I've made a script to automatically download those libraries, since their package manager only works on Windows. git clone https://github.com/holyblackcat/quasi-msys2 cd quasi-msys2 make install _gcc _curl env/shell.sh cd .. git clone https://github.com/sharpclone/Word2Mp3 cd Word2Mp3/ win-clang++ main.cpp -lcurl -o word2mp3 This doesn't rely on an external MinGW installation, and only requires Clang (and LLD) to be installed (a regular Clang for Linux, unlike GCC you don't need to install a special version of it to cross-compile). Or, if you prefer your existing compiler, you can stop at make install _curl, then manually specify the path to the installed library, normally -Lquasi-msys2/root/mingw64/lib. You just need to make sure the MSYS2 repo you're using matches your compiler.
71,893,568
71,893,659
How does std::map's emplace() avoid premature construction?
I am confused about std::maps's implementation of emplace(). emplace() is a variadic template function with the following declaration: template <class Args...> iterator emplace( Args&&... args ); As far as I understand, emplace() completely avoids constructing its value_type, i.e., std::pair<const key_type,mapped_type>, and instead constructs the object in-place. I assume this means that the object is constructed only once, the moment that the new map node is created. The object is never copied or moved. What I don't understand is how std::map finds the correct place to add the new entry before constructing the key-value pair. As far as I see, std::map needs access to the key but the key is contained within args and only accessible after construction of the key-value pair. I must be misunderstanding some aspect of emplace(). Does std::map actually avoid construction of the key-value pair? If so, how does it avoid move/copy operations? Or is there another way to access the key in args?
emplace constructs the pair in-place forwarding the arguments to its constructor; it does not avoid element_type construction, it just avoids one copy of a useless temporary pair compared to insert. In this regard, it's just as for the other containers: emplace is like insert, but instead if receiving a ready-made element_type to copy or move inside the container, it receives the arguments to construct element_type in its target location. To further clarify: if you call emplace(key, value) key and value are copied/moved anyhow when constructing the pair. It's just that, if you did insert(make_pair(key, value)), not only key and value would have beem copied/moved when creating the temporary pair argument, but the pair itself would have then needed to be moved in the map node. I don't think that is what OP intends to ask for. The intended question to me seems to be how std::map can find the correct location to insert the new element if it can't construct the key prior to searching for the location, e.g. if the first argument to emplace is not the key type itself. In that case for an std::map there's not much of a problem: first you can construct a node (which contains the pair and the various pointers to other nodes, and has its own allocation on the heap), and then you can put it in the right place in the RB tree (which boils down to just a couple of pointers assignment).
71,893,745
71,895,697
cannot gate index of arrival gate of new message in omnet++ 5.6.1
I am following the tictoc tutorial and I want to change the code of tictoc12 so that I'll get the index of the gate from which we received the message so that the message will not send out from the same gate. This is my handleMesssage() function: void Txc12::handleMessage(cMessage *msg) { if (getIndex() == 3) { // Message arrived. EV << "Message " << msg << " arrived.\n"; delete msg; } else { int arrivalGate = msg->getArrivalGate()->getIndex(); EV << "arrival gate: " << arrivalGate << "\n"; // We need to forward the message. forwardMessage(msg); } } and this is the error that i receive: Simulation terminated with exit code: -1073741819 Working directory: D:/omnetpp-5.6.1/samples/tictoc Command line: tictoc.exe -m -u Qtenv omnetpp.ini Environment variables: PATH=;D:\omnetpp-5.6.1\bin;D:\omnetpp-5.6.1\tools\win64\mingw64\bin;D:\omnetpp-5.6.1\tools\win64\usr\bin;;D:/omnetpp-5.6.1/ide/jre/bin/server;D:/omnetpp-5.6.1/ide/jre/bin;D:/omnetpp-5.6.1/ide/jre/lib/amd64;.;D:\omnetpp-5.6.1\bin;D:\omnetpp-5.6.1\tools\win64\mingw64\bin;D:\omnetpp-5.6.1\tools\win64\usr\local\bin;D:\omnetpp-5.6.1\tools\win64\usr\bin;D:\omnetpp-5.6.1\tools\win64\usr\bin;C:\Windows\System32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;D:\omnetpp-5.6.1\tools\win64\usr\bin\site_perl;D:\omnetpp-5.6.1\tools\win64\usr\bin\vendor_perl;D:\omnetpp-5.6.1\tools\win64\usr\bin\core_perl;D:\omnetpp-5.6.1; OMNETPP_ROOT=D:/omnetpp-5.6.1/ OMNETPP_IMAGE_PATH=D:\omnetpp-5.6.1\images Does anyone know what I'm doing wrong?
The value of exit code -1073741819 is equal to 0xC0000005 - an access violation. However, handleMessage() presented by you cannot be source of that error. I strongly suggest using debugger to find the lines that cause that error. To do this: Compile your project in debug mode. In your omnetpp.ini set: debug-on-errors = true Start your simulation in debug (i.e. Run | Debug) The execution of the simulation will stop just before the line that causes an exception. Reference: TicToc Tutorial - 2.3 Debugging
71,893,860
71,900,918
New Sec-* headers in WebView2
Working with MS WebView2 in C++ I can see a number of "Sec-*"-headers if visiting https://manytools.org/http-html-text/http-request-headers/ Example of a few: Sec-Fetch-Dest document Sec-Fetch-User ?1 Sec-Fetch-Mode navigate Sec-Fetch-Site none Sec-Ch-Ua-Mobile ?0 Sec-Ch-Ua "Not A;Brand";v="99", "Chromium";v="100", "Microsoft Edge";v="100", "Microsoft Edge WebView2";v="100" These new headers are mentioned in https://wicg.github.io/ua-client-hints/ Is there any way to access/edit those headers, preferably in C++? It's possible to disable the Sec-Ch headers with a command line option: --disable-features=UserAgentClientHint and to do that from C++: Microsoft::WRL::ComPtr<CoreWebView2EnvironmentOptions> options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>(); options->put_AdditionalBrowserArguments(L"--disable-features=UserAgentClientHint"); However, I want to be able to edit those values. Further googling revealed this page which I guess answers this post: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
You are correct that the sec-* headers are part of the "forbidden header" lists. But they are forbidden for client code like the JS that runs on the user-agent. But user-agents like the browser can set those fields. You can change some of the sec-* headers inside a callback added to add_WebResourceRequested. Some fields like Sec-Fetch-Site get overwritten afterwards, others like Sec-Fetch-Mode can be set, but can't be deleted because they will get a default value, if not set after the WebResourceRequestedEvent. But you can change most of the sec-ch ones like this: NOTE: this code is only to demonstrate the approach, it's missing a bunch of error handling EventRegistrationToken webResourceRequestedToken; webviewWindow->AddWebResourceRequestedFilter(L"*", COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL); webviewWindow->add_WebResourceRequested( Callback<ICoreWebView2WebResourceRequestedEventHandler>([](ICoreWebView2* sender, ICoreWebView2WebResourceRequestedEventArgs* args) { COREWEBVIEW2_WEB_RESOURCE_CONTEXT resourceContext; args->get_ResourceContext(&resourceContext); ICoreWebView2WebResourceRequest* req = nullptr; ICoreWebView2HttpRequestHeaders* headers = nullptr; ICoreWebView2HttpHeadersCollectionIterator* iter = nullptr; args->get_Request(&req); req->get_Headers(&headers); headers->GetIterator(&iter); BOOL hasCurrent = FALSE; iter->get_HasCurrentHeader(&hasCurrent); std::vector<std::wstring> headersToDelete; std::wstring secChPrefix = L"sec-ch"; while (hasCurrent) { LPWSTR name = nullptr, value = nullptr; iter->GetCurrentHeader(&name, &value); if (secChPrefix.compare(0, secChPrefix.size(), name, secChPrefix.size()) == 0) { headersToDelete.push_back(name); } iter->MoveNext(&hasCurrent); } for (auto header : headersToDelete) { headers->RemoveHeader(header.c_str()); } // Setting "Sec-Fetch-Site" will have no effect, will get overwritten afterwards headers->SetHeader(L"Sec-Fetch-Site", L"same-origin"); // This will work, but removing this key will just make it take the default value headers->SetHeader(L"Sec-Fetch-Mode", L"same-origin"); return S_OK; }).Get(), &webResourceRequestedToken);
71,893,987
71,894,223
Why isn't cin taking input after an invalid type is passed to the variable
It is a menu driven program and works completely fine when an int is passed to the variable options but runs into an infinite loop when char is passed. int main(){ while(true){ int options{0}; cout<<"\nYour choice >>"; cin>>options; //this line doesnt execute after any char(say r) is given as an input switch(options){ case 1:login();break; case 2:signup();break; case 3:return 0; default:cerr<<"Please enter a valid choice"<<endl; } } txt.close(); return 0; } I tried to debug and here is the problem Breakpoint 1, main () at main.cpp:16 16 cin>>options; (gdb) p options $1 = 0 (gdb) c Continuing. Your choice >>r Breakpoint 2, main () at main.cpp:17 17 switch(options){ (gdb) p options $2 = 0 (gdb) c Continuing. Breakpoint 3, main () at main.cpp:21 21 default:cerr<<"Please enter a valid choice"<<endl; (gdb) p options $3 = 0 (gdb) c Continuing. Please enter a valid choice Breakpoint 1, main () at main.cpp:16 16 cin>>options; (gdb) c Continuing. Breakpoint 2, main () at main.cpp:17 17 switch(options){ (gdb) Quit (gdb) After line 16 its going to line 17 without asking for input from user
This is because of how C++ streams work. When there is an error related to the internal logic of a stream operation (such as expecting an int but getting a char), its failbit is set. When one of the stream bits (failbit, badbit, eofbit) are set, stream operations will not do anything. To reset the iostate, you can use the clear method of the stream: std::cin.clear(); This will set goodbit on which means the other 3 bits are off and you can use the stream. To check the these bits, you can use the state methods: good(), fail(), bad(), eof() But keep in mind that the streams have a conversion operator to bool which returns !fail() so you can use streams in a boolean context: char c; while (std::cin >> c) {... And if you want to skip the bad input line, you can do this after clear(): std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); This will basically skip all characters in the stream's buffer until it reaches '\n'. The first parameter is how many characters to skip until EOF or '\n', which we will set to the max size possible.
71,894,053
71,894,331
Why does a moved class object not trigger the move constructor when bound to function parameter?
Lets say I have a non-trivial class object A that defines a copy and move constructor I move this object to a function which takes either A or A&& Now in case of foo's parameter type being A, the move constructor is called (this is to be expected as A&& is passed as an argument to the function-local A). But in case of A&&, the move constructor is not called, and in fact no constructor is called. Why? I would have assumed that this happens because of copy elision, but it also happens with the -O0 flag set for gcc. I also thought that && basically just flags an rvalue for overload resolution in the parameter list because inside the function body, it is treated as an lvalue. But this would mean that an lvalue A would bind a moved A&& and the move constructor should be called once again. What am I missing? CODE Compiled under x86-x64 gcc 11.2 #include <iostream> #include <string> #include <string.h> struct A { char * str_; A() { std::cout << "normal constructor called\n"; str_ = new char[7]; sprintf(str_, "Hello!"); } ~A(){ delete[] str_; } A(A& copy) { std::cout << "copy constructor called\n"; str_ = strdup(copy.str_); } A(A&& moved) { std::cout << "move constructor called\n"; str_ = moved.str_; moved.str_ = nullptr; } }; void foo(A&& a) { std::cout << a.str_ << "\n"; } int main() { A obj; foo(std::move(obj)); }
When foo takes A&&, you are binding to a r-value reference and not making any new A objects that need construction. This is because std::move is basically just a cast to r-value reference. When foo takes A, you are passing a r-value reference to A as a means of constructing A. Here, the move constructor is chosen as it takes A&& as its argument.
71,894,415
71,894,532
Why is there still no range-enabled reduction algorithm in std?
The only options available are std::ranges::for_each and simple range-based for loop. No counterparts for std::accumulate, std::reduce or std::inner_product. std::ranges::reduce would be enough, if it were present; inner product can be achieved combining reduce with zip. Falling back to iterator based algorithms is disappointing. Adapting reduce for personal codebase is not a big deal, but a std function is IMHO a lot more desirable. I am wondering if there is such function in std lib or on the 23 horizons. Regards, FM.
Why is there still no range-enabled reduction algorithm in std? Because they were not included in "The One Ranges Proposal" P0896 for C++20. I am wondering if there is such function ... on the 23 horizons. The expansion of ranges in C++23 has been planned in proposal P2214 "A Plan for C++23 Ranges". The proposal was divided into 3 tiers of priority. Ideally, all tiers would be part of C++23, but that depends on whether there is time for it. std::ranges::fold is a counterpart to std::accumulate and it It was planned for top tier and has been proposed in P2322 "ranges::fold". std::ranges::reduce was planned in the middle tier. std::inner_product counterpart was decided to not be included in the plan for C++23 ranges as fold and reduce were considered sufficient. can be achieved combining reduce with zip Zip views themseleves weren't in the C++20 ranges either. But they were planned in the top tier for C++23 and have been proposed in P2321 "zip".
71,895,213
71,901,609
pthread_cond_wait never returning with EOWNERDEAD
I tried sharing a mutex and a condition variable between two processes. One process owns the mutex and sets the condition variable while the other waits on the condition variable. My understanding is that the process currently holding the mutex is the "owner". When the owner app exits, a mutex lock on that specific mutex should return a EOWNERDEAD error because the mutex is robust. So far this seems to be working. But if i wait on the condition variable, EOWNERDEAD is never returned and the call is just blocking infinitely. Creating the mutex and condition variable in the "owner" process: struct InternalEvent { pthread_mutex_t lock; pthread_cond_t condSet; bool set; bool manualReset; }; pthread_mutexattr_t mutexAttr; pthread_condattr_t conditionAttr; int filedescriptor = 0; filedescriptor = ::open(name, O_RDWR | O_CREAT | O_EXCL, 0666); if (filedescriptor < 0) return false; ftruncate(filedescriptor, sizeof(InternalEvent)); pthread_mutexattr_init(&mutexAttr); pthread_mutexattr_setrobust(&mutexAttr, PTHREAD_MUTEX_ROBUST); pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_SHARED); pthread_condattr_init(&conditionAttr); pthread_condattr_setpshared(&conditionAttr, PTHREAD_PROCESS_SHARED); internalEvent = (InternalEvent*) mmap(NULL, sizeof(InternalEvent), PROT_READ | PROT_WRITE, MAP_SHARED, filedescriptor, 0); ::close(filedescriptor); pthread_mutex_init(&internalEvent->lock, &mutexAttr); pthread_cond_init(&internalEvent->condSet, &conditionAttr); internalEvent->set = false; Opening the mutex and the condition variable in another process: filedescriptor = ::open(name, O_RDWR, 0666); if (filedescriptor < 0) return false; internalEvent = (InternalEvent*) mmap(NULL, sizeof(InternalEvent), PROT_READ | PROT_WRITE, MAP_SHARED, filedescriptor, 0); ::close(filedescriptor); Setting the condition variable: int res = pthread_mutex_lock(&internalEvent->lock); if(res == EOWNERDEAD) { internalEvent->set = false; pthread_mutex_consistent(&internalEvent->lock); } if(!internalEvent->set) pthread_cond_broadcast(&internalEvent->condSet); internalEvent->set = true; pthread_mutex_unlock(&internalEvent->lock); Waiting for the condition variable: int res = pthread_mutex_lock(&internalEvent->lock); while (!internalEvent->set && res == 0) { res = pthread_cond_wait(&internalEvent->condSet, &internalEvent->lock); } if(res == 0 && !internalEvent->manualReset) { internalEvent->set = false; } pthread_mutex_unlock(&internalEvent->lock); return res == 0; My question is, how can i detect the termination/crashing/exiting of the "owner" process in the blocking pthread_cond_wait call? I dont really need to restore the mutexes or the condition variables state. I only want to detect the termination. Edit: Is there maybe some other way to wait for multiple mutexes in one blocking call? Then i could simply have a mutex per process and one mutex for the condition variable
EOWNERDEAD is a defined return value for pthread_mutex_lock(), not for pthread_cond_wait(). This is perhaps because CVs do not have owners in the same sense that mutexes do. In any case, there is no reason to expect a wait on a CV ever to return EOWNERDEAD. Moreover, a thread waiting for on CV specifically does not hold the associated mutex for the duration, and will not try to reacquire it until the wait is over. If the CV isn't signaled then there isn't any reason for the thread even to notice that the mutex owner is dead.* The bottom line is that POSIX does not define robust condition variables in the same sense that it defines robust mutexes, and using a robust mutex with a CV does not impart robustness on the CV. So, how can i detect the termination/crashing/exiting of the "owner" process in the blocking pthread_cond_wait call? You can't. Condition variables do not have that capability. If you're not satisfied with the resulting risk of failure of one process causing a hang in another then you have several options, among them: use threads instead of processes; use pthread_cond_timedwait() instead of pthread_cond_wait(), and abort or attempt recovery if the wait times out; use a second thread in the waiting process to monitor the state of the other cooperating process(es), and to take corrective action when necessary. *And that is potentially a more fundamental issue here. Is the process that dies while holding the mutex the (only) one that you expect to signal the CV? If so, then you're never going to see that signal in your failure case.
71,895,283
71,895,302
How to use spaceship <=> operator with strcmp style function?
Suppose I have a C library with a struct cat, and a function compare(cat a, cat b) which returns an integer according for following rules :- if a < b then returns -1 if a = b then returns 0 if a > b then returns +1 I am writing c++ wrapper (say catxx, with ct as C struct member) for this library and would like to use the new C++20 spaceship operator. bool operator == (catxx& a, catxx& b) { return !compare(a.ct, b.ct); } auto operator <=> (catxx& a, catxx& b) { int result = compare(a.ct, b.ct); return /*what ?*/; } How would I do this ? I am unable to understand the ordering concept. What if I had to use custom if else instead of compare() ? What exactly is return type of operator<=> ? What do weak_ordering, partial ordering etc. mean ?
From cppreference: The three-way comparison operator expressions have the form lhs <=> rhs The expression returns an object such that (a <=> b) < 0 if lhs < rhs (a <=> b) > 0 if lhs > rhs (a <=> b) == 0 if lhs and rhs are equal/equivalent. So you can just simply do auto operator <=> (catxx& a, catxx& b) { return compare(a.ct, b.ct) <=> 0; } Since the operands are integral type, the operator yields a prvalue of type std::strong_ordering.
71,895,330
71,895,351
Why can't a function that has heap memory passed to it delete it in c++?
I tried to make a function that could delete memory on a int pointer. Unfortunately, it did not succeed. I feel like I made a mistake. Can someone help me find it? #include <iostream> void clean(int * x){ delete x; x=nullptr; } int main() { int * integer = new int; clean(integer); if(integer){ std::cout<<"Clean Failed\n"; } else{ std::cout<<"Clean Succeeded\n"; } }
Your clean function actually does deallocate the memory. But it doesn't update the pointer passed to it. Change clear to accept the pointer by refernce to fix the problem: void clean(int *& x) { delete x; x = nullptr; } Some more information: Parameters in C/C++ are actually always passed by value. In your original code, the pointer value (i.e. the address stored in it) is passed to clean. When you change it to int *& x what is passed is a refernce to the pointer (which is actually similar semantic-wise to int ** x). I.e. it's the address of the pointer itself, not the address stored in it. Using the address of the pointer, the function clear can modify it and set it to nullptr.
71,896,829
71,897,131
c++ using std::copy to copy an istream to a char* buffer
Is there a way to copy a std::istream to a buffer of data accessed by a "data()" method which returns a char*? For instance, the below code example. It results in a segfault. I know I could use std::back_inserter in this example, but my goal is not to copy to a vector ultimately. #include <sstream> #include <algorithm> #include <iterator> #include <vector> int main() { std::vector<char> vec; std::istringstream ss("foobar"); std::copy(std::istream_iterator<char>(ss), std::istream_iterator<char> (),vec.data()); }
No problem to copy provided enough storage is allocated upfront: #include <sstream> #include <algorithm> #include <iterator> #include <vector> int main() { std::vector<char> vec(6); //note what happens here! std::istringstream ss("foobar"); std::copy(std::istream_iterator<char>(ss), std::istream_iterator<char> (), vec.data()); }
71,897,055
71,897,067
Reassigning pointer argument inside function in C++
If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope? In the following code, s==nullptr gets printed. Why did assignment to s inside the function assign_string not reflected in the main function? #include<iostream> #include<string> void assign_string(std::string* s) { s = new std::string("Reassigned"); } int main() { std::string* s = nullptr; assign_string(s); if (s == nullptr) { std::cout << "s==nullptr" << std::endl; } else { std::cout << "s!=nullptr" << std::endl; } return 0; } PS: I'm new to C++ and I might be using terms like "assign" loosely. EDIT. Is passing pointer argument, pass by value in C++? has many useful answers.
If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope? No. When you pass an object by value, the parameter and the argument are separate objects. Modifying one object has no effect on the other object. This applies to all objects, including pointers. In order to modify an object outside of the function, you need to use indirection. There are two forms of indirection: Pointers and references. So, in order to modify a pointer that is outside of the function, you need to pass a reference or a pointer to the pointer. Example: void assign_string(std::string*& s); PS: I'm new to C++ I recommend learning early that owning bare pointers are a bad idea and there is hardly ever a need to use them nor to use allocating new expressions. It's quite rare to need to dynamically allocate a std::string object or any other container.
71,897,288
71,897,329
Removing the first word from a sentence and store it c++
I am reading from a file in C++, and I want to remove all but the first word and store it, sentence = sentence.substr(sentence.find_first_of(" \t") + 1); this code remove the first word and keep the whole sentence , is there a way to store the removed word.
https://en.cppreference.com/w/cpp/string/basic_string/find_first_of take position of first match from find_first_of and then sentence start pos to position from find_first_of std::string w1 = sentence.substr(0, sentence.find_first_of(" \t"));
71,897,375
71,900,891
Modify line behind QStatusbar widgets
Is there a way to modify (remove) the line behind a permanent widget in a QStatusbar? I don't know if it's important, but that's how I added the labels to the status bar: wStyleTest::wStyleTest(QWidget *parent) : QMainWindow(parent), ui(new Ui::wStyleTest) { // ... ui->statusbar->addPermanentWidget(ui->lblPermWidget1); ui->statusbar->addPermanentWidget(ui->lblPermWidget2); // ...
Subclass QProxyStyle and reimplement the drawPrimitive method. In there, check for the QStyle::PE_FrameStatusBar element and return from it instead of calling the base method. #include <QProxyStyle> #include <QStyleOption> class StyleFixes : public QProxyStyle { public: void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { if (element == QStyle::PE_FrameStatusBar) return; QProxyStyle::drawPrimitive(element, option, painter, widget); } }; Apply it to your app either in your main.cpp or constructor of MainWindow: QApplication::setStyle(new StyleFixes);
71,897,899
71,897,993
The following code is supposed to return true if i compare a1 with a2. But it is returning false
#include<iostream> #include<cstring> using namespace std; class Array { private: int* array; int s; public: Array() { array = NULL; s = 0; } Array(int size) { size = (size > 0 ? size : 10); array = new int[size]; for (int i = 0; i < size; i++) array[i] = 0; } Array(int* arr, int size) { for (int i = 0; i < size; i++) { *(arr + i) = *(array + i); } } Array(const Array& a):s(a.s) { array = new int[s]; for (int i = 0; i < s; i++) array[i] = a.array[i]; } int& operator[](int i) { return array[i]; } const Array& operator=(const Array& obj) { if (&obj != this) { if (s != obj.s) { delete[] array; s = obj.s; array = new int[s]; } } for (int i = 0; i < s; i++) array[i] = obj.array[i]; return *this; } bool operator==(const Array&obj)const { if (s != obj.s) return false; for (int i = 0; i < s; i++) { if (array[i] != obj.array[i]) return false; } return true; } ~Array() { delete[] array; } }; int main() { Array a1(5); int arr[] = { 1,2,3,4,5 }; Array a2(arr, 5); a1 = a2; } I am trying to run above program which is supposed to return true if I compare a1 and a2.but when I run this program I am getting false. Kindly check the overloaded operators and let me know where is the mistake. I have overloaded both assignment and equal operators but still I am not getting the actual output.
Three issues. The first is that you never allocated memory in the Array(int*, int) constructor for the array. The second is that this assignment... *(arr + i) = *(array + i); should be *(array + i) = *(arr + i); or even better array[i] = arr[i]; The third is that you are neglecting to assign s to the length of the array in some of your constructors.
71,898,998
71,934,476
Return a named object of a class from a function (by value ) and implicit move rule?
I have a problem with understanding what happens when you return an object of a class ( Not a specific class ) form a function ( pass by value ) in this code : EXAMPLE 1 #include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test( const test& z) { printf(" test( const test&z)\n"); } test(test&& s)noexcept{ printf(" test(test&& s)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; } The Output : test() test(test&& s) The previous Output makes me understand that in the function ( Some_thing ( ) ) Scope there are two objects are created . the first one is an lvalue object which we create it in the first line in the function ( Some_thing ( ) ) and we give it a name ( i ) So the constructor test ( ) is called. And the second one is an rvalue object So the constructor test ( test&& s ) is called. But when i deleted this constructor test(test&& s)noexcept and changed this constructor test( const test& z) into test( test& z) and run the code again : EXAMPLE 2 #include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test( test& z) { printf(" test( test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; } The Output : test() test( test&z) While I expected that this code will not compile because there is no constructor takes test&& or const test& as a parameter and when i tried to add one line to the previous code which is test(test&& z) = delete EXAMPLE 3 #include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(test&& z) = delete; test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test( const test& z) { printf(" test( test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; } I tried to compile it but it does not compile and it does not run So how does EXAMPLE 2 compile and run ?????? and how can the constructor test( test&z) be used instead of test(test&& z) ?????? ( I mean test( test&z) is not test( const test&z) So test( test&z) can not be used instead of test(test&& z) ) edit : this code compiles and runs : EXAMPLE 4 #include<iostream> #include<vector> #include<string> using namespace std; class test { public: test(test&& z) = delete; test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test(const test& z) { printf(" test( test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; int main() { test u; test r(u); return 0; } The Output : test() test( test&z)
The behavior of your program can be understood with the help of Automatic move from local variables and parameters: If expression is a (possibly parenthesized) id-expression that names a variable whose type is either a non-volatile object type or a non-volatile rvalue reference to object type (since C++20) and that variable is declared in the body or as a parameter of the innermost enclosing function or lambda expression, then overload resolution to select the constructor to use for initialization of the returned value or, for co_return, to select the overload of promise.return_value() (since C++20) is performed twice: first as if expression were an rvalue expression (thus it may select the move constructor), and if the first overload resolution failed or it succeeded, but did not select the move constructor (formally, the first parameter of the selected constructor was not an rvalue reference to the (possibly cv-qualified) type of expression) (until C++20) then overload resolution is performed as usual, with expression considered as an lvalue (so it may select the copy constructor). Now, lets apply this to your code snippet on case by case basis. Example 1 In this case, as the move ctor is available and viable, the condition "first as if expression were an rvalue expression" is satisfied and hence the move ctor is selected we get the mentioned output. class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test( const test& z) { printf(" test( const test&z)\n"); } test(test&& s)noexcept{ printf(" test(test&& s)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; } Example 2 In this case, since you've provided the copy ctor test::test( test&), the compiler will not synthesize a move ctor for us. Note that not having a synthesized move ctor is different from having a deleted move ctor. Thus the condition "if the first overload resolution failed" is satisfied(because there is no move ctor) and the overload resolution is then performed for the second time which will now select the provided copy ctor and hence the mentioned output. class test { public: test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test( test& z) { printf(" test( test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; } Example 3 In this case, you've explicitly deleted the move ctor. That is, your intent is that if someone tried to use the move ctor, then it should fail. So here, when the overload resolution happens for the first time, the move ctor is selected but since you've explicitly marked it as deleted fails immediately and hence the error. class test { public: test(test&& z) = delete; test(int y) { printf(" test(int y)\n"); } test() { printf(" test()\n"); } test( const test& z) { printf(" test( test&z)\n"); } test& operator=(test e) { printf(" test& operator=( test e)\n"); return *this; } }; test Some_thing() { test i; return i; } int main() { Some_thing(); return 0; }
71,899,293
71,899,307
When I attempt to add a specific character of a string through push_back() it throws me a type conversion error
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string input; getline(cin, input); int x = input.length(); vector<string> arr; for(x; x==0; x-2){ arr.push_back(input[x]); } return 0; } I get the following error when I try to compile: simplearraysum.cpp:16:23: error: reference to type 'const std::__vector_base<std::string, std::allocator<std::string> >::value_type' (aka 'const std::string') could not bind to an lvalue of type 'std::basic_string<char>::value_type' (aka 'char') arr.push_back(input[x]); Could anyone offer some advice on what I could do?
There are several bugs in the code that make it fail; most important the third part of the for loop: x-2 calculates the result of the subtraction, and then moves on. It is never stored anywhere, so x never changes. The loop runs forever, inserting over and over input[x] into the vector, until something blows up. You probably mean to use: x = x-2. Second problem is if x is odd - subtracting 2 will never hit exactly zero, so the loop will again never stop. You should use x>=0 or such for the condition. Third, input[x] is a char, not a string; the vector expects strings. That is what the shown error message talks about. Fourth, if x is the length of the string, input[x] accesses the char behind the string - in C and C++, indices start with 0, so an array of x chars goes from arr[0] to arr[x-1].
71,899,678
71,901,448
Color Output in MFC List issue
This code is about the worm game. It is a problem to print the color of the tail section. The code is written so that the worm's head grows longer and longer each time it eats. And from head to tail, it goes from green to blue. where the initial values for _GboxColor, _BboxColor, and Colornum are 255, 0, and 1, respectively. The Colornum increases by one every time the worm eats its food. I'll put an example gif at the bottom of this questionnaire. As you can see in the gif, You can see that the third part of the body from the head of the worm turned blue for a moment as soon as the head ate. There seems to be no problem with the code, but I don't know why this is happening. How do I make the color a little softer? // head int halfLength = 10; CBrush brush(RGB(0, 255, 0)); memDc.SelectObject(brush); memDc.Rectangle(_headPos.x - halfLength, _headPos.y - halfLength, _headPos.x + halfLength, _headPos.y + halfLength); // tail int bodyColorFig = 255 / Colornum; POSITION traversalNode = _boxes.GetHeadPosition(); _GboxColor = 255; _BboxColor = 0; while (traversalNode != nullptr) { _bodyPos = _boxes.GetAt(traversalNode); _GboxColor -= bodyColorFig; _BboxColor += bodyColorFig; CBrush brush(RGB(0, _GboxColor, _BboxColor)); memDc.SelectObject(brush); memDc.Rectangle(_bodyPos.x - halfLength, _bodyPos.y - halfLength, _bodyPos.x + halfLength, _bodyPos.y + halfLength); _boxes.GetNext(traversalNode); }
Have a breakpoint to see the value of _GboxColor when drawing the 3rd segment. Maybe an overrun occurs (the RGB macro hides the fact that the color is just a 32-bit value). Maybe you should initialize _GboxColor and _BboxColor before the while loop, not after it.
71,900,146
71,901,361
How to avoid dynamic_cast in this case?
I have 3 classes in my program: class GameObject{ private: std::pair<int, int> position; } class World{ private: std::vector<GameObject*> gameObjects; int gravity; } class MovingObject : public GameObject{ private: int velocity; bool isSensitiveToGravity; unsigned mass; } I am using a vector of GameObject* in the World class because I want to put in there every object that is in the game, and some objects are not MovingObject instances. But I see a problem there: during the game, I will need to loop on world.gameObjects in order to check if an object is sensitive to gravity to drag it down if it is the case, but how should I do this? My first idea was to add a pure virtual method in the GameObject class that would be implemented in the MovingObject class and return whether an object is sensitive to gravity or not, but isn't this a weird design? The other idea is of course to use dynamic_cast on every object, check for (sub)class of MovingObject, and then check for the isSensitiveToGravity field, but I read a lot that dynamic_cast should be avoided and is almost always a sign of bad design, so where is my error here? Thank you!
When you think in terms of functionality in OOP you should think in terms of interfaces and not structs of data. This is exactly the case so you should create an interface with a function interactWithGravity and use it. In case this is an object that does not interact with gravity simply do nothing. To emphasize why this it the correct solution let's consider the other alternative, having a parameter determining if it's moveable by gravity or not. This has the following cons: If you'll have more parameters the affects how certain objects are interact with gravity means adding another property to the common struct (although it's only relevant to some). The previous example also suggests you'll need to expend you're cases in the main function that goes over the objects and make the code more complex and harder to expend. Perhapse you'll find it easier to do the "gravity calculations" in polar coordinates. This means changing all the calculation and coordinates in the different objects. Holding different lists may be reasonable if you need to do some optimizations but otherwise it will be less reusable and expendable from similar reasons. The list goes on and on with other concepts like ISP but you get the general idea.
71,900,460
72,008,239
Tiff Windows Imaging Component c++
I am trying to replace libtiff into WIC (since libtiff is not able to pass Black Duck Analysis tool anymore) I have used their example https://learn.microsoft.com/en-us/windows/win32/wic/-wic-creating-encoder And I was able to create a tiff. I also needed to change the compression type so I change the code into if (SUCCEEDED(hr)) { // This is how you customize the TIFF output. PROPBAG2 option = { 0 }; option.pstrName = L"TiffCompressionMethod"; VARIANT varValue; VariantInit(&varValue); varValue.vt = VT_UI1; varValue.bVal = WICTiffCompressionRLE; hr = pPropertybag->Write(1, &option, &varValue); if (SUCCEEDED(hr)) { hr = piBitmapFrame->Initialize(pPropertybag); } } My new image has Resolution Unit 2 and I would like to set it into 1 I found out this https://learn.microsoft.com/en-us/windows/win32/wic/-wic-photoprop-system-image-resolutionunit but I do not understand how to use the WIC metadata API in order to change this. Can you help?
The WIC built-in TIFF encoder always writes the TIFFTAG_RESOLUTIONUNIT as 2 (inches). You can use WIC to read the existing tag, but you can't write a different value for this particular metadata item.
71,900,490
71,901,791
vulkan error when creating a vulkan instance when pNext is initialized
I'm following a vulkan tutorial and when I'm initializing the instance createInfo.pNext with VkDebugutilsmessengerCreateInfo* I'm getting an erorr. populateDebugMessengerCreateInfo(debugCreateInfo); createInfo.pNext = & debugCreateInfo; populateDebugMessengerCreateInfo: void app::populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) { createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT; createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; createInfo.pfnUserCallback = (PFN_vkDebugUtilsMessengerCallbackEXT)debugCallBack; } this is the error i get: Exception thrown at 0x00007FF8268D26F0 (vulkan-1.dll) in VulkanFirst.exe: 0xC0000005: Access violation reading location
You need to set pNext to NULL or it leads to uninitialized pointer dereference.
71,900,677
71,902,312
CMake project building with SFML library
i can't understand how to build SFML-project using CMakeLists.txt file. Help me, please, if you have time. Thank you!) Details I downloaded SFML library from official site (https://www.sfml-dev.org/index.php), moved it to my project root (see screenshots below), wrote C++-code using SFML and entered this cmake-command: .../test_proj> cmake -G "Ninja" . But in console output i got this: CMake Warning at subdir_02/CMakeLists.txt:5 (find_package): By not providing "FindSFML.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "SFML", but CMake did not find one. Could not find a package configuration file provided by "SFML" with any of the following names: SFMLConfig.cmake sfml-config.cmake Add the installation prefix of "SFML" to CMAKE_PREFIX_PATH or set "SFML_DIR" to a directory containing one of the above files. If "SFML" provides a separate development package or SDK, be sure it has been installed. -- Configuring done -- Generating done -- Build files have been written to: C:/Users/tim/Documents/c-c++/test_proj CMakeLists.txt: add_executable(subdir_02 main.cpp) set(SFML_STATIC_LIBRARIES TRUE) find_package(SFML COMPONENTS window graphics system) target_compile_features(subdir_02 PUBLIC cxx_std_17) target_compile_definitions(subdir_02 PRIVATE SFML_STATIC) target_link_libraries(subdir_02 ${SFML_LIBRARIES} ${SFML_DEPENDENCIES}) Here is the main C++-file using SFML (it is in project subfolder). .../test_proj/subdir_02/main.cpp: #include <SFML/Graphics.hpp> int main() { sf::RenderWindow app(sf::VideoMode(800, 600, 32), "Hello World - SFML"); return 0; } Screenshots project root folder screenshot SFML folder screenshot main.cpp-source folder
Dumb rule when you have a CMakeLists.txt in which dependencies are discovered with find_package(): add their install folder to CMAKE_PREFIX_PATH while calling CMake configuration. In you case, the CMake configuration of your project should be: cmake -S . -B build_release -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:\Users\tim\Documents\c-c++\test_proj\SFML" -G "Ninja" Indeed, SFML packages provide a CMake config file SFMLConfig.cmake in a subdir. It is a possible file find_package(SFML) is trying to find. CMake cannot know where this file is, so it looks into some specific subdirs under each path listed in CMAKE_PREFIX_PATH, and eventually some standard system paths. Actually the search procedure can be very complex (https://cmake.org/cmake/help/latest/command/find_package.html#config-mode-search-procedure), but for a native build CMAKE_PREFIX_PATH is your friend.
71,901,011
71,901,012
Can we convert a matlab built in function to c/c++ code using matlab coder
Can we convert matlab built in function that are present in 5G toolbox to c/c++ code using matlab coder.
It is shown at the end of the help page of that specific function. Type >> help yourFunctionName at the command line. Then scroll to the very bottom and then look at Extended Capabilities > C/C++ Code Generation. When that is present, you should be able to generate code (please unfold to see the details). If C/C++ Code Generation is not mentioned, you cannot generate code from that function.
71,901,206
71,902,812
Show all QCompleter elements on click
There is QComboBox with QCompleter. It is necessary to show all complementer elements when clicking on the LineEdit combobox. There is this code: completer = new QCompleter(this); completer->setModel(assignment_contacts); completer->setCompletionMode(QCompleter::CompletionMode::PopupCompletion); completer->popup()->setStyleSheet("background-color:rgb(54, 57, 63);" "color:white;"); QFont popupFont = QFont("Segoe UI",12,2); completer->popup()->setFont(popupFont); ui->comboBox_NewClientContacts->setEditable(true); ui->comboBox_NewClientContacts->setInsertPolicy(QComboBox::NoInsert); ui->comboBox_NewClientContacts->setModel(assignment_contacts); ui->comboBox_NewClientContacts->setModelColumn(1); ui->comboBox_NewClientContacts->completer()->setCompletionColumn(1); ui->comboBox_NewClientContacts->setCompleter(completer); ui->comboBox_NewClientContacts->lineEdit()->installEventFilter(this); <----- In the last line I set the EventFilter, its code is: bool MainWindow::eventFilter(QObject *object, QEvent *event) { if (object == ui->comboBox_NewClientContacts->lineEdit()){ if(event->type() == QEvent::MouseButtonPress){ ui->comboBox_NewClientContacts->lineEdit()->completer()->setCompletionPrefix(ui->comboBox_NewClientContacts->lineEdit()->text()); ui->comboBox_NewClientContacts->lineEdit()->completer()->complete(); } } return false; } It works PRACTICALLY as it should, when you click, the full list of elements is shown, but it works once, when the text is subsequently completely erased, there is nothing again, and you need to click the mouse again. I tried to solve this problem using the focusIn event, but it does not work, for some reason lineEdit() does not catch the Focus event. Any ideas?
Put this code after installing event filter to lineEdit of your combobox: //... ui->comboBox_NewClientContacts->installEventFilter(this); And this one to eventFilter of MainWindow: //... if (object == ui->comboBox_NewClientContacts){ if(event->type() == QEvent::KeyRelease && ui->comboBox_NewClientContacts->currentText() == "") { ui->comboBox_NewClientContacts->completer()->setCompletionPrefix(""); ui->comboBox_NewClientContacts->completer()->complete(); } } Hope it helps!
71,901,327
71,901,593
Why is getline not splitting up the the stringstream more than once?
When I'm trying to read data from a file, it is not updating the value of tempString2. Instead of grabbing and splitting the new line, it just holds the last value of the first data line. The reason I believe that the second getline is the issue is that the data is being read in, and the loops are running the exact number of times that I need them to. #include <iostream> #include <fstream> #include <string> #include <sstream> void PopulateWindLog(int dataIndex, std::string fileName, int const headerVecSize) { std::string tempString; std::string tempString2; std::stringstream tempStream; // open data file std::ifstream dataFile(fileName); // skip the header line std::getline(dataFile, tempString); // while there is still data left in the file while(std::getline(dataFile, tempString)) { tempStream << tempString; std::cout << tempString << std::endl; for(int i = 0; i < headerVecSize; ++i) { std::getline(tempStream, tempString2, ','); std::cout << tempString2 << std::endl; if(i == dataIndex) { std::cout << tempString2 << " INSIDE IF STATEMENT !!!! " << std::endl; } } } } This is the dataset that I'm using. For replication, I'm looking for column 'S' (index 10). headerVecSize is 18. WAST,DP,Dta,Dts,EV,QFE,QFF,QNH,RF,RH,S,SR,ST1,ST2,ST3,ST4,Sx,T 31/03/2016 9:00,14.6,175,17,0,1013.4,1016.9,1017,0,68.2,6,512,22.7,24.1,25.5,26.1,8,20.74 31/03/2016 9:10,14.6,194,22,0.1,1013.4,1016.9,1017,0,67.2,5,565,22.7,24.1,25.5,26.1,8,20.97 31/03/2016 9:20,14.8,198,30,0.1,1013.4,1016.9,1017,0,68.2,5,574,22.7,24,25.5,26.1,8,20.92 This is the output that I'm getting. Output of the built program
std::getline() extracts characters from input and appends them to str until one of the following occurs (checked in the order listed) end-of-file condition on input, in which case, getline sets eofbit. the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str. str.max_size() characters have been stored, in which case getline sets failbit and returns. (from https://en.cppreference.com/w/cpp/string/basic_string/getline) So after reading all elements from your first input line, tempstream.good() is false. No further input is read. Proposed solution: Move definition of tempstream into your while loop. You will get a stream in good state for each line.
71,901,925
71,901,992
How to read binary data from file after read sucessfully the ascii header in the file
I am trying read the Netpbm image format, following the specification explained here. The ascii types for the format (which have P1, P2 and P3 as magic number), I can read without problems. But I have issues reading the binary data in these files (whose with P4, P5 and P6 as magic number) - the header for the file (which is ascii) I am able to read without problem. In the link, it is stated that: In the binary formats, PBM uses 1 bit per pixel, PGM uses 8 or 16 bits per pixel, and PPM uses 24 bits per pixel: 8 for red, 8 for green, 8 for blue. Some readers and writers may support 48 bits per pixel (16 each for R,G,B), but this is still rare. with this, I try use this answer to read the data, bit by bit, and got this code: if(*this->magicNumber == "P4") { this->pixels = new Matrix<int>(this->width, this->height); vector<int> p; while(getline(file, line_pixels)) { if(line_pixels.size() > 0 && line_pixels.at(0) != '#') { string byte; stringstream ss(line_pixels); while(getline(ss, byte)) { unsigned char c = (unsigned char)byte.at(0); for(int x=0; x != 8; x++) p.push_back( (c & (1 << x)) != 0 ); } } } int count = 0; for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { this->pixels->set(i, j, p[count++]); } } } but when I try read the image named as sample_640×426.pbm in this link, I should get this result: but I am getting this result instead: For the binary format for PGM and PPM images, when I try open the image, I got a segmentation fault error when I try increment count at some point in the execution of the loop. I think somehow the size of vector<int> p is ending bigger than the expected product width x height. the code for the PGM format: if(*this->magicNumber == "P5") { this->pixels = new Matrix<int>(this->width, this->height); vector<int> p; while(getline(file, line_pixels)) { if(line_pixels.size() > 0 && line_pixels.at(0) != '#') { string number; stringstream ss(line_pixels); while(getline(ss, number)) { unsigned char data = (unsigned char)number.at(0); p.push_back((int)data); } } } int count = 0; for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { this->pixels->set(i, j, p[count++]); } } } the code for the PPM format: if(*this->magicNumber == "P6") { this->pixels = new Matrix<struct Pixel>(this->width, this->height); vector<int> p; while(getline(file, line_pixels)) { if(line_pixels.size() > 0 && line_pixels.at(0) != '#') { string byte; stringstream ss(line_pixels); while(getline(ss, byte)) { unsigned char data = (unsigned char)byte.at(0); p.push_back((int)data); } } } int count = 0; for(int i=0; i<height; i++) { for(int j=0; j<width; j++) { struct Pixel pixel; pixel.r = p[count++]; pixel.g = p[count++]; pixel.b = p[count++]; this->pixels->set(i, j, pixel); } } } Anyone can give a hint of what I am doing wrong here?
while(getline(file, line_pixels)) { std::getline reads from the input stream until a newline character is read. A file is a file. It contains bytes. Whether you believe the file contains text, or binary, is purely a matter of interpretation. Text lines are terminated by a newline character. That's what std::getline does: it reads bytes from a file until it reads a newline character. Whatever gets read, goes into the std::string parameter. This would be very confusing if your intent is to read some binary data, like an image. A byte containing the same value as a newline character can occur naturally in a binary file like an image file, representing the appropriate pixel values. Using std::getline to read non-textual data always ends in tears. This would only make sense in one situation: if you already know, in advance, the the binary data you intend to read here ends with a byte that just happens to be the newline character, and that newline character appears nowhere else. But, of course, in an image file, you have no such guarantees, whatsoever. When reading image data you are typically expected to read a specific amount of bytes from the file. Here, you know, in advance, the size of your image and its format. Based on that you can calculate using a simple mathematical formula how many bytes you expect to read. And that happens to be what std::istream's read() method does: read the specific number of bytes from a file. This link provides more information. You need to replace all shown code that improperly uses getline with one that uses read().
71,902,134
71,902,667
Give an aggregate a converting constructor?
I'm writing a large fixed-size integer type that is made up of multiple uint64_ts, like in the (simplified) example below. I would like my type to behave like the built-in integer types, which means (among other things) that: it should be uninitialized if you don't assign a value to it, and it should accept widening from other built-in integer types. It appears to me, however, that one cannot write a type that simultaneously satisfies both properties. This is because property 1 requires the type to be an aggregate, which means it must have no constructors, and we need a constructor to implement property 2. Is there any way to write a large integer type that satisfies both properties? #include <array> #include <cstdint> struct uint128_t{ std::array<uint64_t, 2> data; }; int main(){ uint128_t x; // uninitialized (good) uint128_t y = 100; // can we make this work while ensuring that the previous line still works? }
A constructor such as uint128_t() {} will leave your array uninitialized by default. Ability to leave members uninitalized has nothing to do with being an aggregate. But there's a better option: uint128() = default;. It will cause uint128_t x; to be uninitialized, but uint128_t x{}; will be zeroed, just like with built-in types.
71,902,142
71,902,678
Best way to optimize timer queue with concurrent_priority_queue C++
I'm working on timer queue using concurrent_priority_queue right now.. I implemented basic logic of executing most urgent event in this queue. Here's my code. TimerEvent ev{}; while (timer.mLoop) { while (timer.mQueue.empty() == false) { if (timer.mQueue.try_pop(ev) == false) continue; if (ev.Type == EVENT_TYPE::PHYSICS) // Physics event is around 15 ~ 17ms { auto now = Clock::now(); std::this_thread::sleep_for(ev.StartTime - now); timer.mGameServerPtr->PostPhysicsOperation(ev.WorldID); } else if (ev.Type == EVENT_TYPE::INVINCIBLE) // This event is 3sec long. { auto now = Clock::now(); std::this_thread::sleep_for(ev.StartTime - now); // This is wrong!! timer.mGameServerPtr->ReleaseInvincibleMode(ev.WorldID); } } std::this_thread::sleep_for(10ms); } The problem would be easily solved if there is like front/top method in concurrent_priority_queue. But there is no such method in class because it isn't thread-safe. So, I just popped event out of the queue and waited until start time of the event. In this way, I shouldn't have to insert event into queue again. But problem is that if I have another type of event like EVENT_TYPE::INVINCIBLE, then I shouldn't just use sleep_for because this event is almost 3 second long. While waiting for 3 second, the PHYSICS event will not executed in time. I can use sleep_for method for PHYSIC event since it is most shortest one to wait. But I have to re-insert INVINCIBLE event into queue. How can I optimize this timer without re-insert event into queue again?
How can I optimize this timer without re-insert event into queue again? By the looks of it, that'll be hard when using the implementation of concurrent_priority_queue you are currently using. It wouldn't be hard if you just used the standard std::priority_queue and added some locking where needed though. Example: #include <atomic> #include <chrono> #include <condition_variable> #include <functional> #include <iostream> #include <mutex> #include <queue> using Clock = std::chrono::steady_clock; using time_point = std::chrono::time_point<Clock>; struct TimerEvent { void operator()() { m_event(); } bool operator<(const TimerEvent& rhs) const { return rhs.StartTime < StartTime; } time_point StartTime; std::function<void()> m_event; // what to execute when the timer is due }; class TimerQueue { public: ~TimerQueue() { shutdown(); } void shutdown() { m_shutdown = true; m_cv.notify_all(); } // add a new TimerEvent to the queue template<class... Args> void emplace(Args&&... args) { std::scoped_lock lock(m_mutex); m_queue.emplace(TimerEvent{std::forward<Args>(args)...}); m_cv.notify_all(); } // Wait until it's time to fire the event that is first in the queue // which may change while we are waiting, but that'll work too. bool wait_pop(TimerEvent& ev) { std::unique_lock lock(m_mutex); while(!m_shutdown && (m_queue.empty() || Clock::now() < m_queue.top().StartTime)) { if(m_queue.empty()) { // wait "forever" m_cv.wait(lock); } else { // wait until first StartTime auto st = m_queue.top().StartTime; m_cv.wait_until(lock, st); } } if(m_shutdown) return false; // time to quit ev = std::move(m_queue.top()); // extract event m_queue.pop(); return true; } private: std::priority_queue<TimerEvent> m_queue; mutable std::mutex m_mutex; std::condition_variable m_cv; std::atomic<bool> m_shutdown{}; }; If an event that is due before the event we're currently waiting for in wait_pop comes in, the m_cv.wait/m_cv.wait_until will unblock (because of the m_cv.notify_all() in emplace()) and that new element will be the first in queue. The event loop could simply be: void event_loop(TimerQueue& tq) { TimerEvent te; while(tq.wait_pop(te)) { te(); // execute event } // the queue was shutdown, exit thread } And you could put any kind of invocable with the time point when you'd like it to fire in that queue. #include <thread> int main() { TimerQueue tq; // create a thread to run the event loop auto ev_th = std::thread(event_loop, std::ref(tq)); // wait a second std::this_thread::sleep_for(std::chrono::seconds(1)); // add an event in 5 seconds tq.emplace(Clock::now() + std::chrono::seconds(5), [] { std::cout << "second\n"; }); // wait a second std::this_thread::sleep_for(std::chrono::seconds(1)); // add an event in 2 seconds tq.emplace(Clock::now() + std::chrono::seconds(2), [] { std::cout << "first\n"; }); // sleep some time std::this_thread::sleep_for(std::chrono::seconds(3)); // shutdown, only the event printing "first" will have fired tq.shutdown(); ev_th.join(); } Demo with logging
71,902,547
71,902,648
Why is the move constructor not invoked when returning an rvalue?
I have created a class Animal: class Animal { public: Animal() = default; Animal(Animal&& a) = delete; Animal(Animal& a) = delete; Animal& operator=(Animal&& a) = delete; Animal& operator=(Animal& a) = delete; }; Animal func1() { return Animal(); } Animal func2() { Animal a {}; return a; } int main(void) { Animal a1 = func1(); Animal a2 = func2(); return 0; } I don't understand why func1() works fine: return Animal() creates an rvalue object and I initialize a1 with this object in the main function; as I see it, it is equal to Animal a1 = func1() == Animal a1 = Animal&& temp //(I wrote type in assignment for clarifying) and I have read that the return value is an rvalue; however, in func2 I get an error that ‘copy constructor is deleted’ not the move constructor, why?
Case 1 Here we consider the statement: Animal a1 = func1(); The call expression func1() is an rvlalue of type Animal. And from C++17 onwards, due to mandatory copy elison: Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible: In a return statement, when the operand is a prvalue of the same class type (ignoring cv-qualification) as the function return type: That is, the object is constructed directly into the storage where they would otherwise be copied/moved to. That is, in this case(for C++17), there is no need of a copy/move constructor to be available. And so this statement works. Case 2 Here we consider the statement: Animal a2 = func2(); Here from non mandatory copy elison, Under the following circumstances, the compilers are permitted, but not required to omit the copy and move (since C++11) construction of class objects even if the copy/move (since C++11) constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. This is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed: In a return statement, when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and which is of the same class type (ignoring cv-qualification) as the function return type. That is, the copy/move constructors are required to exist(that is these ctors must be present and accessible) but since you've explicitly marked them as deleted this statement fails with the error: error: use of deleted function ‘Animal::Animal(Animal&&)’ The error can also be seen here
71,902,558
71,902,646
Does the return type of a deleted operator matter if the operator is deleted?
I am reading ‘C++ concurrency in action’, one page talks about copy-assignment operator =delete. I have googled about it (Deleting copy constructors and copy assignment operators. Which of them are essential?) and tried some code by myself. I want to know if there is a difference between void operator= (const MyClass&) = delete; and MyClass& operator= (const MyClass&) = delete; or I can just do void operator= (MyClass) = delete; It seems like it will "delete" the operator = anyway... I just checked cppreference.com about Copy constructors and Copy assignment operator (https://en.cppreference.com/w/cpp/language/copy_constructor)(https://en.cppreference.com/w/cpp/language/copy_assignment). Could I just use the following code? MyClass(MyClass&)=delete; void operator= (MyClass) = delete; I think it will "delete" everything anyway, so I don't need to worry about the "performance" of the copying, right?...
C++ allows you to have operators with whatever return type you want. In all cases, you are overloading operator= with different semantics so they will all work. But it's best to follow the widespread convention of returning a class reference so that assignment chains (a = b = c) and constructs such as (while ((a = b) == c) {...) can work as well. The second way you wrote: MyClass& operator=(const MyClass&) = delete; is most used and as written, there is no need for a named parameter.
71,902,815
72,248,756
qemu-system-i386: Error loading uncompressed kernel without PVH ELF Note
Im trying to boot my OS to qemu with this code: qemu-system-i386 -kernel MyOS/mykernel.elf But I keep getting this error: qemu-system-i386: Error loading uncompressed kernel without PVH ELF Note Here is the code i use to build: i686-elf-gcc -std=gnu99 -ffreestanding -g -c MyOS/start.s -o MyOS/start.o i686-elf-gcc -std=gnu99 -ffreestanding -g -c MyOS/kernel.c -o MyOS/kernel.o i686-elf-gcc -ffreestanding -nostdlib -g -T MyOS/linker.ld MyOS/start.o MyOS/kernel.o -o MyOS/mykernel.elf -lgcc qemu-system-i386 -kernel MyOS/mykernel.elf My files: kernel.c/o start.s/o linker.ld mykernel.elf Can anyone help? If you need the code incase if its the code's fault or something, just reply stating that.
Try adding this to the command line -machine type=pc-i440fx-3.1 Source: https://forum.osdev.org/viewtopic.php?f=1&t=33638 Alternatively have a look at this How can I create a PVH "kernel" that will be run by qemu Hope this helps
71,903,055
71,903,157
Redundant string initialization warning when using initializer list in the default constructor
class person { private: std::string name; int hungerLevel; std::string location; int money; public: person() : name(""), hungerLevel(100), location(""), money(0) {} }; When I initialize my string variables as empty strings in the default constructor using the Initializer list I get the warning "Redundant string initialization". class person { private: std::string name; int hungerLevel; std::string location; int money; public: person() : hungerLevel(100), money(0) { name = ""; location = ""; } }; However, when I initialize my strings as empty strings in the body of the constructor as demonstrated above I don't get any errors. I'm not sure if this warning is only related to IDE that I'm using or if one of them is the proper way/good practice.
The gist of your question has been answered in the comments, but you can avoid a constructor altogether here by declaring your class like this: class person { private: std::string name; int hungerLevel = 100; std::string location; int money = 0; }; This (to me) has the huge advantage that you have the declaration and initialisation of all your member variables in the same place and avoids the danger of forgetting to initialise one in your constructor's initialiser list (which can happen if you add a new member variable, typically). It also means that those variables will be initialised correctly even if you add another constructor, it's a win-win situation. As other have said, the compiler will emit code to intialise your std::strings automatically (by calling the default constructor), so that will take care of itself.
71,903,953
71,904,351
Why is C++ slower than C when doing literaly nothing
C++ is almost 4 times slower than C at doing nothing (at least on my machine). When the following file is compiled by g++, it is 4 times slower than with gcc: int main() {} With time sh -c 'for i in $(seq 0 1000) ; do ./a.out ; done', I get 0.515s for the C version, and 2s for the C++ one. Why is that? There isn't a single thing done in this program, and the disassembled program is basically the same in both versions, so why is the C++ version roughly 4 times slower? My guess is that the C++ library takes a longer time to load, but the assembly is so similar that I can't think of a reason for C++ to be so much slower. Edit : Well, it appears that I only partially disassembled the program (objdump -d instead of objdump -D), resulting in me not seeing the library being loaded. It is pretty obvious now seeing the disassembled output that the C++ version just takes longer to load its libraries. What I first meant by "slightly differing" was that the addresses used in mov or call diverged without calling other functions (if I understand correctly the meaning of objdump's output). So the main question is solved, but 2 seconds is huge for a program that does nothing. I'm on a x86_64 processor if that helps, and I built the executable gcc empty.c and g++ empty.cpp. I think the issue really is me using a HDD, thus taking more time to load libstd++. I also built with the -static flag, and am now getting very similar results (0.246s and 0.241s). The C binary is also exactly the same as the C++ one (if that's not a diff bug).
C++ standard library initial startup is heavier than the C runtime. C++ ABI needs to initialize some structures for basic language features. Mutex locks for thread-safe initialization of data, exeptions, thread local storage, RTTI, etc. This is why an empty executable created with a C++ compiler will start slower than an empty C program. Likewise, an empty program created with Assembly language will start much faster then a similar program created with C with a full-featured C runtime (CRT, GNU LIBC, etc).
71,904,320
71,904,405
C++: Ambiguos function call even with unique function names at each inheritence level
Code - #include<iostream> using namespace std; class P { public: void print() { cout <<" Inside P"; } }; class Q : public P { public: void print() { cout <<" Inside Q"; } }; class Q2: public P { public: void print2() { cout <<" Inside Q2"; } }; class R: public Q2, public Q { }; int main(void) { R r; r.print(); // error: request for member ‘print’ is ambiguous return 0; } Expected behavior: No ambiguous call on 3rd line in main. Actual behavior: Ambiguous call on 3rd line in main Rationale: I expected class Q to hide the print() function of class P. I would expect an ambiguous call error when Q2 has the same function name as R or Q (or even P?). But I deliberately changed the function name in Q2 to 'print2' to avoid this error. This error goes away when I remove 'Q2' as parent class of R. Is this happening because 'Q2' inherits 'print' from 'P'? Note: I know similar questions have been asked on data hiding for regular inheritance and ambiguous calls in case of inheritance from multiple classes, but this case is sort of a mixture of two, and I did not find any specific answers.
I expected class Q to hide the print() function of class P This has nothing to do with Q hiding the superclass's print(). Q2 inherits from P, and therefore inherits print(). class R: public Q2, public Q { }; print() is inherited from both Q2 and from Q. Whether they turn out to be the same or different methods is immaterial. The point is that it is ambigous which print() method R.print() resolves to. would expect an ambiguous call error when Q2 has the same function name But it does. It inherits it.
71,904,533
71,904,597
Problems reading/writing to binary file
I wrote the code below to save a vector of struct to a binary file. The problem is the reading stops before all the written data is read. Changing the reinterpret_cast<const char*> with (char*) or (const char*) does not help or change the output. Seeing as it does read the right number for the data it does read the code is at least partially right. Is there something obvious i'm missing? Or why does this not work? #include <iostream> #include <fstream> #include <vector> struct Pixel { long long data; Pixel() { data = 0; } Pixel(long long data) : data(data) {} }; void saveToBin(std::vector<Pixel>* pixels) { std::ofstream binFile; binFile.open("test.bin", std::ios::binary); if (!binFile.is_open()) { perror("Error open"); exit(EXIT_FAILURE); } for (int i = 0; i < pixels->size(); i++) { binFile.write(reinterpret_cast<const char*>(&pixels->at(i)),sizeof(Pixel)); } binFile.close(); } void readBin(std::vector<Pixel>* pixels) { std::ifstream binFile; binFile.open("test.bin", std::ifstream::in); if (!binFile.is_open()) { perror("Error open"); exit(EXIT_FAILURE); } Pixel p; while (binFile.read(reinterpret_cast<char*>(&p), sizeof(Pixel))) { pixels->push_back(p); } binFile.close(); } int main() { std::vector<Pixel> vecOrig; for (int i = 0; i < 1000; i++) { vecOrig.push_back(Pixel(i*7)); } std::vector<Pixel> vecRead; saveToBin(&vecOrig); readBin(&vecRead); std::cout << "starting length : " << vecOrig.size() << " , read length : " << vecRead.size() << std::endl; for (int i = 0; i < std::min(vecOrig.size(), vecRead.size()); i++) { std::cout << vecOrig[i].data << " -> " << vecRead[i].data << std::endl; } }
binFile.open("test.bin", std::ios::binary); The output file was opened in binary mode. binFile.open("test.bin", std::ifstream::in); The input file was not. This only matters on operating systems that trace their lineage to MS-DOS, and if your binary file happens to have a 0x0D byte it will be gratuously deleted, when read. Open the input file in binary mode, too.
71,904,940
71,904,978
What is the following MACRO doing?
#define DEFINE_VECTOR_MEMBER_DATA_S(T,c,n,s) T c ## :: ## n[s] I have it in the legacy code. It is compiled by MSVC 2022, but not with Clang. I plan to replace it, but before it I need to know what does it do.
It defines a vector which is a static member of a class. Type T. Class c. Name of vector n. Size of vector s. ## pastes 2 pieces together, but isn't needed anyway. If the linker says it the vector's missing just add: T c::n[s]; Into a .cpp file with the parts replaced accordingly.
71,905,148
71,905,334
Stuck using an array in the constructor as a parameter
I am new to this and I am having a problem. I want to use an array as a parameter in the constructor, but when I want to initialize the parameter in the main() function and call the class, it seems I can't directly put the array values as I did with the name and surname. The simplified code looks like below. It shows an error that the default constructor is not available. class Student { private: string name; string surname; int age; int grade[5]; public: Student(string e, string b, int c,int A[5]) { name = e; surname = b; age = c; for (int i = 0; i < 5; i++) grade[i] = A[i]; } }; int main() { Student obj = Student("Jack","blalba", 18, {10,10,9,8,8}); }
The only thing that needs to be changed is the constructor: Student(string e, string b, int c, int (&&A)[5]) { name = e; surname = b; age = c; for (int i = 0; i < 5; i++) grade[i] = A[i]; }
71,905,176
71,905,234
Alias template doesn't work like class template
I am learning about C++ templates from C++ Primer 5th edition. For example, i learnt that we could do the following: template<typename T> struct Custom { }; template<> struct Custom<int> { int a = 0; }; Then i learnt that C++11 also added a feature of alias templates. So i tried the same with them as shown below: template<typename T> using var = std::stack<T>; template<> using var<double> = double; But the above shown snippet doesn't work. What is the problem here, why doesn't the 2nd snippet work.
The problem is that we cannot specialize an alias templates. From temp.decls 17.5.3: Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias template.
71,905,195
71,905,543
Wrap a function that takes std::function<double(doule)> in order to pass functions that take more arguments
Problem I have a function double subs(std::function<double(double)> func), and I want to wrap it in a new function that looks like this template<typename... Args> double subsWrap(std::function<double(Args... args)> func) that applies subs to some function that takes more inputs as subs( subs( subs( ... func(...) ) ) ) with each subs applied to only one of the arguments of func at a time. Minimal example Let's say that we have a function auto subs = [] (std::function<double(double)> func){return func(2) + func(5.3);}; and we want to apply it to auto f2=[](double x, double y){return std::sin(x*std::exp(x/y)); }; as subs( [&f2](double y){ return subs( [&y,&f2](double x){ return f2(x,y); } ); } ) For f2, this is easy, so there is no need for a wrapper. However, if we want to do the same thing for a function of a greater number of arguments (e.g. double(double,double,double,double,double)) things start to become complicated. There has to be a way to do this automatically, but I am not even sure how to start.
What about using variadic lambdas together with std::is_invocable type trait to terminate recursion? template<class Fn> double subs_wrap(Fn func) { if constexpr (std::is_invocable_v<Fn, double>) return subs(func); else return subs([=](double x) { return subs_wrap( [=](auto... xs) -> decltype(func(x, xs...)) { return func(x, xs...); } ); }); } Here an explicit return type specification for a lambda is needed to propagate "invocability" property. [=](auto... xs) { return func(x, xs...); } is formally invocable with any number of arguments, no matter whether func(x, xs...) is invocable or not. When the return type is specified explicitly with decltype, SFINAE jumps in. With this implementation, both expressions subs([=](double y) { return subs([=](double x) { return f2(x, y); }); }); and subs_wrap(f2); will produce the same result. It's interesting to note that with -O3 optimization both GCC and Clang can optimize all this code away and replace subs_wrap(f2) with a compile-time constant. With similar code written using std::function arguments they don't do it. How do we do the unpacking if we want to pass arguments to subs (different for each recursion) Here is a way to achieve this with a slight modification of code: template<class Fn, class P, class... Ps> double subs_wrap(Fn func, P p, Ps... ps) { if constexpr (std::is_invocable_v<Fn, double>) { static_assert(sizeof...(Ps) == 0); return subs(func, p); } else { static_assert(sizeof...(Ps) > 0); return subs([=](double x) { return subs_wrap( [=](auto... xs) -> decltype(func(x, xs...)) { return func(x, xs...); }, ps...); }, p); } } subs_wrap(f2, p1, p2);
71,905,201
71,905,586
Tesseract very low detection quality
Trying to read some data with tesseract but it's already strugling with date and time, so I created a minimal test case. code: #include <string> #include <sstream> #include <tesseract/baseapi.h> #include <leptonica/allheaders.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc.hpp> #include <boost/algorithm/string/trim.hpp> using namespace std; using namespace cv; int main(int argc, const char * argv[]) { string outText, imPath = argv[1]; cv::Mat image_final = cv::imread(imPath, CV_8UC1); tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init(NULL, "eng", tesseract::OEM_LSTM_ONLY); api->SetPageSegMode(tesseract::PSM_AUTO_ONLY); cv::adaptiveThreshold(image_final,image_final,255,ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY,11,2); api->SetImage(image_final.data, image_final.cols, image_final.rows, 3, image_final.step); api->SetVariable("tessedit_char_whitelist", "0123456789- :"); outText = string(api->GetUTF8Text()); api->End(); std::istringstream iss(outText); for (std::string line; std::getline(iss, line); ) { boost::algorithm::trim(line); if (!line.empty()) cout << line << endl; } cv::imwrite("out.png", image_final); return 0; } output: 1122-03-08 18:10 2122-030 18:10 I even tried to whitelist these characters (which will not be the case in the final version) but still getting very bad results.
It looks like the main issue is setting bytes_per_pixel to 3 instead of 1 in api->SetImage. The image after cv::adaptiveThreshold is 1 color channel (1 byte per pixel) and not 3. Replace api->SetImage(image_final.data, image_final.cols, image_final.rows, 3, image_final.step); with: api->SetImage(image_final.data, image_final.cols, image_final.rows, 1, image_final.step); Replace cv::imread(imPath, CV_8UC1) with cv::imread(imPath, cv::IMREAD_GRAYSCALE) You may also try replacing tesseract::PSM_AUTO_ONLY with tesseract::PSM_AUTO or tesseract::PSM_SINGLE_BLOCK. According to the comment in the header file: PSM_AUTO_ONLY = 2, ///< Automatic page segmentation, but no OSD, or OCR. (Unless this is in purpose - I never used the C++ interface). I have tried to reproduce the problem using pytesseract and Python, but I am getting an error when setting PSM to 2. I am probably also using different version of Tesseract. The result is perfect, and it supposed to be perfect with the image from your post. Python code: import cv2 from pytesseract import pytesseract # Tesseract path pytesseract.tesseract_cmd = "C:\\Program Files\\Tesseract-OCR\\tesseract.exe" img = cv2.imread("out.png", cv2.IMREAD_GRAYSCALE) # Read input image as Grayscale text = pytesseract.image_to_string(img, config="-c tessedit" "_char_whitelist=' '0123456789-:" " --psm 3 " "lang='eng'") print(text) Output: 2022-03-08 18:19:15
71,905,686
71,908,684
Trigger stm32 timer on PWM
I'm new to stm32 timers and have a question concerning triggering. I would like to generate four squarewaves two of each complements of each other. That is the trivial part. Now I would like to introduce a variable phaseshift between each of the two complementary signalgroups. (Phaseshift PWM) Now my question, can I trigger timer 2 on the falling or rising edge of a pwm signal produced by timer 1? Or is there another way for me to generate a phaseshift between those signals that's changeable during runtime?
A single advanced control timer (TIM1 or TIM8) can do all of this for you. See the reference manual section 17.3.11 "Complementary outputs and dead-time insertion". Alternatively you can chain timers, see section 13.3.15 of the same manual.
71,905,738
71,905,805
C++, write from file into map
im just new at c++ and I try to read from a file and write the content into a map<string, float>. But only the first element of my file gets mapped and i cant figuer out why. The file looks like this: E:16.93 N:10.53 I:8.02 ... And the code i got for this part so far: std::map<char, float> frequenciesM; fstream frequencieFile("frequencies.txt", std::ios::in); if(!frequencieFile){ cout << "No such File!"; }else{ std::string line; char ch; std::string sub; float fl; while (std::getline(frequencieFile, line, '\0')) { ch = line[0]; sub = line.substr(2); fl = std::stof(sub); frequenciesM[ch] = fl; } } When i try to print out the size and content of my map, this is what i get: Size: 1 E: 16.93 Thx for any help and suggestions!
You are telling getline() to read until a '\0' (nul) character is encountered, but there is no such character in your file, so the entire file gets read into the string on the 1st call, and then you extract only the 1st set of values from the string, discarding the rest of the data. To read the file line-by-line, you need to change the 3rd parameter of getline() to '\n' instead: while (std::getline(frequencieFile, line, '\n')) Or, just drop the 3rd parameter entirely since '\n' is the default delimiter: while (std::getline(frequencieFile, line))
71,906,000
71,906,274
By convention does Qt allow signals and slots to have different signatures?
I assumed from experience with Qt that all signals and slots required identical signatures. Recently I seen Qt code that connects totally different signatures, and the slot are called when the signal they were connected to is emitted. For example, a signal that emits a couple objects to a slot that takes no arguments. I know about the different ways QObject::connect() can be called for connecting signals and slots, still I figured the rule was that their signatures are required to be the same.
From the documentation on Qt Signals and Slots: The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.) Essentially, you can drop arguments from the end of your slot's signature (you can not drop them from the beginning or middle). If you need to ignore arbitrary arguments, you can make your slot's signature identical to the signal and then use the Q_UNUSED macro for any arguments you want to ignore. For example: void MyClass::mySlot(int foo, double argIDontCareAbout, int bar) { Q_UNUSED(argIDontCareAbout) } The point of the Q_UNUSED macro is to simply to suppress compiler warnings about unused arguments.
71,906,069
71,906,177
What is the proper way of using a source generator in CMake
In my C++ project I'm using a source generator to embed some resources into the binary. I use CMake to build my project and my code works but had some issues. I am pretty sure that what I want to accomplish is possible but I didn't find any answer online. The current problems I have are: The generator runs every time, even if the input files did not change. This is not too big of a deal because it is really fast, but I hopped there was a better way to do it While using Ninja the generator runs at every build (as described above) without rebuilding every time. I think that Ninja sees that the file has not changed and does not build it again, but when I make changes in the resources change it still uses the old version. It takes another build to "realize" that the generated file has changed and rebuild it While using Make the code rebuilds every time, even when the generated file does not change, resulting in wasted build time In both cases (looking at the output) the generator runs before the compiler. This situation is not unsustainable but I was wondering if a better solution was possible. Here's a code snippet from my CMakeLists.txt add_subdirectory(Generator) file(GLOB RESOURCES Resources/*) add_custom_command( OUTPUT src/Resources/Generated.hpp src/Resources/Generated.cpp COMMAND Generator ${RESOURCES} DEPENDS ${RESOURCES} DEPENDS Generator ) add_custom_target(Generated DEPENDS src/Resources/Generated.hpp src/Resources/Generated.cpp) add_dependencies(${PROJECT_NAME} Generated) Here's a minimal reproducible example, sorry for not having it before. EDIT: I implemented the functional solution from the correct answer in the fix branch, on the same repo. It might be useful for future reference :)
This one is interesting, because there are multiple errors and stylistic issues, which partially overlap each other. First off: file(GLOB_RECURSE SRC src/*.cpp src/*.hpp) add_executable(${PROJECT_NAME} ${SRC}) While convenient in the beginning, globbing your sources is not a good idea. At some point you will have a testme.cpp in there that should not be built with the rest, or a conditionally_compiled.cpp that should only be compiled if a certain option is set. You end up compiling sources that you really did not intended to. In this case, the file src/Generated.hpp from your git repository. That file is supposed to be generated, not checked out from repo. How did it even get in there? add_custom_command( OUTPUT src/Generated.hpp COMMAND ${PROJECT_SOURCE_DIR}/generator.sh ${PROJECT_SOURCE_DIR}/Resources/data.txt > ${PROJECT_SOURCE_DIR}/src/Generated.hpp DEPENDS Resources/data.txt DEPENDS ${PROJECT_SOURCE_DIR}/generator.sh ) Do you see the output redirection there? You wrote to ${PROJECT_SOURCE_DIR}. That is not a good idea. Your source tree should never have anything compiled or generated in it. Because these things end up being committed with the rest... like it happened to you. Next issue: add_custom_target(Generated DEPENDS src/Generated.hpp) This creates a make target Generated. Try it: make Generated. You keep getting the following output: [100%] Generating src/Generated.hpp [100%] Built target Generated Obviously it does not realize that Generated.hpp is already up-to-date. Why not? Let's look at your custom command again: add_custom_command( OUTPUT src/Generated.hpp COMMAND ${PROJECT_SOURCE_DIR}/generator.sh ${PROJECT_SOURCE_DIR}/Resources/data.txt > ${PROJECT_SOURCE_DIR}/src/Generated.hpp DEPENDS Resources/data.txt DEPENDS ${PROJECT_SOURCE_DIR}/generator.sh ) What if I told you that your OUTPUT is never actually generated? Quoting from CMake docs on add_custom_command, emphasis mine: OUTPUT Specify the output files the command is expected to produce. If an output name is a relative path it will be interpreted relative to the build tree directory corresponding to the current source directory. So your output claims to be to the binary tree, but your command's redirection is to the source tree... no wonder the generator keeps getting re-run. Having your header generated in the wrong location does not give you a compiler error, because that header from your source tree gets picked up by your GLOB_RECURSE. As that one keeps getting re-generated, your executable keeps getting recompiled as well. Try this from your build directory: mkdir src && touch src/Generated.hpp && make Generated Output: [100%] Built target Generated You see that make has nothing to do for the Generated target, because it now sees an OUTPUT of your custom command that is newer than its dependencies. Of course, that touched file isn't the generated one; we need to bring it all together. Solution Don't write to your source tree. Since ${PROJECT_BINARY_DIR}/src does not exist, you need to either create it, or live with the created files on the top dir. I did the latter for simplicity here. I also removed unnecessary ${PROJECT_SOURCE_DIR} uses. add_custom_command( OUTPUT Generated.hpp COMMAND ${PROJECT_SOURCE_DIR}/generator.sh \ ${PROJECT_SOURCE_DIR}/Resources/data.txt \ > Generated.hpp DEPENDS Resources/data.txt DEPENDS generator.sh ) Don't glob, keep control over what actually gets compiled: add_executable( ${PROJECT_NAME} src/main.cpp ) Add the binary tree to your target's include path. After add_executable: target_include_directories( ${PROJECT_NAME} PRIVATE ${PROJECT_BINARY_DIR} ) That's it, things work as expected now.
71,906,265
71,907,938
Get variables from gnuplot to c++
I'm writing a code in c++ which plots a dataset using gnuplot, and I realized that I could simplify my code a lot if I could get variables from gnuplot to my c++ code. e.g. if I did a fit f and get his stats i.e. f(x)=a*x+b fit f 'data.txt' via a,b stats 'data.txt' u (f($1)):2 name 'Sf' Is there any way to get, for example, the Sf_records and save it to a variable in my code? Like int N = Rf_records? Thanks for your help
Assuming that you are communicating with gnuplot trougth a FIFO, you can order to gnuplot print <variable> and you can read this to your c++ program. Eg. for reading a varirable: double getVal(std::string val){ float ret; std::string str; str="print "; str+=val;str+="\n"; fprintf(gp, str.c_str()); fflush(gp); fscanf(gpin, "%f", &ret); return ret; } To open a gnuplot FIFO void connecttognuplot(){ //make an unique FIFO std::stringstream alma; alma.str(std::string()); alma<<std::clock(); GPFIFO="./gpio"+alma.str(); //gnuplot => program FIFO if (mkfifo(GPFIFO.c_str(), 0600)) { if (errno != EEXIST) { perror(GPFIFO.c_str()); unlink(GPFIFO.c_str()); } } // For fprintf if (NULL == (gp = popen("gnuplot 2> /tmp/gp1","w"))) { perror("gnuplot"); pclose(gp); } // Redirect print fprintf(gp, "set print \"%s\";\n", GPFIFO.c_str()); fflush(gp); // For fscanf if (NULL == (gpin = fopen(GPFIFO.c_str(),"r"))) { perror(GPFIFO.c_str()); pclose(gp); } }
71,906,301
71,906,701
How can you pass an ifstream to thread?
I'm trying to implement multi-threading in my program. I'm trying to make my directory searcher run in a thread, and join for the rest of the function. The file thread function searches my directory and finds each file, and I'm trying to use this in my file reader section within my main() function. How should I pass an ifstream path to a thread? After a lot of googling, I'm not any closer to finding an answer due to it being so specific. void file_thread(std::ifstream& file){ //open csv file for reading std::string path = "path/to/csv"; for (const auto & f : std::filesystem::directory_iterator(path)){ std::ifstream file(f.path()); } } int main(){ std::ifstream file; std::thread test(file_thread, file); //if csv is successfully open if(file.is_open()) { ... } ... }
I suspect you actually want this, although its not at all clear why you are using a separate thread void file_thread(std::ifstream& file){ //open csv file for reading std::string path = "path/to/csv"; file.open(path); } If thats the path, why iterate over the directory This code still wont help if you call it in a separate thread as main will not wait. Why not just call normally? std::thread test(file_thread, file); // the line below will run before file_thread finishes // thats the whole point of threads if(file.is_open()) { ... } just do file_thread(file); //if csv is successfully open if(file.is_open()) { ... }
71,906,814
71,923,795
fread/fwrite introduces garbage values
Data file data.dat: 5625010350032.36719 5627008621379.12591 5628763999478.55791 5630383772880.98831 5632384688238.96095 5633992371569.87936 5635830220975.76879 5637713568911.67183 5639436594135.51215 5641160625591.58400 5643072053703.23919 5644920788572.33232 5646668772882.99855 5648398453919.33759 5650178043246.84799 5651842484825.03887 5653671759113.42399 5655374735235.55599 5657184594518.72287 5658951103084.33839 5660687853998.58127 5662491073242.24399 The following code x1 <- data.matrix(data.table::fread("data.dat")) # Read it plot(x1[1,]) data.table::fwrite(x=x1, file="xout.dat", sep=" ") # Write it x2 <- data.matrix(data.table::fread("xout.dat")) # Read it again lines(x2[1,], col='red') reveals that the element x2[1,13] takes the value 2.7898250541260385e-311 when it should in fact be equal to x1[1,13]. What is causing the garbage values to be introduced? The data.dat file is written from a C++ file in the following way std::ofstream file("data.dat", std::ios::out); file << std::setprecision(std::numeric_limits<long double>::digits10) << std::showpoint; for (size_t i = 0; i < v.size(); ++i) file << v[i] << " "; file << std::endl; where the vector v contains the values written to data.dat. I am using data.table version 1.14.2 and R 4.1.3.
Appearantly it does some rounding somewhere in the process and fread stores that 13th value as integer64 "integer64" (default) reads columns detected as containing integers larger than 2^31 as type bit64::integer64. What you can do is force it to be interpretted as numeric, by adding colClasses = c("numeric") to your fread. x2 <- data.matrix(data.table::fread("xout.dat", colClasses = c("numeric"))) This does not prevent the floating point issues but does not make the 13th value be changed completely. If we now do x1-x2 we see for all values we have the same sort of differences. x1-x2 # V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 # [1,] -0.0029297 -0.0039062 -0.0019531 -0.0019531 0.00097656 -0.00097656 -0.00097656 0.0019531 0.0019531 0.0039062 -0.00097656 0.0019531 # V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 # [1,] -0.00097656 -0.0019531 -0.0019531 -0.00097656 0.0039062 -0.0039062 0.0029297 -0.00097656 0.00097656 0.0039062
71,906,974
71,907,017
Initialize a template class private static variable in C++
I'm trying to compile a sample program in C++ using templates. The template class has a priavte static member variable which seems to be undefined when trying to compile. Going through other answers on SO, I realized that this variable needs to be defined as well. However my attempts at defining this variable have been unsuccessful so far, likely due to my lack of experience working with templates. Here is my sample program: #include <iostream> #include <array> enum FRUIT { APPLE, ORANGE }; using FunctionPtr = void(*)(void); template <FRUIT T> void FruitFunction(void); template <FRUIT...TotalFruits> class TestClass { public: struct fruitGroup { FRUIT fruit; FunctionPtr func; }; static int find_fruit(FRUIT fruit, int arg) { for (auto i = pv_mem_.begin(); i != pv_mem_.end(); ++i) { if (i->fruit == fruit) { break; } } return 0; } private: constexpr static std::array<fruitGroup, sizeof...(TotalFruits)> pv_mem_ { fruitGroup{TotalFruits, &FruitFunction<TotalFruits>}... }; }; int main() { TestClass<FRUIT::APPLE, FRUIT::ORANGE> test; test.find_fruit(FRUIT::APPLE, 0); return 0; } This yields: $ g++ -std=c++11 fruit.cpp -o foo /tmp/ccqaSBYm.o: In function `TestClass<(FRUIT)0, (FRUIT)1>::find_fruit(FRUIT, int)': fruit.cpp:(.text._ZN9TestClassIJL5FRUIT0ELS0_1EEE10find_fruitES0_i[_ZN9TestClassIJL5FRUIT0ELS0_1EEE10find_fruitES0_i]+0xf): undefined reference to `TestClass<(FRUIT)0, (FRUIT)1>::pv_mem_' fruit.cpp:(.text._ZN9TestClassIJL5FRUIT0ELS0_1EEE10find_fruitES0_i[_ZN9TestClassIJL5FRUIT0ELS0_1EEE10find_fruitES0_i]+0x1d): undefined reference to `TestClass<(FRUIT)0, (FRUIT)1>::pv_mem_' collect2: error: ld returned 1 exit status I have tried defining pv_mem_ as: constexpr static std::array<TestClass::fruitGroup, sizeof...(TotalFruits)> pv_mem_; but that resulted in the following error: $ g++ -std=c++11 fruit.cpp -o foo fruit.cpp:44:74: error: wrong number of template arguments (1, should be 2) constexpr static std::array<TestClass::fruitGroup, sizeof...(TotalFruits)> pv_mem_; ^ In file included from fruit.cpp:2:0: /usr/include/c++/5/array:89:12: note: provided for ‘template<class _Tp, long unsigned int _Nm> struct std::array’ struct array ^ fruit.cpp:44:76: error: uninitialized const ‘pv_mem_’ [-fpermissive] constexpr static std::array<TestClass::fruitGroup, sizeof...(TotalFruits)> pv_mem_; ^ What would be the right way to initialize this variable?
pv_mem_ is defined as follows constexpr static std::array<fruitGroup, sizeof...(TotalFruits)> pv_mem_ { fruitGroup{TotalFruits, &FruitFunction<TotalFruits>}... }; which uses & to take the address of FruitFunction<TotalFruits>, but since FruitFunction is only declared and not defined, it will generate an undefined reference error at runtime. Adding the definition for the template function FruitFunction will solve the problem in C++17 template <FRUIT T> void FruitFunction() { /* */ } In C++11, constexpr static member variables still need to be defined outside the class, so you also need to add template <FRUIT...TotalFruits> constexpr std::array< typename TestClass<TotalFruits...>::fruitGroup, sizeof...(TotalFruits)> TestClass<TotalFruits...>::pv_mem_; Demo
71,907,008
71,907,476
OpenCV Program that Allows User to Enter Image and Transformation Matrix and See Transformation Applied
So, the first problem I ran into was that OpenCV defines its origin about the top left corner rather than the center of the window. This was a problem because I want to just apply a transformation matrix to an image (say a reflection about the x-axis for example) and see it applied "in place", so it stays in the same spot, but is still reflected. My solution to fix this was to first translate the image to OpenCV's origin, apply my transformation matrix to the image, then translate it back to its original location. This works fine, however, any part of the image that goes off screen at any point is permanently deleted/cropped. I cannot figure out how to prevent this, I figured there was maybe a flag or something and I tried utilizing BORDER_WRAP rather than BORDER_CONSTANT which almost fixed my problem, but not quite and now I am completely stuck on where to go next. Here is what I have so far: int main() { // Read in and display input image Mat src = imread("myImage.png"); imshow("Input Image", src); // Translate the image to the origin Mat M = (Mat_<double>(2, 3) << 1, 0, -(src.rows / 2), 0, 1, -(src.cols / 2)); Size dsize = Size(src.rows, src.cols); warpAffine(src, src, M, dsize, INTER_LINEAR, BORDER_CONSTANT, Scalar()); // Apply the affine transformation Mat M2 = (Mat_<double>(2, 3) << 1, 0, 0, 0, -1, 0); dsize = Size(src.rows, src.cols); warpAffine(src, src, M2, dsize, INTER_LINEAR, BORDER_CONSTANT, Scalar()); // Translate the resulting image back to its original location and display Mat M3 = (Mat_<double>(2, 3) << 1, 0, (src.rows / 2), 0, 1, (src.cols / 2)); dsize = Size(src.rows, src.cols); warpAffine(src, src, M3, dsize, INTER_LINEAR, BORDER_CONSTANT, Scalar()); // This is an extremely cropped version of the input image because // it gets cropped when translated to the origin imshow("Output Image", src); waitKey(); return 0; } NEW CODE: // Read in and display input image Mat src = imread("umichLogo.png"); imshow("Input Image", src); Mat M = (Mat_<double>(3, 3) << 1, 0, -(src.rows / 2), 0, 1, -(src.cols / 2), 0, 0, 1); Mat M2 = (Mat_<double>(3, 3) << 1, 0, 0, 0, -1, 0, 0, 0, 1); Mat M3 = (Mat_<double>(3, 3) << 1, 0, (src.rows / 2), 0, 1, (src.cols / 2), 0, 0, 1); Mat Composition = M3 * (M2 * M); Size dsize = Size(src.rows, src.cols); warpPerspective(src, src, Composition, dsize, INTER_LINEAR, BORDER_CONSTANT, Scalar()); imshow("Output Image", src); waitKey(); return 0;
To avoid undesired cropping, transform once only (simultaneously). Mat M = (Mat_<double>(3, 3) << 1, 0, -(src.rows / 2), 0, 1, -(src.cols / 2), 0,0,1); Mat M2 = (Mat_<double>(3, 3) << 1, 0, 0, 0, -1, 0, 0,0,1); Mat M3 = (Mat_<double>(3, 3) << 1, 0, (src.rows / 2), 0, 1, (src.cols / 2), 0,0,1); Mat Composition = M3 * (M2 * M); Size dsize = Size(src.rows, src.cols); warpPerspective(src, src, Composition, dsize, INTER_LINEAR, BORDER_CONSTANT, Scalar()); I found that, rows and cols are mistaken (not only for size but also M and M3). Fixed code is : Mat M = (Mat_<double>(3, 3) << 1, 0, -(src.cols / 2), 0, 1, -(src.rows / 2), 0,0,1); Mat M2 = (Mat_<double>(3, 3) << 1, 0, 0, 0, -1, 0, 0,0,1); Mat M3 = (Mat_<double>(3, 3) << 1, 0, (src.cols / 2), 0, 1, (src.rows / 2), 0,0,1); Mat Comp = M3 * (M2 * M); warpPerspective(src, src, Comp, src.size(), INTER_LINEAR, BORDER_CONSTANT, Scalar());
71,907,197
71,908,010
Can I split my code into header and cpp files at the end of development?
I am coding a minesweeper game and I am currently splitting declarations and code between header and cpp files like you're supposed to, however, this is making it kind of convoluted to keep track of everything. I know this is against best practices, but could I just declare and code everything on cpp files and then split them up into their respective files at the end? Would this mess up anything inside Visual Studio 2019? I feel like it shouldnt but ive had linker problems with VS code in the past and I havent been able to fix them (one of the reasons why I use visual studio for cpp now) so I just want to make sure before I do something thats going to bite me later on. Any insight is appreciated. I know its a lazy way to cope with the problem but Im just trying to get this done quickly.
Declaring and coding everything on cpp files will cause error lnk2005. Putting it all in the header file won't cause the error, although this is also against best practices. But it all depends on personal writing style.In addition, code should be easier for others to read and understand. And It's a good choice to follow experienced people's coding style.
71,907,603
71,907,747
Why is my permutation code generating duplicates?
My code is generating duplicates (3) to be precise and I don't know why, could anyone help out? I've tried searching for a problem, but to my eyes it seems the same as other premutation codes on the internet. I was thinking it could've been a miss-use of the loop but I don't see why it's giving me 9 answers instead of 6. #include <iostream> using namespace std; void swap(char *a, int x, int y); void print(char *a, int n); void permute(char *a, int n, int index); int grabSize(char a[]); int main() { char array[] = {'a', 'b', 'c'}; // PLACE COMPONENTS HERE int n = grabSize(array); // cout << "[" << endl; cout << " "; permute(array, n, 0); cout << endl << "]"; } int grabSize(char a[]) { int i = 0; while (a[i] != '\0') { i++; } return i; } void swap(char *a, int x, int y) { char aux; aux = a[x]; a[x] = a[y]; a[y] = aux; } void permute(char *a, int n, int index) { if (index == n-1) { print(a, n); return; } for (int i = 0; i < n; i++) { swap(a, i, index); permute(a, n, index+1); swap(a, i, index); } } void print(char *a, int n) { cout << " [ "; for (int i = 0; i < n; i++) { cout << a[i]; } cout << " ] "; }
You are getting 9 combinations of string because, in permute(), the for loop variable i initialised with 0: for (int i = 0; i < n; i++) { ^^^ Note that you are calling permute() function recursively to generate the permutations of string and, in every recursive call, the index is incremented by 1 while passing to permute() function but the for loop , in permute() function, starts with 0 and iterate till < n. Hence you are getting n*n combinations of string in output. Instead, the for loop variable i should be initialised with index: for (int i = index; i < n; i++) { ^^^^^ Other problems in your code: This char array[] = {'a', 'b', 'c'}; is array of 3 characters. Note that there is no terminating null character in array array. Passing it to grabSize() function and checking for '\0' character in it will lead to UB as grabSize() function will end up accessing array array beyond its size while looking for null terminating character. To get the size of array, you can simply do sizeof(array)/sizeof(array[0]) in main() function and do away with grabSize() function. If you are inclined to use grabSize() function then either add null terminating character manually char array[] = {'a', 'b', 'c', '\0'}; or initialise array array with string, like this char array[] = "abc"; and then pass it to grabSize() function. Suggestion: In C++, the use of plain C style array is discouraged. C++ has Containers Library, go through it. The sequence container array and vector will be of your interest.
71,907,657
71,907,786
How to take 3 dimensional input for 3D vector?
I have to take input in a 3D vector, of dimension (n,m,4). I have written the following piece of code, which is not working don't know why, please lemme know what I am doing wrong. cin>>n>>m; vector<vector<vector<char>>> v3; for(int i=0;i<n;i++){ vector<vector<char>> v2; for(int k=0;k<m;k++){ vector<char> v1; char a; for(int j=0;j<4;j++){ cin>>a; v1.push_back(a); } v2.push_back(v1); } v3.push_back(v2); } Sample Input:- 2 4 G Y B R B G R Y G Y B R G R B Y B Y G R G B R Y B R G Y B R G Y Thanks in advance :)
You haven't described the problem. Is it a compilation error? A runtime error? Anyway - you're code compiles on MSVC (replaced int with char as already suggested). But it is implemented in an inefficient way, because it involves a lot of copying around std::vectors and using push_back will cause reallocations of the vectors. Since you know the sizes in advances, it is better to allocate beforehand and just fill the std::vectors. Something like: int n=0, m=0; std::cin >> n >> m; std::vector<std::vector<std::vector<char>>> v3(n); for (auto & v2 : v3) { v2.resize(m); for (auto & v1 : v2) { v1.resize(4); for (auto & val : v1) { std::cin >> val; } } } BTW - It's not a good idea to use using namespace std. Always better to avoid it and use std::vector, etc. You can see why here: Why is "using namespace std;" considered bad practice?
71,908,109
71,972,294
BIts Per Sample / Pixel libtiff vs WIC
TIFF *TiffImage; uint16 photo, bps, spp, fillorder; uint32 width,height; unsigned long stripSize; unsigned long imageOffset, result; int stripMax, stripCount; unsigned char *buffer, tempbyte; unsigned short *buffer16; unsigned int *buffer32; unsigned long bufferSize, count; bool success = true; int shiftCount = 0; //read image to InData const char *InFileName = fileName.c_str(); if((TiffImage = TIFFOpen(InFileName, "r")) == NULL){ ErrMsg("Could not open incoming image\n"); return false; } // Check that it is of a type that we support if(TIFFGetField(TiffImage, TIFFTAG_BITSPERSAMPLE, &bps) == 0) { ErrMsg("Either undefined or unsupported number of bits per sample\n"); return false; } TBitPrecision bitPrecision = (TBitPrecision)bps; char* imageDesc = NULL; TIFFGetField(TiffImage, TIFFTAG_IMAGEDESCRIPTION, &imageDesc); // Get actual bit precision for CP Images if (bps > 8 && bps <= 16) { if (GetCpTiffTag(imageDesc, CP_TIFFTAG_BITPRECISION, (uint32*)&bitPrecision) == true) { shiftCount = 16 - bitPrecision; } } In my libtiff implementation I have used 12 bit per pixel image and also 10 bpp it is very easy to set this info in libtiff I can't find a similar way to do so in WIC uint16_t photo, bps, spp, fillorder; uint32_t width,height; unsigned long stripSize; unsigned long imageOffset, result; int stripMax, stripCount; unsigned char *buffer, tempbyte; unsigned short *buffer16; unsigned int *buffer32; unsigned long bufferSize, count; bool success = true; int shiftCount = 0; //read image to InData const char *InFileName = fileName.c_str(); IWICImagingFactory* piFactory = NULL; // Create WIC factory HRESULT hr = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&piFactory) ); // Create a decoder IWICBitmapDecoder *pIDecoder = NULL; IWICBitmapFrameDecode *pIDecoderFrame = NULL; std::wstring ws; ws.assign(fileName.begin(), fileName.end()); // get temporary LPCWSTR (pretty safe) LPCWSTR pcwstr = ws.c_str(); hr = piFactory->CreateDecoderFromFilename( pcwstr, // Image to be decoded NULL, // Do not prefer a particular vendor GENERIC_READ, // Desired read access to the file WICDecodeMetadataCacheOnDemand, // Cache metadata when needed &pIDecoder // Pointer to the decoder ); // Retrieve the first bitmap frame. if (SUCCEEDED(hr)) { hr = pIDecoder->GetFrame(0, &pIDecoderFrame); } else { ErrMsg("Could not open incoming image\n"); } return true; Am I suppose to use EXIF or XMP? how do I find the TIFFTAG's for WIC?
The DirectXTex library has lots of examples of using WIC from C++. You need something like: using Microsoft::WRL::ComPtr; ComPtr<IWICMetadataQueryReader> metareader; hr = pIDecoderFrame->GetMetadataQueryReader(metareader.GetAddressOf()); if (SUCCEEDED(hr)) { PROPVARIANT value; PropVariantInit(&value); if (SUCCEEDED(metareader->GetMetadataByName(L"/ifd/{ushort=258}", &value)) && value.vt == VT_UI2) { // BitsPerSample is in value.uiVal } PropVariantClear(&value); } You should get in the habit of using a smart-pointer like ComPtr rather than using raw interface pointers to keep the ref counts correct.
71,908,718
71,908,920
What does std::filesystem::is_regular_file(path) mean on Windows?
About std::filesystem::is_regular_file(path), cppreference.com says: Checks if the given file status or path corresponds to a regular file […] Equivalent to s.type() == file_type::regular. For example, in the Linux kernel, file types are declared in the header file sys/stat.h. The type name and symbolic name for each Linux file type is listed below: Socket (S_IFSOCK) Symbolic link (S_IFLNK) Regular File (S_IFREG) Block special file (S_IFBLK) Directory (S_IFDIR) Character device (S_IFCHR) FIFO (named pipe) (S_IFIFO) What is the thing that this function checks on Windows?
Since we are talking about Windows we can consider MS implementation of the standard library, and that's how they determine if the file is regular: if (_Bitmask_includes(_Attrs, __std_fs_file_attr::_Reparse_point)) { if (_Stats._Reparse_point_tag == __std_fs_reparse_tag::_Symlink) { this->type(file_type::symlink); return; } if (_Stats._Reparse_point_tag == __std_fs_reparse_tag::_Mount_point) { this->type(file_type::junction); return; } // All other reparse points considered ordinary files or directories } if (_Bitmask_includes(_Attrs, __std_fs_file_attr::_Directory)) { this->type(file_type::directory); } else { this->type(file_type::regular); } So if it isn't IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK or a directory, then it is a regular file.
71,909,245
72,134,309
How to use grpc c++ ClientAsyncReader<Message> for server side streams
I am using a very simple proto where the Message contains only 1 string field. Like so: service LongLivedConnection { // Starts a grpc connection rpc Connect(Connection) returns (stream Message) {} } message Connection{ string userId = 1; } message Message{ string serverMessage = 1; } The use case is that the client should connect to the server, and the server will use this grpc for push messages. Now, for the client code, assuming that I am already in a worker thread, how do I properly set it up so that I can continuously receive messages that come from server at random times? void StartConnection(const std::string& user) { Connection request; request.set_userId(user); Message message; ClientContext context; stub_->Connect(&context, request, &reply); // What should I do from now on? // notify(serverMessage); } void notify(std::string message) { // generate message events and pass to main event loop }
I figured out how to used the api. Looks like it is pretty flexible, but still a little bit weird given that I typically just expect the async api to receive some kind of lambda callback. The code below is blocking, you'll have to run this in a different thread so it doesn't block your application. I believe you can have multiple thread accessing the CompletionQueue, but in my case I just had one single thread handling this grpc connection. GrpcConnection.h file: public: void StartGrpcConnection(); private: std::shared_ptr<grpc::Channel> m_channel; std::unique_ptr<grpc::ClientReader<push_notifications::Message>> m_reader; std::unique_ptr<push_notifications::PushNotificationService::Stub> m_stub; GrpcConnection.cpp files: ... void GrpcConnectionService::StartGrpcConnection() { m_channel = grpc::CreateChannel("localhost:50051",grpc::InsecureChannelCredentials()); LongLiveConnection::Connect request; request.set_user_id(12345); m_stub = LongLiveConnection::LongLiveConnectionService::NewStub(m_channel); grpc::ClientContext context; grpc::CompletionQueue cq; std::unique_ptr<grpc::ClientAsyncReader<LongLiveConnection::Message>> reader = m_stub->PrepareAsyncConnect(&context, request, &cq); void* got_tag; bool ok = false; LongLiveConnection::Message reply; reader->StartCall((void*)1); cq.Next(&got_tag, &ok); if (ok && got_tag == (void*)1) { // startCall() is successful if ok is true, and got_tag is void*1 // start the first read message with a different hardcoded tag reader->Read(&reply, (void*)2); while (true) { ok = false; cq.Next(&got_tag, &ok); if (got_tag == (void*)2) { // this is the message from server std::string body = reply.server_message(); // do whatever you want with body, in my case i push it to my applications' event stream to be processed by other components // lastly, initialize another read reader->Read(&reply, (void*)2); } else if (got_tag == (void*)3) { // if you do something else, such as listening to GRPC channel state change, in your call, you can pass a different hardcoded tag, then, in here, you will be notified when the result is received from that call. } } } }
71,910,536
71,910,644
error: no matching function for call to ‘Point::Point()
So i created the class Point and want to use it as the parameter of the constructor in the class Circle , but the error : There is no default constructor for class "Point" shows up and I dont know how to fix it. The code is represented below this text: class Point { private: int x, y; public: Point(int X, int Y) { x = X; y = Y; } }; class Circle { private: int radius; Point centre; public: Circle(Point q, int r) { centre = q; radius = r; } }; int main() { Point obj = Point(3, 4); Circle obj = Circle(obj, 3); }
The first problem is that when the constructor Circle::Cirlce(Point, int) is implicitly called by the compiler, before executing the body of that ctor, the data members centre and radius are default initialized. But since you've provided a user-defined ctor Point::Point(int, int) for class Point, the compiler will not synthesize the default ctor Point::Point(). Thus, the data member centre cannot be default initialized. To solve this you can use constructor initializer list as shown below. The constructor initializer list shown below, copy initialize the data member centre instead of default initializing it. class Point { private: int x, y; public: Point(int X, int Y) { x = X; y = Y; } }; class Circle { private: int radius; Point centre; public: //--------------------------vvvvvvvvvvvvvvvvvvvv--->constructor initializer list used here Circle(Point q, int r): radius(r), centre(q) { } }; int main() { Point obj = Point(3, 4); Circle circleObj(obj,4); } Demo Additionally, you had 2 objects with the same name obj inside main.
71,911,012
71,925,416
How to make StopWatch in QT c++?
I'm making an app on QT with UI. Also, I have a function. I want to display the running time of a function. I also want to pause the stopwatch. Any ideas on how to properly embed a stopwatch in my application? Here is my code: void SomeFunc() { while (1) { // Start Timer // some code // Stop Timer // Start Timer2 // some code // Stop Timer2 } } on_push_button() { auto futureWatcher = new QFutureWatcher<void>(this); QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater); auto future = QtConcurrent::run( [=]{ PackBytes( file_path, file_name, isProgressBar); }); futureWatcher->setFuture(future); }
Use QElapsedTimer for measuring the duration since starting the computation. Judging from your previous questions on very related topics, you do have a MainWindow class that contains the on_push_button function. In that class, declare the QElapsedTimer member; then start it when your computation starts. Use a QTimer to update the GUI element you use for displaying the current duration (only needs to run once a second or so). Example code: in your header file: #include <QElapsedTimer> #include <QTimer> //... class MainWindow { // ... other stuff you have private: QTimer m_stopwatchUpdate; QElapsedTimer m_stopwatchElapsed; }; in your cpp file: void MainWindow::on_push_button() { // ideally do this once only in the constructor of MainWindow: connect(&m_stopwatchUpdate, &QTimer::timeout, this, [=]{ //.. update GUI elements here... }); auto futureWatcher = new QFutureWatcher<void>(this); connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater); auto future = QtConcurrent::run( [=]{ m_stopwatchElapsed.start(); PackBytes(file_path, file_name, isProgressBar); }); m_stopwatchUpdate.start(1000); futureWatcher->setFuture(future); }
71,911,323
71,975,395
Questions regarding Red-Black Tree Deletion (z has 2 children) (pre-fixDelete)
Code Source - https://github.com/Bibeknam/algorithmtutorprograms/blob/master/data-structures/red-black-trees/RedBlackTree.cpp y = z; int y_original_color = y->color; if (z->left == TNULL) { x = z->right; rbTransplant(z, z->right); } else if (z->right == TNULL) { x = z->left; rbTransplant(z, z->left); } else { y = minimum(z->right); y_original_color = y->color; x = y->right; if (y->parent == z) { x->parent = y; \\ [1] Local Class TNull } else { rbTransplant(y, y->right); \\ [2] Losing Y y->right = z->right; y->right->parent = y; } rbTransplant(z, y); y->left = z->left; y->left->parent = y; y->color = z->color; \\ [3] Need of Recoloring } Questions Local Class TNull - (In case y->right is a TNull) Within this class function, TNull is a local pointer simply passed to x; isn't changing the parent of x also change the parent of the local TNull? Losing Y - This section is meant to be executed in case the minimum in right subtree of z is not a direct children. Later it will be placed at z's location. Won't this segment only pivot y->right / x until it reaches z's location, instead of y / minimum? Need of Recoloring - Iirc, recoloring will also happen in the later fixDelete() function call, why is this needed? Please bear with me, I'm slow in this kind of stuff and I'm really at my wits' end. This is the first time I'm asking here. Thank you.
On your questions Yes that can happen, TNull's parent is set and the authors remark that this is a deliberate design choice which they exploit. y is moving to where z is and this just fixes y so its pointers are what z had. s No. Essentially when the node to be deleted has 2 children, you find the successor or predecessor node (which has to have 0 or 1 child) and swap the nodes. You then delete the node at the successor or predecessor node position. The predecessor or successor node swapped, preserves the tree ordering. But the important thing is in swapping the nodes, the colour is not swapped, it must be preserved so the red-black tree properties are still correct. This is what y_original_color is for.
71,911,487
71,911,784
OpenCV output monochrome TIFF group 4 compression
Is there a way to output monochrome TIFF files in OpenCV with group 4 compression? This is the command to do it with imagemagick/graphicsmagick 'gm convert '.$file.' -type bilevel -monochrome -compress group4 '.$output OpenCV version 4.5.1 update # g++ -Wall -O3 -std=c++17 main.cpp -o main `pkg-config opencv4 --cflags --libs` -ltiff find doesn't return anything root@x:/usr/include/opencv4/opencv2# find . -name "*tif*" code #include <tiffio.h> #include <opencv4/opencv2/opencv.hpp> std::vector<int> params = {cv::IMWRITE_TIFF_COMPRESSION, COMPRESSION_CCITTFAX4}; cv::imwrite(_output, src_bin, params); error [ WARN:0] global ../modules/imgcodecs/src/grfmt_tiff.cpp (914) writeLibTiff OpenCV TIFF(line 914): failed TIFFSetField(tif, TIFFTAG_PREDICTOR, predictor) imwrite_('out.tif'): can't write data: OpenCV(4.5.1) ../modules/imgcodecs/src/grfmt_tiff.cpp:914: error: (-2:Unspecified error) OpenCV TIFF: failed TIFFSetField(tif, TIFFTAG_PREDICTOR, predictor) in function 'writeLibTiff'
OpenCV uses libtiff (link). If you call cv.imwrite (link) you can pass additional parameters. For group 4 compression the docs say that you have to pass the IMWRITE_TIFF_COMPRESSION flag (link) with value COMPRESSION_CCITTFAX4 (link). Example: #include <tiffio.h> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; vector<int> params = {IMWRITE_TIFF_COMPRESSION, COMPRESSION_CCITTFAX4}; bool success = imwrite("image.tif", img, params); Update Well, this is how it should work. But it seems that opencv4 currently has one or more issues in writing Group 4 TIFF. Btw it's the same when you try the python-lib. This known issue deals with a predictor tag that is wrongly added by opencv. I applied the fix to my local build but after that one more issue came up missing a conversion of the 8bit Mat to 1bit/sample for group4. So my recommendation is: Workaround Instead you can use the GraphicsMagick API Magick++. #include <opencv2/opencv.hpp> #include <Magick++.h> using namespace cv; using namespace Magick; int main(int argc, char* argv[]) { InitializeMagick(""); Mat img = imread("img.png"); Image image(img.cols, img.rows, "BGR", CharPixel, (char *)img.data); image.compressType(CompressionType::Group4Compression); image.write("img.tif"); return(0); }
71,911,501
71,911,564
C++ return char* then delete it
So I have this function: char * func() { char * temp = new char[length]; // Length is defined elsewhere /* Do some stuff with temp */ return temp } My problem is I'm not sure whether or not this leaks memory. If so, I don't know how to make it not do that. I thought I could delete it after return, but how would I do that? (Also assuming i can't just delete it outside the function) This function is part of a class. This function's purpose is to return an internal value of the class. A user would use this function. i find it too much to ask that the user deletes the value afterwards. Thanks!
My problem is I'm not sure whether or not this leaks memory. This doesn't leak memory, because the pointer to the allocation is returned and thus the ownership is transferred to the caller. If the caller loses the returned pointer value before deleting it, then the caller has leaked memory. That said, this is a bad design. You should avoid owning bare pointers. Instead, in this case I recommend returning a vector. This way the vector template will take care of releasing the allocated memory: std::vector<char> func() { std::vector<char>(length) temp; /* Do some stuff with temp */ return temp; } Alternatively, you could consider using std::string if the array represents text.
71,911,677
71,911,799
Is there a performance difference between assigning before returning and directly returning in C++?
Is there a performance difference between the two following functions, or is it handled by the compiler the same? double f1(double a, double b) { return a + b; } double f2(double a, double b) { double sum = a + b; return sum; } Thanks.
Is there a performance difference between the two following functions One function contains two statements and the other contains one statement. or is it handled by the compiler the same? They can be. Both functions have identical observable behaviour, so they may produce an identical program.
71,911,860
71,911,983
Dereferencing std::vector passed by reference
I have a quick (and possibly stupid) question, but I couldn't find an answer online: When I pass a struct by reference, I can nicely and cleanly access its fields via MyArray->Field1, MyArray->Field2 etc. Is there a similar way to do this for the elements of a std::vector? The only way to do this I know, is something like MyVector[0][0], MyVector[0][1] etc. or maybe do something like std::vector<double> MyVector2 = *MyVector; and then MyVector2[0, 1, 2...] = 1.0... Edit: Wow, was Stackoverflow quick closing my question... I think, I got passing by reference and passing by pointer confused. I'm not sure, what the better solution in my case is: Basically I have a class where I set a std::vector* to an "external" std::vector. It uses this vector a lot of times, so I don't want to copy it all the time for performance reasons (and also the class changes it). Passing it by pointer, as mentioned above, I have to write something like MyVector[0][0] = 3; and while this works perfectly, it just doesn't look very nice. The better way of writing this, according to wohlstads answer (thank you for the good explanation) would be (*MyVector)[0] = 3;.
Passing a std::vector by refernce allows you to access its public members, e.g.: void f(std::vector<int> & v) { v.resize(1); v[0] = 3; } However, the syntax you used your question actually looks like passing by pointer. You can do that as well with a std::vector but in C++ we usually prefer to pass by reference. If you have a good reason to pass by pointer instead of a reference, you can do it like that: void f(std::vector<int> * pV) { pV->resize(1); (*pV)[0] = 3; } The brackets around *pV are necessary because operator [] has precedence over the dereferencing operator (*); without those, *pV[0] will be interpreted as *(pV[0]).
71,912,177
71,915,998
pybind11 how to cast double pointer argument implicitly to long value?
I'm trying to expose c++ library with classes that have function members that receives double pointer argument (for initialization) to python via pybind11. For example: class IInitializer{ virtual bool CreateTexture(ITexture **out_pTex, UINT Width, UINT Height) = 0; } I know that pybind11 has no support out-of-the-box for double pointer argument. in the python side I would like to receive the out_pTex as long number or opaque pointer. I do not need to do anything with this pointer on the python side just pass it as handle to other c++ functions. I tried to create custom type caster like this: template <> struct type_caster<ITexture*> : public type_caster_base<ITexture*> { using base = type_caster_base<ITexture*>; public: PYBIND11_TYPE_CASTER(ITexture*, const_name("ITexture*")); bool load(handle src, bool) { value = reinterpret_cast<ITexture*>(PyLong_AsVoidPtr(src.ptr())); return true; } static handle cast(ITexture* src, return_value_policy, handle) { return PyLong_FromVoidPtr((void*)src); } }; but I keep getting compilation errors like: no known conversion for argument 1 from ‘pybind11::detail::type_caster_base<ITexture>::cast_op_type<ITexture**&&> {aka ITexture*}’ to ‘ITexture**’ Anyone has a suggestion how to expose double pointer to some class (as opaque or long number) to python?
I would write the glue code into a lambda: IInitializerWrap.def("CreateTexture", [](const IInitializer& self, UINT Width, UINT Height) { ITexture* rv; self.CreateTexture(&rv, Width, Height); return rv; // Or reinterpret_cast if you prefer to. });
71,912,373
71,912,773
How to store values from a normal array to a 2D array in C++?
I want to store the Values to the CustomValues array. How can I do this? Any code and explanation would be great. int main() { int CustomValues[4][3]; int Values[3] = {234, 98, 0}; int Values1[3] = {21, 34, 5}; int Values2[3] = { 12, 6, 765 }; int Values3[3] = { 54, 67, 76 }; } The CustomValues array should look like: {{234, 98, 0}, { 21, 34, 5 }, { 12, 6, 765 }, { 54, 67, 76 }}
There's a few different ways you can do this. Since we already know your constraints, I've taken liberties to not do this dynamically. The first is memcpy, which is in the <cstring> header: memcpy(CustomValues[0], Values, sizeof(Values)); memcpy(CustomValues[1], Values1, sizeof(Values1)); memcpy(CustomValues[2], Values2, sizeof(Values2)); memcpy(CustomValues[3], Values3, sizeof(Values3)); Another is to loop through the array and store the values individually: for (int i = 0; i < sizeof(CustomValues)/sizeof(CustomValues[0]); i++) { for (int j = 0; j < sizeof(CustomValues[0])/sizeof(CustomValues[0][0]); j++) { if (i == 0) { CustomValues[i][j] = Values[j]; } else if (i == 1) { CustomValues[i][j] = Values1[j]; } else if (i == 2) { CustomValues[i][j] = Values2[j]; } else if (i == 3) { CustomValues[i][j] = Values3[j]; } } } There is probably a better way to handle the logic for selecting which Values array you want, but that was just a quick solution to demonstrate. EDIT: Example of 2D Vector usage This example doesn't contain the logic for actually controlling the number of elements in a vector, but you can simply do that by following the for loop logic. Basically, you just need something to check the size of your vector with size(), and then move to a different one. #include <iostream> #include <vector> using namespace std; int main() { vector<vector<int>> CustomValues; //2D vector //1D vectors vector<int> Values; vector<int> Values1; Values.push_back(234); //to insert a value individually Values.insert(Values.end(), {98, 0}); //to append multiple values Values1.insert(Values1.end(), {21, 34, 5}); //inserting the 1D arrays to the 2D arrays CustomValues.push_back(Values); CustomValues.push_back(Values1); //example of getting # of elements int countOfInnerVectors = 0; for (int i = 0; i < CustomValues.size(); i++) countOfInnerVectors++; cout << "The number of 1D vectors in CustomValues is: " << countOfInnerVectors; } An example of checking for the correct amount of vectors would be: //check if we have less than 10 inner vectors int maxCustomValuesSize = 10; if (CustomValues2.size() < maxCustomValuesSize) In this example, you would have something like int index = 0, and when that if is no longer satisfied, you could do index++ or some other logic to start inserts at your new index, like CustomValues2[index].push_back(Values);. You can follow the same logic for the inner vectors as well, you would just be changing to a new 1D array instead of changing to a new "row" like the outer vector does.
71,912,427
71,913,202
Why does this code with SFINAE compiles error, even though there is a template that can match
The code is as follows. #include <tuple> #include <array> template <typename T, typename Type> struct Vec { using value_type = T; static constexpr size_t size() { return Type::size; } }; template <size_t Size> struct Const { static constexpr size_t size = Size; }; template <class T, class Type, class = void> struct vec_size_impl {}; template <class T, class Type> struct vec_size_impl<T, Type, std::enable_if_t<std::is_arithmetic_v<T>>> : std::integral_constant<size_t, Type::size> {}; template <class T, class Type> inline constexpr size_t Vec_size_v = vec_size_impl<T, Type>::value; template<class T, class Type, size_t... Sizes> // template<size_t... Sizes, class T, class Type> std::enable_if_t< ((0 + ... + Sizes) == Vec_size_v<T, Type>), std::tuple<Vec<T, Const<Sizes>>...> > split(const Vec<T, Type>&) noexcept { return std::make_tuple<Vec<T, Const<Sizes>>...>(); } template<class V, class Type> std::enable_if_t< (Vec_size_v<typename V::value_type, Type> % V::size() == 0), std::array<V, Vec_size_v<typename V::value_type, Type> / V::size()> > split(const Vec<typename V::value_type, Type>&) noexcept { return std::array<V, Vec_size_v<typename V::value_type, Type> / V::size()>(); } int main() { Vec<int, Const<6>> a; split<Vec<int, Const<2>>, Const<6>>(a); return 0; } Here (I think) the second split() can be matched, but I still got a compile error for the substitution fail of the first template. What is the reason for this? I have not yet found an entry in the C++ standard that can explain this problem. (This appears to be related to variadic templates, because if I modify the order of the template parameters and put the parameter pack in the first place, the code would compile correctly.)
SFINAE applies only if the invalid type or expression resulting from a use of a template parameter appears within: a template parameter declaration within the same template parameter list a default template argument which is used (or will be if overload resolution or class partial specialization matching selects the template) for a function template, the declared type of the function (including its function parameter types, return type, or exception specification, but not when deducing a placeholder return type from return statements), for a function template, its explicit(constant-expression) specifier, if any for a class template partial specialization, the template arguments specified after the template name See [temp.deduct]/8 - this is the "immediate context" rule. Substitution of all type aliases and type alias templates happens essentially "before" template argument substitution, since [temp.alias]/2 says a use of the alias template is always equivalent to its substitution. For example, this explains why SFINAE applies to the ::type member lookup in a std::enable_if_t within a function type - it is equivalent to the written-out typedef std::enable_if<...>::type, so when this forms an invalid type, it's considered to be in the "immediate context" of the function template argument substitution. Type aliases don't actually get "instantiated" at all like function templates, class templates, and variable templates do. When overload resolution considers the first split template, it tries to get the value of Vec_size_v<Vec<int, Const<2>>, Const<6>>, which causes an implicit instantiation of that specialization of the variable template. The evaluation of that variable template's initializer is within that variable template instantiation, not within the function template's function type, so SFINAE does not apply and the variable template has an error, even though it happened during a template argument deduction for overload resolution. The obvious workaround, though probably not what you want, is to require the longer Vec_size<T, Type>::value instead of Vec_size_v<T, Type>. Or you could give the primary template for vec_size_impl a static value member. But it doesn't actually need to have a numeric type: if you do template <class T, class Type, class = void> struct vec_size_impl { struct none_t {}; static constexpr none_t value; }; // partial specialization as before template <class T, class Type> inline constexpr auto Vec_size = vec_size_impl<T, Type>::value; then the same declaration of the first split would get an actual valid constant expression for its Vec_size_v use, but an invalid expression (0 + ... + Sizes) == Vec_size_v<T, Type> since there's no matching operator==. But this invalid expression is within the function template's function type, so then SFINAE can discard the function template from the overload resolution process.
71,912,564
71,913,123
Can ranges::equal be used as a predicate for a pair of transform_view ranges?
Example Program and Compiler Errors The following code produces two compiler errors (MSVC++ 2022 compiling with /std:c++latest because <ranges> isn't yet enabled for /std:c++20 at time of writing this question): error C2672: 'operator __surrogate_func': no matching overloaded function found error C7602: 'std::ranges::_Equal_fn::operator ()': the associated constraints are not satisfied #include <iostream> #include <ranges> #include <algorithm> #include <string> #include <cctype> int main() { using std::views::transform; std::vector<std::string> foo{ "THe", "CaT", "SaT", "oN", "THe", "MaT" }; std::vector<std::string> bar{ "The", "Cat", "Sat", "On", "The", "Mat" }; bool are_equal = std::ranges::equal( foo | transform(transform(std::tolower)), bar | transform(transform(std::tolower)), std::ranges::equal ); std::cout << "vectors 'foo' and 'bar' are equal? - " << std::boolalpha << are_equal << std::endl; } Analysis My guess regarding the first error __surrogate_func appears to be attempting to use operator== between the two transform_view::iterators (As far as I can tell, the iterator defines operator==). The second error appears to relate to a constraint for std::ranges::equal::operator(). As far as I can tell, a constraint does not seem to be satisfied by transform_view, or perhaps more specifically, transform_view::iterator. Looking at the source for ..\include\algorithm, ranges::equal is an instance of class _Equal_fn, with _Equal_fn::operator() having constraint requires indirectly_comparable<iterator_t<_Rng1>, iterator_t<_Rng2>. I'm struggling to find anything on cppreference/ranges/transform_view to suggest that the transform_view::iterator is required to conform to this constraint, so I assume it's not supposed to. However the implementation _Equal_fn clearly behaves as-expected when bypassed using a lambda without any constraints to wrap ranges::equal. This alternative implementation compiles in MSVC++ and produces the expected result: auto lambda_equal = [](const auto& lhs, const auto& rhs) { return std::ranges::equal(lhs, rhs); }; // Now it compiles (MSVC++) bool are_equal = std::ranges::equal( foo | transform(transform(std::tolower)), bar | transform(transform(std::tolower)), lambda_equal ); (Which could be made a little more generic using a python-esque decorator pattern to make it generic enough for any other binary functionoid): constexpr auto binary_invocable = [](const auto& fn) { return [&fn](const auto& lhs, const auto& rhs) { return fn(lhs, rhs); }; }; // Now it compiles (MSVC++) bool are_equal = std::ranges::equal( foo | transform(transform(std::tolower)), bar | transform(transform(std::tolower)), binary_invocable(std::ranges::equal) ); Question: On the basis that the problem appears to be with the constraint and not a lack of an iterator::operator== (), is there any way, using standard library functions/functors to either wrap range::equal or to wrap transform_view, as a means to satisfying the indirectly_comparable<iterator_t<Rng1>, iterator_t<Rng1> constraint?
Can ranges::equal be used as a predicate for a pair of transform_view ranges? No, it cannot. This is because ranges::equal is colloquially referred to as a niebloid (cppref, blog). In the standard, they are defined in [algorithms.requirements]/2: The entities defined in the std​::​ranges namespace in this Clause are not found by argument-dependent name lookup ([basic.lookup.argdep]). When found by unqualified ([basic.lookup.unqual]) name lookup for the postfix-expression in a function call ([expr.call]), they inhibit argument-dependent name lookup. That's it. Namely, ranges::equal is still presented as a function template - just as this special kind of function template that inhibits, and is not found by, argument-dependent lookup. The only way to implement that in C++ today is as a function object. But they're not specified as function objects, so you cannot rely on function-object-like properties. Like copyability. libstdc++ simply implements them as empty function objects, but MSVC deliberately chooses to not provide any functionality not specified in the standard. Hence in MSVC's implementation, ranges::equal is not copyable -- because it is not specified to be an object, it's specified as a function template, and you cannot use function templates that way.
71,912,594
71,913,133
Threading returns unexpected result - c++
I'm learning about threads for homework, and I've tried to implement threading on a simple program I've made. Without threading the program works perfectly, but when I thread the two random number generator functions, it returns incorrect results. The result always seems to be '42' for both number generators, not sure why this would be the case. Also for context, I'm just starting with threads so I understand this program doesn't need multithreading. I'm doing it just for learning purposes. Thanks for any help! // struct for vector to use struct readings { std::string name; int data; }; // random generator for heat value - stores in vector of struct void gen_heat(std::vector<readings>& storage) { readings h = {"Heat", rand() % 100 + 1}; storage.insert(storage.begin(), h); } // random generator for light value - stores in vector of struct void gen_light(std::vector<readings>& storage) { readings l = {"Light", rand() % 100 + 1}; storage.insert(storage.begin(), l); } int main() { // vector of readings struct std::vector<readings> storage; srand(time(NULL)); // initialising threads of random generators std::thread H(gen_heat, std::ref(storage)); std::thread L(gen_light, std::ref(storage)); // waiting for both to finish H.join(); L.join(); // print values in vec of struct for (const auto& e : storage) { std::cout << "Type: " << e.name << std::endl << "Numbers: " << e.data << std::endl; } // send to another function smartsensor(storage); return 0; }
Since you have several threads accessing a mutual resource, in this case the vector of readings, and some of them are modifying it, you need to make the accesses to that resource exclusive. There are many ways of synchronizing the access; one of them, simple enough and not going down to the use of mutexes, is a binary semaphore (since C++20). You basically: own the access to the resource by acquiring the semaphore, use the resource, and then, release the semaphore so others can access the resource. If a thread A tries to acquire the semaphore while other thread B is using the resource, thread A will block until the resource is freed. Notice the semaphore is initialized to 1 indicating the resource is free. Once a thread acquires the semaphore, the count will go down to 0, and no other thread will be able to acquire it until the count goes back to 1 (what will happen after a release). [Demo] #include <cstdlib> // rand #include <iostream> // cout #include <semaphore> #include <string> #include <thread> #include <vector> std::binary_semaphore readings_sem{1}; // struct for vector to use struct readings { std::string name; int data; }; // random generator for heat value - stores in vector of struct void gen_heat(std::vector<readings>& storage) { for (auto i{0}; i < 5; ++i) { readings_sem.acquire(); readings h = {"Heat", rand() % 100 + 1}; storage.insert(storage.begin(), h); readings_sem.release(); } } // random generator for light value - stores in vector of struct void gen_light(std::vector<readings>& storage) { for (auto i{0}; i < 5; ++i) { readings_sem.acquire(); readings l = {"Light", rand() % 100 + 1}; storage.insert(storage.begin(), l); readings_sem.release(); } } int main() { // vector of readings struct std::vector<readings> storage; srand(time(NULL)); // initialising threads of random generators std::thread H(gen_heat, std::ref(storage)); std::thread L(gen_light, std::ref(storage)); // waiting for both to finish H.join(); L.join(); // print values in vec of struct for (const auto& e : storage) { std::cout << "Type: " << e.name << std::endl << "Numbers: " << e.data << std::endl; } } // Outputs (something like): // // Type: Heat // Numbers: 5 // Type: Light // Numbers: 83 // Type: Light // Numbers: 40 // ... [Update on Ben Voigt's comment] The acquisition and release of the resource can be encapsulated by using RAII (Resource Acquisition Is Initialization), a mechanism which is already provided by the language. E.g.: Both threads still try and acquire a mutex to get access to the vector of readings resource. But they acquire it by just creating a lock guard. Once the lock guard goes out of scope and is destroyed, the mutex is released. [Demo] #include <mutex> // lock_guard std::mutex mtx{}; // random generator for heat value - stores in vector of struct void gen_heat(std::vector<readings>& storage) { for (auto i{0}; i < 5; ++i) { std::lock_guard<std::mutex> lg{ mtx }; readings h = {"Heat", rand() % 100 + 1}; storage.insert(storage.begin(), h); } }
71,912,838
71,913,058
Subtract extremely small number from one in C++
I need to subtract extremely small double number x from 1 i.e. to calculate 1-x in C++ for 0<x<1e-16. Because of machine precision restrictions for small enoughf x I will always get 1-x=1. Simple solution is to switch from double to some more precise format like long. But because of some restrictions I can't switch to more precise number formats. What is the most efficient way to get accurate value of 1-x where x is an extremely small double if I can't use more precise formats and I need to store the result of the subtraction as a double? In practice I would like to avoid percentage errors greater then 1% (between double representation of 1-x and its actual value). P.S. I am using Rcpp to calculate the quantiles of standard normal distribution via qnorm function. This function is symmetric around 0.5 being much more accurate for values close to 0. Therefore instead of qnorm(1-(1e-30)) I would like to calculate -qnorm(1e-30) but to derive 1e-30 from 1-(1e-30) I need to deal with a precision problem. The restriction on double is due to the fact that as I know it is not safe to use more precise numeric formats in Rcpp. Note that my inputs to qnorm could be sought of exogeneous so I can't to derive 1-x from x durning some preliminary calculations.
Simple solution is to switch from double to some more precise format like long [presumably, double] In that case you have no solution. long double is an alias for double on all modern machines. I stand corrected, gcc and icc still support it, only cl has dropped support for it for a long time. So you have two solutions, and they're not mutually exclusive: Use an arbitrary precision library instead of the built-in types. They're orders of magnitude slower, but if that's the best your algorithm can work with then that's that. Use a better algorithm, or at least rearrange your equation variables, to not have this need in the first place. Use distribution and cancellation rules to avoid the problem entirely. Without a more in depth description of your problem we can't help you, but I can tell you with certainty that double is more than enough to allow us to model airplane AI and flight parameters anywhere in the world.
71,913,815
71,913,894
How to improve operator overloading for my class?
I have started learning C++. My teacher gave an assignment. I completed it (some polishing work is left) and everything seems to work but there is redundancy. My major issue is overloading. How to improve overloading in my class. Rather than writing all four functions (two for fstream and two for iostream), is it possible to write only two ? Any other suggestions to improve the code further ? #include <iostream> #include <fstream> #include <string> #include "../../my_func.hpp" #define usi unsigned short int using namespace std; class book { public: usi book_id = 0, price = 0, no_of_pages = 0, year_of_publishing = 0; string author_name = "NONE", publisher = "NONE"; book(usi b_id = 0, usi b_price = 0, usi b_no_of_pages = 0, usi b_year_of_publishing = 0, const string& b_author_name = "NONE", const string& b_publisher = "NONE") { book_id = b_id; price = b_price; no_of_pages = b_no_of_pages; year_of_publishing = b_year_of_publishing; author_name = b_author_name; publisher = b_publisher; } friend fstream& operator >> (fstream& is, book& obj); friend fstream& operator << (fstream& os, const book& obj); friend istream& operator >> (istream &is, book& obj); friend ostream& operator << (ostream &os, const book& obj); }; fstream& operator >> (fstream &is, book& obj) { char ch; is >> obj.book_id >> obj.price >> obj.no_of_pages >> obj.year_of_publishing; is.ignore(1, '\n'); //To take care of new line character getline(is, obj.author_name); getline(is, obj.publisher); return is; } fstream& operator << (fstream &os, const book& obj) { os.operator<<(obj.book_id) << '\n' //calling operator function cuz it works << obj.price << '\n' << obj.no_of_pages << '\n' << obj.year_of_publishing << '\n'; os << obj.author_name << '\n' << obj.publisher << '\n'; return os; } istream& operator >> (istream &is, book& obj) { is >> obj.book_id >> obj.price >> obj.no_of_pages >> obj.year_of_publishing; is.ignore(1, '\n'); //To take care of new line character getline(is, obj.author_name); getline(is, obj.publisher); return is; } ostream& operator << (ostream &os, const book& obj) { os << obj.book_id << '\n' << obj.price << '\n' << obj.no_of_pages << '\n' << obj.year_of_publishing << '\n' << obj.author_name << '\n' << obj.publisher << '\n'; return os; } int main() { string path = ".\\C++_Experiment\\Exp-7\\Files\\Source.txt"; book b1(12, 3000, 100, 2003, "Lol", "Pew"), b2, b3; fstream fio; fio.open(path, ios::out | ios::app | ios::in); if(fio) fio << b1; else cout << "error"; fio.seekg(0, ios::beg); if(fio) fio >> b2 >> b3; cout << b2 << b3; fio.close(); cout << "DONE"; return 0; }
You only need two overloads here. ifstream and ofstream inherit from istream and ostream respectively so if you have friend istream& operator >> (istream &is, book& obj); friend ostream& operator << (ostream &os, const book& obj); then those will work with cout and cin, and any fstream or stringstream objects as they also inherit from istream and ostream.
71,914,593
71,983,793
Remotely debugging android NDK app using VSCode
I've tried a number of ways to get this to work but to no avail so far. My requirements are as follows: To be able to connect using visual studio code & gdb to a debug-enabled APK process running on an android device The device should not have to be rooted I expect full visual debugging of C++ NDK code on that device. Java code would be nice too but C++ is what I'm interested in. I'm aware that the gdb server must run on the device. A python script in the NDK (ndk-gdb) can copy this to the device and execute it, which then launches its own shell which can be used to set breakpoints, which is useful in a pinch but nowhere near as intuitive as a full GUI. So, given that the gdb-server is now running on the device, I should be able to connect to it. I'm trying to use this 'launch.json' debug config in vs-code: { "name": "Debug App on Device", "type": "cppdbg", "request": "launch", "cwd": "${workspaceRoot}", "program":"${workspaceRoot}\\android-build\\DebugSys\\system\\bin\\app_process64", "additionalSOLibSearchPath": "${workspaceRoot}\\android-build\\obj\\local\\arm64-v8a", "miDebuggerServerAddress": "192.168.1.121:5039", "setupCommands": [{ "text": "set solib-absolute-prefix ${workspaceRoot}/android-build/", "ignoreFailures": false }], "windows": { "miDebuggerPath": "C:\\Users\\luthe\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620\\prebuilt\\windows-x86_64\\bin\\gdb.exe", "MIMode": "gdb" } }, But running it gives me this error: (No connection could be made because the target machine actively refused it). This probably isn't a firewall issue as I'm able to connect to another server I have running, launched by the app in question on port 8080. Is there an error in my 'launch.json' or am I going about all of this in entirely the wrong way. Also, would it make sense for my app to launch the gdb server instead or is it better/neutral to have ndk-gdb do it?
In then end, I eschewed lldb in favour of gdb, which ndk-debug can use (for now, they're depreciating it, even though it works and lldb clearly either does not work or requires some setting that it doesn't advertise to work) if you include the 'no_lldb' flag or set 'use_lldb' to 'False' in ndk-gdb.py. However, if you want visual debugging, you have to not let ndk-dbg.py launch the local gdb client. I've done this by creating a minimal batch file that connects to the phone and this may be useful for people reading this in the future in order to have a clear overview of what's happening on the android device and on the local machine. This script assumes only one device is attached for clarity. adb shell forward tcp:5039 localfilesystem:/data/user/0/yourorg.yourapp/debug_socket #forward port 5039 to a temporary file called 'debug_socket'. I believe this is called is a 'Unix domain socket' adb shell run-as yourorg.yourapp rm /data/user/0/yourorg.yourapp/debug_socket #remove the old socket file adb push libs\arm64-v8a\gdbserver /data/local/tmp/arm64-gdbserver #push the arm64-gdbserver to a temp dir on the device adb shell run-as yourorg.yourapp "cp /data/local/tmp/arm64-gdbserver /data/user/0/yourorg.yourapp/arm64-gdbserver" #copy the gdbserver to a directory from which it can be run with the privilages of the app you wish to debug adb shell run-as yourorg.yourapp chmod 700 /data/user/0/yourorg.yourapp/arm64-gdbserver #Ensure 'arm64-gdbserver' is executable adb shell run-as yourorg.yourapp /data/user/0/yourorg.yourapp/arm64-gdbserver --once +/data/user/0/yourorg.yourapp/debug_socket --attach 1234 #Run gdb server on device, connecting to the societ and the process '1234' (replace with actual PID of your running process) Where 'yourorg.yourapp' is the name of your org and app and 1234 is the PID of the process to be debugged on your android device. In visual studio code, you will need to have C++ extensions and gdb debugger extensions installed. This is the 'launch.json' script that launches gdb locally and connects to the android device. Note that symbols are needed on the client side but not on the android device, so they can stripped if needed. { "name": "Debug pilkapel on device", "type": "cppdbg", "request": "launch", "cwd": "${workspaceRoot}", "program":"${workspaceRoot}\\android-build\\DebugSys\\system\\bin\\app_process64", "additionalSOLibSearchPath": "${workspaceRoot}\\android-build\\obj\\local\\arm64-v8a", "miDebuggerServerAddress": "localhost:5039", "setupCommands": [ { "text": "set solib-absolute-prefix ${workspaceRoot}/android-build/", "ignoreFailures": true } ], "windows": { "miDebuggerPath": "C:\\Users\\luthe\\AppData\\Local\\Android\\Sdk\\ndk\\23.1.7779620\\prebuilt\\windows-x86_64\\bin\\gdb.exe", "MIMode": "gdb" } } Also, compiler flags are important for this! These are the compiler flags I used for the debug build of the library I'm working on: LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS) -O0 -g -ggdb -gdwarf64 LOCAL_CPPFLAGS += -gfull -fstandalone-debug -Wl -gno-split-dwarf LOCAL_CPPFLAGS += -fno-unique-internal-linkage-names -fno-direct-access-external-data LOCAL_CPPFLAGS += -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes LOCAL_CPPFLAGS += -Wformat -Werror=format-security -fno-limit-debug-info -fPIC Some of these may be unnecessary for the task at hand, I did really quite a lot of iteration using lldb but nothing worked. For gdb, I believe it needs -gdwarf-5 as the debugging format (which I gather is the default). When I specified -gdwarf-4 as part of my experimentations, the gdb server ran but breakpoints did not work.
71,915,092
71,921,671
ReadConsoleOutputAttribute function usage in c++
I need to get background color by known coord in c++. I tried to use ReadConsoleOutputAttribute from windows.h, but i didn't work. Here is my code: HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); DWORD count; COORD cursor = { this->X, this->Y }; LPWORD *lpAttr = new LPWORD; CONSOLE_SCREEN_BUFFER_INFO info; GetConsoleScreenBufferInfo(console, &info); ReadConsoleOutputAttribute(console, *lpAttr, 1, cursor, &count); What's wrong here and what's the way to fix it? Do I suppose to get background color from lpAttr or what?
Color attributes are specified by TWO hex digits -- the first corresponds to the background; the second the foreground. Each digit can be any of the following values: 0 = Black 8 = Gray 1 = Blue 9 = Light Blue 2 = Green A = Light Green 3 = Aqua B = Light Aqua 4 = Red C = Light Red 5 = Purple D = Light Purple 6 = Yellow E = Light Yellow 7 = White F = Bright White We only need to extract the first digit of the hexadecimal result to know the background color of the current coordinate.This is my test code. I modified the mouse coordinate points to simplify the test. #include <Windows.h> #include <iostream> using namespace std; int main() { //color set test system("color F0"); std::cout << "Hello World!\n" << endl; HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE); if (!Console) return 0; CONSOLE_SCREEN_BUFFER_INFO buf; GetConsoleScreenBufferInfo(Console, &buf); WORD Attr; DWORD Count; COORD pos = buf.dwCursorPosition; ReadConsoleOutputAttribute(Console, &Attr, 1, pos, &Count); //hexadecimal out cout << hex << Attr << endl; if (Attr) { //extract the first digit of the hexadecimal result int color = Attr / 16; switch (color) { case 0:cout << " background color is Black. " << endl; break; case 1:cout << " background color is Blue. " << endl;break; case 2:cout << " background color is Green . " << endl; break; case 3:cout << " background color is Aqua. " << endl; break; case 4:cout << " background color is Red. " << endl; break; case 5:cout << " background color is Purple . " << endl; break; case 6:cout << " background color is Yellow. " << endl; break; case 7:cout << " background color is White. " << endl; break; case 8:cout << " background color is Gray . " << endl; break; case 9:cout << " background color is Light Blue." << endl; break; case 10:cout << " background color is Light Green." << endl; break; //A case 11:cout << " background color is Light Aqua ." << endl; break; //B case 12:cout << " background color is Light Red . " << endl; break; //C case 13:cout << " background color is Light Purple . " << endl; break; //D case 14:cout << " background color is Light Yellow . " << endl; break; //E case 15:cout << " background color is Bright White . " << endl; break; //F default: cout << " error color " << endl; break; } } return 0; }
71,915,138
71,915,540
How do I fix this error in the algorithm header file?
I'm currently writing a code that receives a string as an input, checking whether or not it is comprised of only chars from the car_acc array and, if it isn't the case, requesting the input once again, using a do-while loop. This is the code: char car_acc [11] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ':'}; deque <bool> contr_car; do { cout << "Inserire il tempo di attesa (ore:minuti:secondi) -> "; cin >> tempo; fflush (stdin); lung = (int) tempo.length ()-1; for (; i != lung; i+=1) { contr_car [i] = false; } for (i = 0; i != 11; i+=1) { if (car_acc [i] == tempo [j]) { contr_car [j] = true; } } } while (all_of (contr_car [0], contr_car [lung], true) == false); I'm using the contr_car deque to store whether or not each character in the string is equal to one of those stored in the car_acc array. I'm receiving this error, linking in the algorithm header file: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:926:21: Indirection requires pointer operand ('int' invalid) The error occurs in the part of the file that is defining the all_of function: template <class _InputIterator, class _Predicate> inline _LIBCPP_INLINE_VISIBILITY bool all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred) { for (; __first != __last; ++__first) if (!__pred(*__first)) // error's here return false; return true; } I also get this message on the same line as the while: In instantiation of function template specialization 'std::__1::all_of<bool, bool>' requested here Using the find () function in place of all_of () doesn't fix the error. I'm using a deque since I had to declare it outside of the loop, inside of which I get the size, so arrays weren't an option, and I don't really know how to use vector <bool>, since it works as a bitset. I did include both the algorithm and deque headers. I tried using a vector <int> but it still doesn't work, it only changes the message I get on the line where the while is at: In instantiation of function template specialization 'std::__1::all_of<int, int>' requested here I honestly have no clue how to fix it, since I'm just getting started with C++ and coding in general, so I would be really greatful if you could phrase your anwsers in a easy-to-understand way.
The algorithm std::all_of is intended to invoke a unary predicate on every element within an iteration sequence, reaping either 'true' or 'false' from each, and answering with one encompassing 'true' (everything reported true) or 'false' (at least one thing reported false). To do this, you supply three things: A beginning iterator An ending iterator A callable unary predicate returning a bool. Your code supplies exactly none of those, and therefore it is no wonder it won't compile. An example of how you can use std::all_of is shown below. It isn't intended to be cookie-cutter, so please don't think otherwise. #include <iostream> #include <algorithm> #include <unordered_set> #include <string> int main() { const std::unordered_set<char> car_acc = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ':'}; std::string tempo; do { std::cout << "Inserire il tempo di attesa (ore:minuti:secondi) -> "; std::cout.flush(); if (!(std::cin >> tempo)) { // TODO: handle failure on stdin std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } while ( !std::all_of(tempo.begin(), tempo.end(), [&car_acc](char c){return car_acc.find(c) != car_acc.end();}) ); std::cout << "You entered: " << tempo << '\n'; } This simply creates an unordered set containing what you've deemed are "allowable" characters, then uses that set as the basis for the unary predicate here, a simple lambda: [&car_acc](char c){return car_acc.find(c) != car_acc.end();} This is then fed through std::all_of using the string begin and end iterators. If any character in the string fails to find a match in the set, the result of that match-check will be false, and therefore shall also be the result of std::all_of.
71,915,181
71,915,730
C++ omp for loop with conditional counter (not loop index, not a reduction)
I am parallelizing a code where elements of an array B are a function of elements of an array A. B is smaller than A (i know both sizes in advance) and B[n] is written only if A[n] satisfy a certain condition. A representation of the code would be copy A[n] to B[n] only if A[n] is even, like: #include<omp.h> #include<iostream> bool isEven(int number) { if (number%2 == 0) return true; else return false; } int main() { int array_length = 100; int A [array_length] = {}; int B [array_length/2] = {}; // fill A with natural numbers for (int a=0; a<array_length; a++) { A[a] = a; } int count = 0; #pragma omp parallel for for (int n=0; n<array_length; n++) { if (isEven(A[n])) { #pragma omp critical { count++; B[(count-1)] = A[n]; } } } // print values of b std::cout << "B is : " ; for (size_t i = 0; i < array_length/2; i++) { std::cout << B[i] << ' '; } std::cout << std::endl; return 0; } I am trying several combinations of critical and atomic pragmas, as well as increment of count without any success: there is a race condition on count and the final result is garbage in B. Anyone has any idea on how to make it work?
You say that copying A into B is a "representation" of your code. If computing the B elements actually takes some amount of work, then you could let the A loop be done sequentially, and create tasks for the computation of the B elements.
71,915,275
71,955,385
How to set up the Google Code Jam interactive judge for a C++ solution on Windows?
Here is the Code Jam Interactive problem that I'm trying to test locally. My solution is in C++, my IDE is Visual Studio 2019, and I'm on Windows 10. I have little to no experience with Linux, Bash, Python and I'm stuck. Reading an answer from How to debug Google Code Jam interactive problems on VSCode using python? was not helpful because I'm using a different language and IDE. First thing I did was to download the local_testing_tool.py which is given at the bottom of the problem statement. Then I read the interactive problem section of the CodeJam FAQ which does not go into enough details on how to set up the interactive tool. To test your solution locally, use our interactive_runner script in conjunction with the judge. Instructions are included in the comments I'm stuck on this part. Where do I use the script and how to I use both at the same time? The instructions in the comments do not specify where to run the code.(command prompt? terminal?) Moreover, I watched a video on Youtube where the person runs both python script and C++ script (at around 15 minute mark) in the same IDE. But unfortunately, the person was using Linux instead of Windows. Attempt using Spyder3 to run script I tried running the interactive_runner.py script on Spyder IDE but got this error : AssertionError: There should be exactly one instance of '--' in the command line. Attempt using Ubuntu Following a comment from Codeforces, I installed WSL from the official Microsoft docs. I tried this command python3 interactive_runner.py python3 testing_tool.py 0 -- cpp.exe on Ubuntu Bash, where cpp.exe is the executable file of my solution, but got this error : python3: can't open file 'interactive_runner.py': [Errno 2] No such file or directory Any help is much appreciated. Thank you.
I figured it out. I'll try to explain everything from start. First make sure that you have the compiled your solution and that you have the executable file somewhere. There's an interactive_runner Python script which can be found in the FAQ of CodeJam. Create a Python file named interactive_runner in the same folder as your executable file . The file extension should be .py. Paste the script given on the website in your newly created interactive_runner file then save it. Then download the respective local_testing_tool of the interactive problem you have solved. The link for this file is found at the bottom of problem statement. Fortunately this file is already a python script so you can simply move this file to the previous folder containing the interactive_runner and solution.exe(your executable file) Now you will need to run the following 3 files together : interactive_runner, solution.exe,local_testing_tool. I used Ubuntu to do this. Follow the instructions from the official Microsoft Docs to setup WSL. Open your Ubuntu terminal. Navigate to directory containing the 3 files The path to my folder was C:\Users\user\source\repos\CP\Debug. For Ubuntu, this translates to /mnt/c/Users/user/source/repos/CP/Debug. It will be different for you. I then ran this : cd /mnt/c/Users/user/source/repos/CP/Debug If you need more help on how to change directories, try reading this Running each test set Replace my file path with yours. 1st test set python3 interactive_runner.py python3 local_testing_tool.py 0 -- /nnn/c/Users/user/source/repos/CP/Debug/my_solution.exe 2nd test set python3 interactive_runner.py python3 local_testing_tool.py 1 -- /nnn/c/Users/user/source/repos/CP/Debug/my_solution.exe Notice how there's a single number changing when changing test sets. The number of test sets varies from problem to problem. Remarks All interactive problems uses the same interactive_runner but different local_testing_tool. So you have to download a new local_testing_tool for each interactive problem but there's no need to redownload the interactive runner. Each time you make a change to your source code, you have to recompile your code to update your executable file. Remember that you have to flush the output in your program each time you output something.
71,915,342
72,225,479
LibTorch with OpenCV: version GOMP_5.0 not found
I'm trying to use OpenCV and LibTorch in the same project. Libtorch is installed in /usr/include/libtorch, downloaded from the PyTorch website. I'm using the cxx11 ABI version for CUDA 11.3. Here's my CMakeLists.txt file: cmake_minimum_required(VERSION 3.23 FATAL_ERROR) project(chess-rl VERSION 1.0) find_package( OpenCV REQUIRED ) set(CMAKE_PREFIX_PATH /usr/include/libtorch/share/cmake/) find_package(Torch REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) include_directories(${OpenCV_LIBS}) include_directories(${TORCH_INCLUDE_DIRS}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}") file (GLOB SOURCE_FILES ${PROJECT_SOURCE_DIR}/src/*.cc ${PROJECT_SOURCE_DIR}/src/chess/*.cc ) add_executable(${PROJECT_NAME} ${SOURCE_FILES}) target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS} "${TORCH_LIBRARIES}" ) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20) The program has a #include <opencv2/opencv.hpp> line at the top. Compilation works fine, but running the executable gives me this error: /usr/include/libtorch/lib/libgomp-52f2fd74.so.1: version `GOMP_5.0' not found (required by /usr/lib/libvtkCommonCore.so.1) I believe libtorch is trying to use a library that is incompatible with OpenCV. If I run the program with LD_PRELOAD=/usr/lib/libgomp.so ./build/my-program, it runs fine. How can I fix this error without having to use that environment variable? Is there a way to link that particular library in CMake?
I faced the same problem, and your thread contributed to one solution. You need to add a shared library in your CMakelists.txt file. add_library(libName SHARED IMPORTED) set_property(TARGET libName PROPERTY IMPORTED_LOCATION "/usr/lib/libgomp.so") target_link_libraries(PROJECT_NAME libName) I hope I could help you With kind regards
71,915,764
71,915,931
How does memory work in declaration of structure which uses self-referential structure pointer in C/C++?
In declaration of structure in C/C++, we have to use a self-referential structure pointer instead of a structure itself. // compile error struct stack { int overflow; stack p; } struct stack { int overflow; stack* p; } One brings about the error but the other doesn't under the same condition(declaration) I'm curious about the operation of memory areas when use stack* p; during the declaration and how to make it possible.
This struct stack { int overflow; stack p; } Tries to contains itself , so how big should it be? With one copy of itself it would look line this int ov; { int ov; stack p; } but that stack p needs to be expanded - so we get int ov; { int ov; { int ov; stack p; } } but that stack p needs to be expanded - so we get int ov; { int ov; { int ov; { int ov; stack p; } } } but that stack p needs to be expanded - so we get ...... forever. Look at another way, how many int overflows should the struct contain? The pointer one works like this int overflow; stack *p; The end. The struct is of a well defined size an integer and a pointer
71,915,860
71,916,553
How initialize time points and set them to a falsy value afterward in C++?
I am new to C++ and I want to implement the following behavior. #include <thread> #include <chrono> #include <iostream> using namespace std; int main(){ chrono::high_resolution_clock::time_point start_time_point; while(true){ if(statement_1){ // check whether start_time_point is falsy if(...) start_time_point = chrono::high_resolution_clock::now(); auto current_time_point = chrono::high_resolution_clock::now(); if(chrono::duration_cast<std::chrono::seconds>(current_time_point - start_time_point).count() > 5) { // do something } } if(statement_2){ // assign some falsy value to start_time_point // so that next time the first if block is entered a new time point is assigned to start_time_point } } } I am used to javascript, so in JS I only would assign null to start_time_point in the second if block but in C++ it is different. How would I achieve the above-mentioned behavior?
I am used to javascript, so in JS I only would assign null to start_time_point in the second if block but in C++ it is different. How would I achieve the above-mentioned behavior? A chrono::time_point has a min() member, returning the lowest possible time point. It is not identical, but could be used similar to the null value in javascript. So perhaps start_time_point = start_time_point.min();
71,916,444
71,916,683
Dynamic sized int list
I would like to create a int list in C++, but it just doesn't make sense at all. Also I don't want it to have static size. I tried this, but "array size must be specified in new expressions without an initializer", what should I do? int* list = {}; int* list = new int[]; int list[]; Full code #include <iostream> using namespace std; int* list = new int[]; int main() { int num; cout << "Select number > "; cin >> num; rozloz(num, list); for (int j = 0; j < sizeof(list)/sizeof(list[0]); j++) { cout << list[j] << endl; } } int avaible[] = { 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1 }; void rozloz(int num, int* list) { int i = 0; int i2 = 0; while (num > 0) { int current = avaible[i]; if (current > num) { i++; continue; } list[i2] = current; num -= current; i2++; }; }
"array size must be specified in new expressions without an initializer", what should I do? As per the error message, you should specify a size when you create an array. That size determines how many elements the array has. That said, you normally shouldn't use allocating new expressions at all. See end of the answer for a recommendable solution. sizeof(list)/sizeof(list[0]) This is wrong. This works only with arrays. I recommend using std::size with arrays, so that you won't encounter this problem because the program would safely fail to compile instead of give you the wrong size. The type of list is not an array type. Its type is "pointer to int". It points to first element of a dynamic array. The most convenient way to create a dynamic array is to use std::vector from the standard library. Example: std::vector<int> rozloz(int num) { std::vector<int> list; //... list.push_back(current); // add elements like this //... return list; }