question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
70,239,675
70,248,097
How can I profile a MEX function written using the matlab editor and compiled using gcc
I'd like to profile a mex function I've written in the matlab (2021a) editor. The best I can do right now is to using matlab's tic, toc functions to measure total execution time, but I dont know how to use more detailed diagnostic tools to evaluate the code performance. I've found other questions and responses discussing this issue by using visual studio, but the responses appear to use older versions of visual studio as opposed to my current one of 2019. I'm also not super familiar with visual studio, so I'm not sure where to find some of the tools they mention which appear to have been moved from where they were in previous versions.
There were two solutions I decided to pursue for this. Number one was adding timers to my code as suggested in the comments above (stackoverflow.com/a/47888078/7328782). You can then program your script to output the values to the matlab console using the following code snippet: std::ostringstream stream; stream << "Here is the name/value pair that you entered." << std::endl; displayOnMATLAB(stream); stream << SIG.rows() << " " << SIG.cols() << std::endl; displayOnMATLAB(stream); And make sure to include the following function definition outside the main body of the mexFunction but still inside the class definition of the mexFunction: // outputting to matlab console for debugging void displayOnMATLAB(std::ostringstream& stream) { // Pass stream content to MATLAB fprintf function matlabPtr->feval(u"fprintf", 0, std::vector<matlab::data::Array>({ factory.createScalar(stream.str()) })); // Clear stream buffer stream.str(""); } However, simply timing a piece of c++ code doesn't necessarily give a full picture of what you can optimize with your code. For example, Microsoft visual studio's profiling tools (Detailed introduction/overview/tutorials included here) can tell you how much memory is being consumed at a given line, your processor usage throughout the script and much more. You might be explicitly looking to get a good idea of how neat and efficient a certain line is, or you might catch that an innocuous line could be running fast relative to your bottleneck but is actually consuming far more resources than it should. I decided to simply port my mex function code over to visual studio. Luckily, Matlab support has published a response on their forums explaining how to do this. So far, it seems to be working with 2021a and Visual Studio 2019 even though the response was written for older versions of both Matlab and Visual Studio. (Note, the module definition file only needs you to substitute the MYFILE statement with your project name I think. The other two lines should be left as written) Update The above answer has some issues to be worked out. The best option I've found thus far is using Cris Luengo's approach mentioned in the comment above.
70,239,789
70,240,121
Am I correct about how this C++ code works?
In this code : class iop { public: iop(int y) { printf("OK\n"); } iop() { printf("NO\n"); } }; int main() { line 1- iop o; line 2- o = 8; line 3- return 0; } My conclusion of the way this C++ code work with is: Create an object of iop class (o) using the default parameterless constructor. Create an rvalue object of iop class using the constructor with parameter (int) and using the overloaded operator (operator = (iop&&)) to assign it to the object (o) then call the destructor of that rvalue. Call the destructor of the object (o). Is my conclusion correct? Edit This code also compiled class iop { public: iop(int y) { printf("OK\n"); } iop() { printf("NO\n"); } }; int main() { iop o(5); o = 8; return 0; } output : OK OK That is mean two object are created (o) and one is temporary and the operator= assigen (o) with the temporary object that its constractor argument is 8
The class iop has implicitly defined copy and move constructors and assignments. o = 8; This will attempt to call operator=. As I've stated the copy and move assignment operators are implicitly defined: iop& operator=(const iop&); iop& operator=(iop&&); Because iop is implicitly constructible from int, both operators are viable, but the move one is preferred as is a perfect match. So yes, a temporary is created from 8, that is moved into o. At the end of the full expression (at ;) that temporary is destroyed. At the end of main scope o is destroyed. So your code is more or less equivalent to o = iop{8}. Sidenote: if you make the int constructor explicit i.e. explicit iop(int y) then o = 8; will no longer compile.
70,239,890
70,239,914
What is the difference between iterator and v.begin() method in STL?
#include <iostream> #include <vector> using namespace std; int main(void){ vector<int> v = {1, 2, 3}; auto& it = v.begin(); // 1. v.begin() += 1; cout << *(v.begin()); // output is 1 // 2. cout << *(v.begin()+1); // output is 2 } The upper code shows that v.begin() += 1; doesn't work as I intended. I don't know the actual difference between code1 and code2. Is v.begin() lvalue or rvalue? Or nothing? When it is inserted instead of v.begin() both case returns value 2. Why such things happens?
Is v.begin() lvalue or rvalue? It's an rvalue. auto& it = v.begin(); This is ill-formed because an lvalue reference to non-const cannot be bound to an rvalue. v.begin() += 1; This advances the temporary iterator to the beginning, and discards the result. It "works" if the goal is to do nothing useful. cout << *(v.begin()); // output is 1 This indirects through the iterator to beginning. cout << *(v.begin()+1); // output is 2 This advances the iterator to the beginning, and instead of discarding the result, it indirects through the resulting iterator. v.begin() cannot be changed? then why v.begin()+=1 code is not error? You can change a temporary object returned by the function. But changes to that temporary object have no effect on what v.begin() will return in future. Yes, v.begin() += 1 is a compound assignment to an rvalue. If you come from C, you may be surprised by this since you may have learned that "only lvalues may be the left hand operand of an assignment". But in C++ that only applies to fundamental types, and it does not apply to class types in general. When defining assignment operator overloads for your own classes, it may be useful to use lvalue ref qualified member functions which would prevent direct assignment to an rvalue, and thus would prevent code such as v.begin() += 1. Ref qualifiers were added to the standard later (in C++11), so the pre-existing standard library classes couldn't have those qualifiers, and so assigning rvalues of standard types is unfortunately possible. There was a proposal to add the qualifiers, but it didn't pass due to concerns of backward compatibility. I don't know why, but specifications of new standard classes haven't had qualified assignment operators either.
70,239,955
70,240,051
Calculating the number of elements in an array using pointer arithmetic
I have come across a piece of example code that uses pointers and a simple subtraction to calculate the number of items in an array using C++. I have run the code and it works but when I do the math on paper I get a different answer. There explanation does not really show why this works and I was hoping someone could explain this too me. #include <iostream> using namespace std; int main() { int array[10] = {0, 9, 1, 8, 2, 7, 3, 6, 4, 5}; int stretch = *(&array + 1) - array; cout << "Array is consists of: " << stretch << " numbers" << endl; cout << "Hence, Length of Array is: " << stretch; return 0; } From: https://www.educba.com/c-plus-plus-length-of-array/ When I run the code I get the number 10. When I print the results of *(&array + 1) and array by cout << *(&array+1) << endl; cout << array << endl; I get of course two hex address's. When I subtract these hex numbers I get 1C or 28??? Is it possible that C++ does not actually give the hex results or their translation to decimal but rather sees these numbers as addresses and therefore only returns the number of address slots remaining? That is the closest I can come to an explanation if some one with more knowledge than I could explain this I would be very grateful.
You forgot a small detail of how pointer addition or subtraction works. Let's start with a simple example. int *p; This is pointing to some integer. If, with your C++ compiler, ints are four bytes long: ++p; This does not increment the actual pointer value by 1, but by 4. The pointer is now pointing to the next int. If you look at the actual pointer value, in hexadecimal, it will increase by 4, not 1. Pointer subtraction works the same way: int *a; int *b; // ... size_t c=b-a; If the difference in the hexadecimal values of a and b is 12, the result of this subtraction will not be 12, but 3. When I subtract these hex numbers I get 1C or 28 ??? There must've been a mistake with your subtraction. Your result should be 0x28, or 40 (most likely you asked your debugger or compiler to do the subtraction, you got the result in hexadecimal and assumed that it was decimal instead). That would be the ten ints you were looking for.
70,240,164
70,240,441
Detected memory leaks in c++
The following declaration in the file generated by grpc (grpc.pb.cc) causes a memory leak. It seems that google::protobuf::ShutdownProtobufLibrary() does not free the memory allocated by this declaration. Would you tell me how to release it? PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_DxpGrpc_2eproto(&descriptor_table_DxpGrpc_2eproto); Windows, C ++, gRPC-1.40.0 Create a console application in the Windows c++ environment and execute the following code. #include <crtdbg.h>. #include "google/protobuf/service.h"; int main(int argc, char** argv) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); google::protobuf::ShutdownProtobufLibrary(); return 0; } The following leaks will be out. Detected memory leaks! Dumping objects -> {159} {Normal block at 0x00E49B18, 8 bytes long. Data: < k > 10 6B C9 00 00 00 00 00 Object dump complete. When declare AddDescriptorsRunner in grpc.pb.cc, it calls DefaultConstruct() of the following class. (File: third_party\protobuf\src\google\protobuf\message_lite.h) template <typename T>. class ExplicitlyConstructed { public: void DefaultConstruct() { new (&union_) T(); } template <typename... Args> void Construct(Args&&... args) { new (&union_) T(std::forward<Args>(args)...) ; } void Destruct() { get_mutable()->~T(); } constexpr const T& get() const { return reinterpret_cast<const T&>(union_); } T* get_mutable() { return reinterpret_cast<T*>(&union_); } private: // Prefer c++14 aligned_storage, but for compatibility this will do. union AlignedUnion { alignas(T) char space[sizeof(T)]; int64 align_to_int64; void* align_to_ptr; } union_; };
The static or global object is freed the very last thing, after atexit, and the debugger reports false leak. This behavior can be reproduced with this example: #include <Windows.h> std::string str; int main() { _CrtDumpMemoryLeaks();//str is not freed yet return 0; } You can create a structure and place the leak report in the destructor, as shown below. Note in this example, std::string str; is used to cause a leak report. If cleanup is not defined, or if cleanup is defined after std::string str; then false leak is reported. The order of definition matters. #include <iostream> #include <string> #include <Windows.h> struct cleanup_t { ~cleanup_t() { if(IsDebuggerPresent()) _CrtDumpMemoryLeaks(); } } cleanup; std::string str; int main() { return 0; }
70,240,221
70,240,270
What is the right way to assign 0xFFFFFFFF to an unsigned integer variable?
If I compile following code size_t a = -1; with MSVC with W4 option I get warning C4245: 'initializing': conversion from 'int' to 'size_t', signed/unsigned mismatch and I am not 100% sure that -1 is 0xFFFFFFFF on all the platforms. Is -1 bit representation defined by the standard? Other options are: size_t a = std::numeric_limits<size_t>::max(); size_t a = static_cast<size_t>(-1); Are there some other alternatives? It can be uint8_t, uint16_t, etc... And in the code above I do not know what is the actual size of size_t, it can be 4 bit or 8 bit, for example.
size_t a = -1; This will initialize a with the biggest value size_t can hold. This is defined in terms of modulo arithmetics and not bit patterns. So this is true regardless if signed integers use 2s complement or something else. Unsigned integers are required to be encoded directly as their binary representation so the largest value will always have the 0xFF...FF bit pattern. To silence the cast both of your solution work. It's just a matter of personal taste which one you use.
70,240,467
70,240,482
Warning in C++: Pointer holds a value that must be examined when trying to assign new int32_t
I was trying to learn dynamic memory allocation in C++. My program compiles and works, but Visual Studio throws these warnings at me. What do they mean? Warning C28193 'ptr' holds a value that must be examined. Warning C28182 Dereferencing NULL pointer. 'ptr' contains the same NULL value as 'new(1*4, nothrow)' My code: #include <iostream> #include <cstdint> int main() { int* ptr = nullptr; if (!ptr) { ptr = new (std::nothrow) int32_t; *ptr = 10; } std::cout << *ptr << "\n"; }
new (std::nothrow) int32_t Attempts to allocate the memory for int32_t, and if it cannot, it doesn't throw an exception, it returns nullptr. You go ahead and assign a number (10) to it, but you need to first determine if the memory allocation succeeded by checking if ptr is nullptr or not before assigning the value. It's trying to tell you that you need some error checking. Same thing when you print it out, it may be a nullptr and you need to examine that.
70,240,586
70,243,331
I keep getting an "error: constexpr variable 'x' must be initialized by a constant expression" from previously used working code
I've been scratching my head for days now. Gone step by step removing and adding lines and recompiling at each stage until it breaks. ACTION act1(name nm, uint64_t amount); ACTION act2(name nm, uint64_t signing_value); ACTION receiverand(name nm, checksum256& random_value); ACTION act4(name nm, uint64_t stake); ACTION act5(uint64_t num); ACTION act6(name nm); using act1_action = action_wrapper<"act1"_n, &project::act1>; using act2_action = action_wrapper<"act2"_n, &project::act2>; using receiverand_action = action_wrapper<"receiverand"_n, &project::receiverand>; using act4_action = action_wrapper<"act4"_n, &project::act4>; using act5_action = action_wrapper<"act5"_n, &project::act5>; using act6_action = action_wrapper<"act6"_n, &project::act6>; The problem arises when I add act6. I had up to act4 and everything was working. So I added 5 and 6 then the error was thrown so I went back added 5 and things were still okay. Here is the error I keep getting error: constexpr variable 'x' must be initialized by a constant expression constexpr auto x = eosio::name{std::string_view{eosio::detail::to_const_char_arr<Str...>::value, sizeof...(Str)}}; note: in instantiation of function template specialization 'operator""_n<char, 'a', 'c', 't', '6'>' requested here using act6_action = action_wrapper<"act6"_n, &project::act6>; note: non-constexpr function 'check' cannot be used in a constant expression eosio::check( false, "character is not in allowed character set for names" );
Appears that a name cannot contain the character '6', but only '1' thru '5'. Action names [...] May contain: a-z, 1-5, or . https://eosio.stackexchange.com/questions/7/what-are-naming-rules-for-actions-tables-and-contracts
70,240,823
70,240,884
I can't store the address of Derived class in the pointer of base class when inheritance is private, but when I inherit it in public it shows no error
I am stuck with this code, when I store the address of the the Derived class in Pointer of base class, it shows error, but when made inheritance public there is no error, can anyone help..? #include <iostream> using namespace std; class Base // Created a Class Base { public: void show() { cout << "base"; } }; class Derived: private Base { public: int d; void display() { cout << "derived"; } }; int main() { Base b, *bptr; Derived d, *dptr; bptr = &b; dptr = &d; bptr->show(); bptr = &d; bptr->show(); return 0; }
In your case the class Base is not accessible and $11.2/5 states - If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10, 4.11). [ Note: it follows that members and friends of a class X can implicitly convert an X* to a pointer to a private or protected immediate base class of X. —end note ] Since Base is not an accessible class of Derived when accessed in main, the Standard conversion from Derived class to Base class is ill-formed. Hence the error.
70,241,162
70,241,300
How does the C++ compiler find operator overloading?
I have been looking into examples of operator overloading and some will include code snippets such as ostream& operator<<(ostream& os, const Date& dt) { os << dt.mo << '/' << dt.da << '/' << dt.yr; return os; } The ostream& operator<<(ostream& os, ...) seems to placed, for what atleast seems "randomly" around a C++ program. My question is, can it be placed anywhere? How does the C++ find, compile and now interpret overloading << for the class Date to now return a ostream& and use this function.
You can simply define as an inline as you did std::ostream& operator << ( ostream& os, const Date& dt ) { os << dt.mo << '/' << dt.da << '/' << dt.yr; return os; } But you have to include this header before you use it, otherwise the C++ compiler will not know. Or you can define as a friend inline inside the class, which will allow you to tap into private and protected fields, for example if the "mo", "da" and "yr" fields were private inside Date. class Date { ... friend inline std::ostream& operator << ( ostream& os, const Date& dt ) { os << dt.mo << '/' << dt.da << '/' << dt.yr; return os; } }; or you can define in the header (Date.h) class Date { ... friend std::ostream& operator << ( ostream& os, const Date& dt ); }; and then implement in the body (Date.cpp) file std::ostream& operator << ( ostream& os, const Date& dt ) { os << dt.mo << '/' << dt.da << '/' << dt.yr; return os; }
70,242,045
70,242,528
Detecting the first digit in the second digits?
Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet. Input: 1 4325121 Output: 2 Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer. Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result. No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.
As you said, you need to keep it as simple as possible. Then this can be a solution: #include <iostream> int main() { int first { }; int second { }; std::cin >> first >> second; int quo { second }; int rem { }; int count { }; while ( quo > 0 ) { rem = quo % 10; quo /= 10; if ( first == rem ) { ++count; } } std::cout << "Result: " << count << '\n'; }
70,242,089
70,249,725
Using std::less for a set of pointers
I've a some class where I'm declaring a set like this: std::set<UPFIR::RetentionSignal*> _retSignalSet; I'm trying to use std::less compare function on it. I tried something like this: std::set<UPFIR::RetentionSignal*, std::less<UPFIR::RetentionSignal*>> _retSignalSet; The feedback I'm getting is "adding std::less wont make it determinism. You have to compare the name", Can somebody explain me how can this be accomplished as I haven't worked with std::less before? Thanks
If the requirement is that the set should be sorted by name, then std::less does not help. You must provide a custom comparator that compares the name. For example (just an untested sketch): struct LessByName { bool operator<(UPFIR::RetentionSignal* a, UPFIR::RetentionSignal* b) { return a->name < b->name; } }; and then use it like std::set<UPFIR::RetentionSignal*, LessByName> _retSignalSet; BTW, the comment "std::less won't make it deterministic" is wrong, because std::less is defined to provide a total order on pointers. The order you get may just not be the one required to fulfill your task.
70,242,118
70,249,702
g++ - not reflecting changes made in source file
I'm building a project with a structure like this: - Makefile - main.cpp - util.h - subsrc/ - one.cpp - two.cpp And I have my Makefile set up to output to a build directory: all: $(BIN_FILE) $(BIN_FILE): $(OBJ_FILES) mkdir -p $(BIN_DIR) g++ $^ -o $@ $(OBJ_DIR)/%.o: %.cpp mkdir -p $(OBJ_DIR) g++ -c $^ -o $@ $(OBJ_DIR)/subsrc/%.o: subsrc/%.cpp mkdir -p $(OBJ_DIR)/subsrc g++ -c $^ -o $@ clean: rm -rf $(BUILD_DIR)/* However, I'm seeing this issue when I run g++ manually as well, so I don't think it's related to the Makefile. I can build from clean and everything works fine. The issue is when I change one of the subsrc files and try to recompile, via make or by running these commands myself: g++ -c subsrc/one.cpp -o build/obj/subsrc/one.o g++ build/obj/main.o build/obj/subsrc/one.o build/obj/subsrc/two.o -o build/bin/prog If I do this, changes made in one.cpp are not reflected in the binary output. If I recompile main.cpp (or, of course, the entire project), it works fine. This is not an issue of g++ not properly overwriting files, since even if I rm build/obj/subsrc/one.o and/or rm build/bin/prog before running the above commands, I still don't see the changes. That makes no sense to me and I have no idea what's happening. EDIT: I have uploaded a minimum reproducible example here. https://github.com/scatter-dev/so_70242118_min_repro Reproduction instructions: Build using make or by running the g++ commands above. Run the program to ensure it has built correctly. Change the output of the doWork function in one.cpp. Save to disk. Rerun make and note that the one.o file is recompiled and prog is recreated with the linker. Run the program again and see that the output has not changed. At the suggestion of a commenter, I checked the md5sum of one.o and prog between steps 1 and 4 and they are indeed both the same. This remains the case even if I delete one.o before recompiling. Yes, I am sure that one.cpp is being saved to disk (its md5sum does change, along with the fact that make clean && make will compile using the new changes).
Your problem is that your code is weirdly written and as a result, your makefile is incomplete. In your main.cpp you have: #include "subsrc/derived.h" which is fine but in that header you have: #include "one.cpp" #include "two.cpp" which is extremely bizarre. You pretty much never want to include .cpp files in other source files (or in header files). It's just a bad idea. In this situation, ALL the content of your program is included into main.cpp and thus appears in your main.o file. Linking in the other objects (one.o and two.o) is useless and unnecessary: they are ignored. In your makefile, however, you don't list one.cpp or two.cpp as prerequisites of main.o, which means that when you modify these source files main.o is not updated, and so nothing changes. If you remove main.o, then it is recompiled and you get the new behavior. ETA You have two options: You can either put the declaration of the classes into derived.h and put the definition of the doWork() method into the .cpp files. That would look like this: $ cat main.cpp #include "subsrc/derived.h" ... $ cat subsrc/derived.h #include "../base.h" class Derived1 : public Base { public: void doWork(); }; class Derived2 : public Base { public: void doWork(); }; $ cat subsrc/one.cpp #include <iostream> #include "derived.h" void Derived1::doWork() { std::cout << "I'm Derived1" << std::endl; } $ cat subsrc/two.cpp #include <iostream> #include "derived.h" void Derived2::doWork() { std::cout << "I'm Derived2" << std::endl; } $ cat Makefile ... $(OBJ_DIR)/main.o : base.h subsrc/derived.h $(OBJ_DIR)/subsrc/one.o: base.h subsrc/derived.h $(OBJ_DIR)/subsrc/two.o: base.h subsrc/derived.h Or you can inline everything in a header file the way you're doing (but you really don't want to name these files with .cpp extensions, if they contain class declarations). Or you can just have one derived.h and throw away one.cpp and two.cpp altogether. But you need to add the prerequisites in the makefile: if you keep multiple headers then main.o must depend on them.
70,243,298
70,247,227
What is the point of two types of module files (interface and implementation) in C++20?
When I want to export something I write export void foo(); I can implement it in the same module file or do it in a separate one. But what is the point of formally distinguishing these files (export module mymodule vs module mymodule) when, anyway, I can have any number of the latter type. Wouldn't be enough to just put export keyword before the thing I want to make public and not need to bother with special interface files?
At some point, the build system sees that some file says import MyModule;. When it sees that, the build system needs to go find the module for MyModule. If MyModule has not yet been built, the build system needs to build it. To do that, it has to (among other things) scan all of the known source files in your project to see which ones are used to build MyModule. But the most important thing is that it needs to figure out which file it specifically needs to build in order for import MyModule to work right now. That process works best and fastest if the system only needs to look for a single file to build (this way, the system can pre-process everything with a quick scanner to find all of those files). So the module system provides that: for any particular module, there is the primary module interface which defines everything that is exported by a module. Building that module may provoke the compilation of other modules, but we know which file has to be finished building before import MyModule can work. Now sticking everything a module can export into just one file is not the best idea. So in many cases, you'll have multiple files that export stuff, and you'll export import them in your main MyModule primary interface file. But since module names are global, we don't want dozens of tiny module names cluttering up the namespace. Enter module partitions: These are module interface files whose names are namespaced within a specific module. Module interface files can include other partitions, but only those within the same module. And obviously, the graph of partition inclusion must be acyclic. But that leaves us with a small problem. Let's say you have a partition that defines a class that gets exported to the primary module interface. But you don't want to put the implementation of those member functions in that partition file. So... where does it go? I mean, you could put it in another partition that doesn't get imported by anybody. But if that partition doesn't get imported... why bother giving it a partition name? It'd be best if you can communicate immediately that this "partition" cannot be included. Enter module implementation units. They are part of a specific module, and therefore they can import partitions of that module. But they cannot themselves be imported by anyone. That's what they're for. But note that the build system knows that it doesn't need to build module implementation units in order to completely build the module. It only needs to build the primary module interface file and any partitions included by it (directly or indirectly). This allows module rebuilding to be as fast as possible if you put your implementations into implementation units. Lastly, module implementation units (and interface units) have access to any names that they import from a partition which the partition does not export. These module-local names are only accessible within the module.
70,244,490
70,245,497
Optimization of image resizing (method Nearest) with using SIMD
I know that 'Nearest' method of image resizing is the fastest method. Nevertheless I search way to speed up it. Evident step is a precalculate indices: void CalcIndex(int sizeS, int sizeD, int colors, int* idx) { float scale = (float)sizeS / sizeD; for (size_t i = 0; i < sizeD; ++i) { int index = (int)::floor((i + 0.5f) * scale) idx[i] = Min(Max(index, 0), sizeS - 1) * colors; } } template<int colors> inline void CopyPixel(const uint8_t* src, uint8_t* dst) { for (int i = 0; i < colors; ++i) dst[i] = src[i]; } template<int colors> void Resize(const uint8_t* src, int srcW, int srcH, uint8_t* dst, int dstW, int dstH) { int idxY[dstH], idxX[dstW];//pre-calculated indices (see CalcIndex). for (int dy = 0; dy < dstH; dy++) { const uint8_t * srcY = src + idxY[dy] * srcW * colors; for (int dx = 0, offset = 0; dx < dstW; dx++, offset += colors) CopyPixel<N>(srcY + idxX[dx], dst + offset); dst += dstW * colors; } } Are the next optimization steps exist? For example with using SIMD or some other optimization technic. P.S. Especially I am interesting in optimization of RGB (Colors = 3). And if I use current code I see that ARGB image (Colors = 4) is processing faster for 50% then RGB despite that it bigger for 30%.
I think that using of _mm256_i32gather_epi32 (AVX2) can give some performance gain for resizing in case of 32 bit pixels: inline void Gather32bit(const uint8_t * src, const int* idx, uint8_t* dst) { __m256i _idx = _mm256_loadu_si256((__m256i*)idx); __m256i val = _mm256_i32gather_epi32((int*)src, _idx, 1); _mm256_storeu_si256((__m256i*)dst, val); } template<> void Resize<4>(const uint8_t* src, int srcW, int srcH, uint8_t* dst, int dstW, int dstH) { int idxY[dstH], idxX[dstW];//pre-calculated indices. size_t dstW8 = dstW & (8 - 1); for (int dy = 0; dy < dstH; dy++) { const uint8_t * srcY = src + idxY[dy] * srcW * 4; int dx = 0, offset = 0; for (; dx < dstW8; dx += 8, offset += 8*4) Gather32bit(srcY, idxX + dx,dst + offset); for (; dx < dstW; dx++, offset += 4) CopyPixel<N>(srcY + idxX[dx], dst + offset); dst += dstW * 4; } } P.S. After some modification this method can be applied to RGB24: const __m256i K8_SHUFFLE = _mm256_setr_epi8( 0x0, 0x1, 0x2, 0x4, 0x5, 0x6, 0x8, 0x9, 0xA, 0xC, 0xD, 0xE, -1, -1, -1, -1, 0x0, 0x1, 0x2, 0x4, 0x5, 0x6, 0x8, 0x9, 0xA, 0xC, 0xD, 0xE, -1, -1, -1, -1); const __m256i K32_PERMUTE = _mm256_setr_epi32(0x0, 0x1, 0x2, 0x4, 0x5, 0x6, -1, -1); inline void Gather24bit(const uint8_t * src, const int* idx, uint8_t* dst) { __m256i _idx = _mm256_loadu_si256((__m256i*)idx); __m256i bgrx = _mm256_i32gather_epi32((int*)src, _idx, 1); __m256i bgr = _mm256_permutevar8x32_epi32( _mm256_shuffle_epi8(bgrx, K8_SHUFFLE), K32_PERMUTE); _mm256_storeu_si256((__m256i*)dst, bgr); } template<> void Resize<3>(const uint8_t* src, int srcW, int srcH, uint8_t* dst, int dstW, int dstH) { int idxY[dstH], idxX[dstW];//pre-calculated indices. size_t dstW8 = dstW & (8 - 1); for (int dy = 0; dy < dstH; dy++) { const uint8_t * srcY = src + idxY[dy] * srcW * 3; int dx = 0, offset = 0; for (; dx < dstW8; dx += 8, offset += 8*3) Gather24bit(srcY, idxX + dx,dst + offset); for (; dx < dstW; dx++, offset += 3) CopyPixel<3>(srcY + idxX[dx], dst + offset); dst += dstW * 3; } } Note that if srcW < dstW then method of @Aki-Suihkonen is faster.
70,244,805
70,245,700
When does reference casting slice objects?
Take a look at this piece of code: #include <iostream> class A{ public: int x; virtual void f(){std::cout << "A f\n";} }; class B: public A { public: int y; void f() {std::cout << "B f\n";} }; void fun( A & arg) { std::cout << "fun A called" << std::endl; arg.f(); // arg.y = 222; - this gives error, compiler's work? arg.x = 2223333; } void fun(B & arg){ std::cout << "fun B called" << std::endl; arg.f(); } int main() { B b; b.y = 12; b.x = 32; fun(static_cast<A&>(b)); std::cout << b.x << " " << b.y << std::endl; return 0; } What exactly happens when I reference cast b into A&? I'm guessing a reference to type A 'arg' is created in a funtion 'fun()' and now it's only compiler's work to differentiate types? Meaning no actual object was created and no slicing occurred and it's still the same object in memory, however compiler will treat it as type A? (meaning after function call I can safely use b as type B?) I assumed that's true, because the vptr of the instance didn't change (arg of type A called B's virtual function override), but I'm not completely sure what's going on behind the scenes during reference casting. Also, if I assign static_cast<A&>(b) to a new object of type A, I assume that's when the construction of a new object of type A and slicing occurres?
Yes, you seem to have got this. :-) A B is also an A (by inheritance), so it can bind to either A& or B&. Nothing else happens, it is just a reference to the existing object. The slicing happens if you assign a B object to an A object, like A a = b;, which will only copy the inherited A portion of b.
70,244,992
70,245,047
Why is using a reserved identifier name in constexpr context not diagnosed?
Based on the following two rules: Using an identifier starting with "_" + capital letter, or containing double underscore, is undefined behavior. Undefined behavior is not allowed in constexpr expressions -> compiler should not compile. Then why aren't compilers complaining about this? constexpr int _UB() {return 1;} int main() { constexpr int a = _UB(); return a; } Demo Also, I see a lot of professional, MISRA-compliant code that seems to violate this naming rule, see e.g. here: #ifndef __STM32F732xx_H #define __STM32F732xx_H Are all these libs invoking UB too?
Undefined behavior is not allowed in constexpr expressions -> compiler should not compile It's a bit more narrow than this; as per [expr.const]/5, /5.7 in particular: An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following: [...] /5.7 an operation that would have undefined behavior as specified in [intro] through [cpp]; Now, [intro] through [cpp] includes: 1 Scope[intro.scope] 2 Normative references[intro.refs] 3 Terms and definitions[intro.defs] 4 General principles[intro] 5 Lexical conventions[lex] 6 Basics[basic] 7 Expressions[expr] 8 Statements[stmt.stmt] 9 Declarations[dcl.dcl] 10 Modules[module] 11 Classes[class] 12 Overloading[over] 13 Templates[temp] 14 Exception handling[except] 15 Preprocessing directives[cpp] The rule about underscore for global names, however, comes from [library], particularly [reserved.names]/2 and [global.names]/1 in [library], which is not covered by "[intro] through [cpp]". [reserved.names]/2 If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined. [global.names]/1 Certain sets of names and function signatures are always reserved to the implementation: (1.1) Each name that contains a double underscore __ or begins with an underscore followed by an uppercase letter ([lex.key]) is reserved to the implementation for any use. (1.2) Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace. Now, [lex.name]/3 also includes the same rule for reservation of identifiers In addition, some identifiers are reserved for use by C++ implementations and shall not be used otherwise; no diagnostic is required. (3.1) Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use. (3.2) Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace. A violation of [lex.name]/3 is ill-formed no diagnostic required (IFNDR), which is not the same as undefined behaviour; as per [expr.const]/5.7 above some UB should actually be diagnosed (constexpr contexts). The limitations of [expr.const]/5.7 to UB as per [intro] through [cpp] is arguably intentionally limiting the rule to avoid constructs that is UB for the typical C++ implementor but not the STL library implementors, e.g. rules in [library]. This could also be a wording defect, particularly as the rules of [lex.name]/3 goes from IFNDR to UB only "after the fact" of [reserved.names]/2 in [library]. Thus, this "kind" of undefined behaviour (UB) does arguably not fall under the UB that disqualifies an expression from being a core constant expression.
70,245,044
70,245,791
What cause undefined behavior when converting from unsign int to sign int and print it out
I have the following codes: #include "stdio.h" #include "stdint.h" #include <string> #include "string.h" #include<iostream> using namespace std; class myMessage { public: uint8_t latitude[4]; //Binary uint8_t longitude[4]; //Binary }; int8_t sentMessage[4]={0,}; int main() { myMessage msg; memset(&msg, 0x00, sizeof(msg)); uint8_t Input_Latitude[4] = {0x4,0x82,0x85,0xf1} ; printf("%x ", Input_Latitude[0] ); printf("%x ", Input_Latitude[1] ); printf("%x ", Input_Latitude[2] ); printf("%x \n", Input_Latitude[3] ); memcpy(&msg.latitude[0], &Input_Latitude, sizeof(uint8_t) * 4); printf("%x ", msg.latitude[0] ); printf("%x ", msg.latitude[1] ); printf("%x ", msg.latitude[2] ); printf("%x \n", msg.latitude[3] ); memcpy(&sentMessage[0], &msg.latitude[0], 4); printf("%02X ", sentMessage[0] ); printf("%02X ", sentMessage[1] ); printf("%02X ", sentMessage[2] ); printf("%02X \n", sentMessage[3] ); } When I print it out, I have: 4 82 85 f1 ==> original value 4 82 85 f1 ==> copy from unsign int to unsign int 04 FFFFFF82 FFFFFF85 FFFFFFF1 ==> after implicit converting from unsign int to int and printf Why do we have a bunch of FFFFFFF ???? I understand that there is some implicit conversion from uint8 to int8 when I run memcpy(&sentMessage[0], &msg.latitude[0], 4); // sentMessage is int8_t // msg.latitude[0] is uint8_t However, I what I don't understand is some extra FFFFF that clearly exceeds the size of each element in array sentMessage[]
The program prints out FFFFFF82 with some extra Fs because of printf. Printf takes %x and assume that I will pass into it value unsigned int which has 8 bytes. 0x82 with int8_t is unsign 8 bits, or 1 byte. Since printf assumes it is unsigned int, 8 bytes, it prints extra FFFFFF82. To fix it, we can use format specifier %#04hhx. The answer to this question is same as Why does printf not print out just one byte when printing hex? printf("%#04hhx ", sentMessage[0] );
70,245,354
70,247,443
deducing return type template c++
I'm making a parser combinator in c++. Currently, I'm trying to make a sequence function that will call other parsers in order and return all the results in a Tuple. Code template<typename T> T parse(std::function<T(Stream*)> parser, Stream* stream) { return parser(stream); } std::function<char(Stream*)> Char(char c) { return [=](Stream* stream) -> char { auto ch = stream->Next(); if (ch == c) { stream->Consume(1); return c; } return 0; }; } template <typename ...T, typename R> std::function<R(Stream*)> Seq(T... a) { return [=](Stream* stream) -> R { std::tuple tuple = { a(stream)... }; return tuple; }; } The problem is that the function Seq needs to know the return type which is a Tuple. This tuple is made of all the results of the functions inside the parameter pack. So I don't know how to tell the compiler what the return type is. This is the main code. auto& charA = Char('a'); auto& seq = Seq(Char('#'), charA); Stream stream("text.txt"); parse(seq, &stream); Here is the error trace. TestLayer.cpp(338,27): error C3547: el parámetro de plantilla 'R' no se puede usar porque sigue a un paquete de parámetros de plantilla y no se puede deducir de los parámetros de funciones de 'Seq' TestLayer.cpp(337): message : vea la declaración de 'R' TestLayer.cpp(356,14): error C2672: 'Seq': no se encontró una función sobrecargada que coincida TestLayer.cpp(356,14): error C2783: 'std::function<R(Stream *)> Seq(T...)': no se pudo deducir el argumento de plantilla para 'R' TestLayer.cpp(338): message : vea la declaración de 'Seq' TestLayer.cpp(356,12): error C2530: 'seq': se deben inicializar las referencias TestLayer.cpp(360,11): error C3536: 'seq': no se puede usar antes de inicializarse TestLayer.cpp(360,2): error C2672: 'parse': no se encontró una función sobrecargada que coincida TestLayer.cpp(360,20): error C2784: 'T parse(std::function<T(Stream *)>,Stream *)': no se pudo deducir el argumento de plantilla para 'std::function<T(Stream *)>' desde 'int' TestLayer.cpp(293): message : vea la declaración de 'parse' Edit: So, thanks to the comments I came up with this solution: template <typename ...T> auto Seq(T... a) -> std::function<decltype(std::tuple{ a(std::declval<Stream*>())... })(Stream*)> { return [=](Stream* stream) -> decltype(std::tuple{ a(std::declval<Stream*>())... }) { std::tuple tuple = { a(stream)... }; return tuple; }; } I don't know if it's the optimal solution.
In C++11 you can figure out what std::functions R parameter is supposed to be in different places. I've chosen to make it a template parameter with a default type: template< typename... T, class R = decltype(std::make_tuple(std::declval<T>()(std::declval<Stream*>())...)) > auto Seq(T... a) -> std::function<R(Stream*)> { return [=](Stream* stream) { return std::make_tuple(a(stream)...); }; } Here's an alternative version without that extra template parameter: template<typename... T> auto Seq(T... a) -> std::function< decltype( std::make_tuple(std::declval<T>()(std::declval<Stream*>())...) )(Stream*) > { return [=](Stream* stream) { return std::make_tuple(a(stream)...); }; } In C++17 it is simpler: template<typename... T> auto Seq(T... a) { return std::function([=](Stream* stream) { return std::make_tuple(a(stream)...); }); }
70,245,579
70,245,828
Problems with binary long handling
I made a binary decimal conversion menu which always take 0 for binary numbers #include<iostream> #include<cmath> using namespace std; int main() { int dec,ch,i; long bin,temp; do { dec=bin=i=ch=0; cout<<"\n\n\t\tMENU\n1. Deciml to Binary number\n2. Binary to Decimal number\n3. Exit\n"; cout<<"Enter your choice(1/2/3)> "; cin>>ch; switch(ch) { case 1: cout<<"Enter a decimal number: ";cin>>dec; temp=dec; while(dec) { bin+=(dec%2)*pow(10,i); dec/=2; i++; } cout<<temp<<" in decimal = "<<bin<<" in binary"<<endl;break; case 2: cout<<"Enter a binary number: ";cin>>bin; temp=bin; while(bin) { dec+=(bin%10)*pow(2,i); bin/=10; i++; } cout<<temp<<" in binary = "<<dec<<" in decimal"<<endl;break; case 3: break; default: cout<<"Invalid choice"; } }while(ch!=3); } When I select choice 1 and enter 23, it gives 0 and when I enter 11001 in choice 2 it gives 0 and tells that I entered 0. Output: MENU 1. Deciml to Binary number 2. Binary to Decimal number 3. Exit Enter your choice(1/2/3)> 1 Enter a decimal number: 23 23 in decimal = 0 in binary MENU 1. Deciml to Binary number 2. Binary to Decimal number 3. Exit Enter your choice(1/2/3)> 2 Enter a binary number: 11001 0 in binary = 0 in decimal MENU 1. Deciml to Binary number 2. Binary to Decimal number 3. Exit Enter your choice(1/2/3)> 3 -------------------------------- Process exited after 7.103 seconds with return value 0 Press any key to continue . . .
Main problem is that many newbies have wrong mindset when trying to solve this problem. They assume the have to recalculate directly from decimal to binary. They amuse that int type some some kind of magic aware of desired base. In this insane approach they are trying to calculate a value, which printed in decimal representation could be read as desired binary value. This is wrong and bug prone!!! Real conversion which should happen should be done in two steps: reading text representing a value in decimal format, then convert it to internal machine representation of that value (it not relay important that CPU uses binary, important thing is that you have a some value in CPU). This is covered by library: std::cin >> intVariable;. then this value should be converted to text representing value in binary format. Standard library do not have such functionality (not really true, but I will not confuse you how). So task is calculate each digit and then print it or store it in text representation. So to fix your code by trying write this function: void printAsBinary(std::ostream& out, int x) { for ( .... ) { .... out << ( someCondition ? '1' : '0'); } }
70,246,137
70,246,204
c++ login system fails when it s not the first element of stl vector
I m trying to create a login system but I encounter an issue at login. If it's the first person from the vector the login is successful otherwise the login is failed. Here is the code: #include<iostream> #include<fstream> #include<string> #include<vector> using std::string; using std::cin; using std::cout; using std::endl; std::ofstream out("login_data.txt",std::ios::app); std::ifstream in("login_data.txt"); class Person { private: string nume; string parola; public: void setNume(string nume) { this->nume = nume; } void setParola(string parola) { this->parola = parola; } Person(string nume, string parola) { this->nume = nume; this->parola = parola; } Person() { nume = ""; parola = ""; } string getNume() { return nume; } string getParola() { return parola; } bool equalTo(Person p) { if (this->nume == p.nume && this->parola == p.parola) { return true; } else return false; } }; std::vector<Person> persoane; void printPers() { for (int i = 0; i < persoane.size()-1; i++) { cout << persoane.at(i).getNume() << " " << persoane.at(i).getParola(); } } void registerPerson() { string n; string p; cout << "Enter name:"; cin >> n; cout << "Enter password:"; cin >> p; out <<endl<< n << " " << p<<","; } void savePerson() { string line; char delim =','; while (std::getline(in, line, delim)) { Person pers; string delimiter = " "; size_t pos = 0; string token; while ((pos = line.find(delimiter)) != std::string::npos) { token = line.substr(0, pos); pers.setNume(token); line.erase(0, pos + delimiter.length()); } pers.setParola(line); persoane.push_back(pers); } } bool checkLogin() { savePerson(); string username; string userPassword; Person user; cout << "Specify the name:"; cin >> username; cout << "Specify password:"; cin >> userPassword; user.setNume(username); user.setParola(userPassword); for (int i = 0; i < persoane.size() - 1; i++) { if (user.equalTo(persoane.at(i))) { return true; } else { return false; } } } int main() { int choice; cout << "Enter option\n1.Register\n2.Login\nYour choice:"; cin >> choice; if (choice == 1) { registerPerson(); } else if (choice == 2) { if (!checkLogin()) { cout << "Login failed"; } else { cout << "Login succesful"; } } else { cout << "Error please select a valid option."; exit(0); } return 0; } And the text file contains: a b, c d, e f, g h, i j, I also checked and the vector saves the Person objects properly,but for some reason in the checkLogin() method the problem occurs.
Instead of else { return false; } You want to continue the loop. Your function fails because of a premature return.
70,246,174
70,246,484
How can we set the memory of array using cstring packgae functions in c++
i want to allocate a number to whole array using memset function of cstring class.bbut it only works for 0,if i provide any other value to the function memset it randomly assigns a large integer no to the memory of array. memset(arr,0,sizeof(arr)); for this it works fine each slot in array i assigned 0 value; but if i do this memset(arr,1 or any other no,sizeof(arr)); for this it alots a random larger integer value to each slot of array; pls explain why is it happening like this.
I think you want std::fill. std::memset is a primitive function. It sets bytes in memory, not values. The value 257 in binary is 0x0101. That shows you what happened: both bytes were set to 0x01. Since you want to set the value to 0x0001, it clearly is not possible to do so with std::memset, since it sets everything to the same byte value. std::fill on the other hand understands types, and will convert the value you give it. So it can convert 1 to 1.0f when filling an array of floats.
70,246,289
70,246,554
typedefing a pointer recognized by C to an inner C++ class
I have a class that I want to share between C and C++, where C is only able to get it as a pointer. However because it is an inner class it cannot be forward-declared. Instead this is what our current code does in a common header file: #ifdef __cplusplus class Container { public: class Object { public: int x; }; }; typedef Container::Object * PObject; #else typedef void* PObject; #endif This looks like it violates the one definition rule (ODR), because C and C++ see different definition using the #ifdef. But because this is a pointer, I'm not sure if this creates a real problem or not. C only uses the pointer in order to pass it to C++ functions, it doesn't directly do anything with it. For instance this code in the common header file: #ifdef __cplusplus extern "C" { #endif int object_GetX(PObject pObject); #ifdef __cplusplus } #endif /* __cplusplus */ This as how we implemented it in the C++ file: int object_GetX(PObject pObject) { return pObject->x; } My questions are: Would violating the ODR like this cause any real problems? If so, is there another convenient way to share the class to C?
First of all, type-aliasing pointers is usually a recipe for trouble. Don't do it. Second, the "inner" class is an overused concept, so my first reflex would be to consider whether it's really necessary. If it is necessary, you can define an opaque empty type and derive from it for some type safety: In a shared header: struct OpaqueObject; #ifdef __cplusplus extern "C" { #endif int object_GetX(OpaqueObject* pObject); #ifdef __cplusplus } #endif /* __cplusplus */ In a C++ header: struct OpaqueObject {}; class Container { public: class Object : public OpaqueObject { public: int x; }; }; Implementation: int object_GetX(OpaqueObject* pObject) { return static_cast<Container::Object*>(pObject)->x; }
70,246,716
70,249,086
Getting C26xxx errors in my C++ Windows service code
I'm getting errors in my code. The code compiles, but I'd still like to get rid of the warnings. I've looked on stackoverflow and google and clicked on the warnings which take me to the microsoft.com page, explaining each, but I don't see concrete examples of how to get rid of them. Here's the C++ code and the warnings. void WINAPI ServiceMain(DWORD dwArgc, LPWSTR* lpszArgv); VOID main() noexcept { CONST SERVICE_TABLE_ENTRY ste[] = { {L"MyService", ServiceMain}, {NULL, NULL} }; //C26485 Expression 'ste': No array to pointer decay (bounds.3). StartServiceCtrlDispatcherW(ste); } // C26429 Symbol 'lpszArgv' is never tested for nullness, it can be marked as not_null (f.23). // C26461 The pointer argument 'lpszArgv' for function 'ServiceMain' can be marked as a pointer to const (con.3). VOID WINAPI ServiceMain(DWORD dwArgc, LPWSTR* lpszArgv) { // C26481 Don't use pointer arithmetic. Use span instead (bounds.1). ssh = RegisterServiceCtrlHandlerExW(lpszArgv[0], (LPHANDLER_FUNCTION_EX) Service_Ctrl, 0); ... } Any help is appreciated.
Those are not compiler warnings but a code analysis warnings (based on CppCoreGuidelines), which give hints on how to improve code to prevent common errors - like null pointer dereferences and out of bound reads/writes. Fixing them might require use of gsl library of tools : https://github.com/microsoft/GSL. //C26485 Expression 'ste': No array to pointer decay (bounds.3). StartServiceCtrlDispatcherW(ste); this informs you about potentially dangerous call, this function does not take information about size of the array so it might potentially lead to reading outside buffer. Analyzer does not know that this function relies on last element to be null initialized. You could silence this warning by allocating memory for ste on heap and releasing after the StartServiceCtrlDispatcherW call, or even better by wrapping allocated memory inside std::unique_ptr or even storing entries in std::vector https://learn.microsoft.com/en-us/cpp/code-quality/c26485?view=msvc-170 // C26429 Symbol 'lpszArgv' is never tested for nullness, it can be marked as not_null (f.23). // C26461 The pointer argument 'lpszArgv' for function 'ServiceMain' can be marked as a pointer to const (con.3). VOID WINAPI ServiceMain(DWORD dwArgc, LPWSTR* lpszArgv) You should be able to fix this warning with gsl: const auto args = gsl::span<LPWSTR>(lpszArgv, dwArgc); then use args as if it was lpszArgv. For instructions on how to use gsl see here: https://github.com/Microsoft/GSL According to documentation, ServiceMain should always be called with at least one element in lpszArgv: ...The first parameter contains the number of arguments being passed to the service in the second parameter. There will always be at least one argument. The second parameter is a pointer to an array of string pointers. The first item in the array is always the service name. https://learn.microsoft.com/en-us/windows/win32/services/writing-a-servicemain-function So it should be fine to suppress this warning with: #pragma warning(suppress: 26429 26461) VOID WINAPI ServiceMain(DWORD dwArgc, LPWSTR* lpszArgv) or better: [[gsl::suppress(f.23)]] [[gsl::suppress(con.3)]] VOID WINAPI ServiceMain(DWORD dwArgc, LPWSTR* lpszArgv) links to both warnings: https://learn.microsoft.com/en-us/cpp/code-quality/c26429?view=msvc-170 https://learn.microsoft.com/en-us/cpp/code-quality/c26461?view=msvc-170 // C26481 Don't use pointer arithmetic. Use span instead (bounds.1). ssh = RegisterServiceCtrlHandlerExW(lpszArgv[0], (LPHANDLER_FUNCTION_EX) Service_Ctrl, 0); .. this will be fixed if you use gsl::span as shown above
70,246,891
70,247,240
How to initialize tm struct memebers in initializer list of a structure in C++ 98 standard
I'm trying to initialize ::tm struct's members in a structure using initializer list as shown below. But it's only possible in C++ stds > 98. How can I achieve the same in C++ 98? struct abc { abc () : time_struct_{0,0,0,0,0,0,0,0,0}, x(0) { } ::tm time_struct_ ; int x; };
As Daniel Langr mentioned time_struct_() does the job.
70,246,995
70,247,043
Are temporary variables released at the end of a statement?
I'm trying to find out when temporary variables are released. I wrote the code below. #include <stdio.h> class C { public: C() { printf("C O\n"); } C(const C&) { printf("C& O\n"); } virtual ~C() { printf("C D\n"); } }; int kkk(const C&) { printf("kkk\n"); return 0; } int kkk2(int) { printf("kkk2\n"); return 0; } int main() { (kkk2( kkk2( (kkk(C()),3) ) ), printf("dsfsdfs\n"), true) && (printf("dsdddf\n"),true); printf("=====\n"); return 0; } I expect Class C to be released after kkk is called, but actually, the result is: C O kkk kkk2 kkk2 dsfsdfs dsdddf C D ===== I run the code with g++ clang++ and msvc++, the result is same. Class C is release at the end of a statement. Is it a C++ standard to release temporary variables at the end of a statement?
From Temporary_object_lifetime All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception. There are two exceptions from that: [..] So to answer your question: Is it a C++ standard to release temporary variables at the end of a sentence? Yes, temporaries are destroyed at end of full-expression (not sentence).
70,247,123
70,249,302
Is there an simd/avx instruction to return a u8 mask for every 32 bit lane that isn't 0
Say i have a 256 bit wide vector like this: 00000000 00000000 11100110 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000101 00000000 00000000 00000000 01111110 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00001100 00000000 00000000 00000000 00000000 00000000 What would be the most efficient way to get a 8 bit mask that looks a little something like this: 10110010 where every set bit represents a 32 bit integer lane that is > 0 using AVX2 and everything that both amd and intel support
Assuming signed integer lanes: inline uint8_t positiveMask_epi32( __m256i vec ) { // Compare 32-bit integers for i > 0 const __m256i zero = _mm256_cmpgt_epi32( vec, _mm256_setzero_si256() ); // Collect high bits const int mask = _mm256_movemask_ps( _mm256_castsi256_ps( zero ) ); // Return that value return (uint8_t)mask; } If they’re unsigned integers: inline uint8_t nonZeroMask_epu32( __m256i vec ) { // Compare 32-bit integers for i == 0 const __m256i eqZero = _mm256_cmpeq_epi32( vec, _mm256_setzero_si256() ); // Collect high bits const int mask = _mm256_movemask_ps( _mm256_castsi256_ps( eqZero ) ); // Flip lowest 8 bits in the result, we want 1 for non-zeros return (uint8_t)( mask ^ 0xFF ); }
70,247,395
70,247,479
Ambiguous overload for ‘operator=’ when trying to invoke the move assignment operator
I am trying to clarify-understand move semantics and, for that, I wrote the following code. I used a raw pointer as a data member only to practice in finding all the dangerous spots and also apply idioms like copy & swap. #include <iostream> #include <utility> class Example { protected: int* intPtr; public: Example() : intPtr{nullptr} { allocate(); std::cout << "Example() called" << "\n"; } Example(int value) : intPtr{nullptr} { allocate(); assign(value); std::cout << "Example(int) called" << "\n"; } ~Example() { deallocate(); std::cout << "~Example called" << "\n"; } Example(const Example& anExample) : intPtr{anExample.intPtr ? new int(*anExample.intPtr) : nullptr} { std::cout << "Example(const Example&) called" << "\n"; } Example(Example&& anExample) noexcept { intPtr = anExample.intPtr; anExample.intPtr = nullptr; std::cout << "Example(Example&&) called" << "\n"; } Example& operator=(Example&& anExample) noexcept { if(this != &anExample){ intPtr = anExample.intPtr; anExample.intPtr = nullptr; std::cout << "Move assignment op called" << "\n"; } return *this; } Example& operator=(Example anExample) { std::swap(intPtr, anExample.intPtr); std::cout << "Copy assignment op called \n"; return *this; } void assign(int value) { if (intPtr != nullptr && *intPtr!=value) *intPtr = value; else { std::cout << __FUNCTION__ << ": intPtr is either null, or its memory contains already the value you want.\n"; } } private: void allocate() {intPtr = new int{};} void deallocate() {delete intPtr;} friend std::ostream& operator<<(std::ostream& strm, const Example& anExample) { return strm << *anExample.intPtr; } }; int main() { Example ex1; std::cout << "----------------" <<std::endl; Example ex2{ex1}; std::cout << "----------------" <<std::endl; Example ex3 = ex2; // invokes copy constructor std::cout << "----------------" <<std::endl; Example ex4; std::cout << "----------------" <<std::endl; ex4 = ex3; // invokes copy assignement operator std::cout << "----------------" <<std::endl; Example ex5 = std::move(ex1); // invokes move constructor std::cout << "----------------" <<std::endl; ex4 = std::move(ex5); // compilation error! return 0; } The last line gives the following error main.cxx:116:22: error: ambiguous overload for ‘operator=’ (operand types are ‘Example’ and ‘std::remove_reference<Example&>::type’ {aka ‘Example’}) 116 | ex4 = std::move(ex5); | ^ main.cxx:36:12: note: candidate: ‘Example& Example::operator=(Example&&)’ 36 | Example& operator=(Example&& anExample) noexcept { | ^~~~~~~~ main.cxx:45:12: note: candidate: ‘Example& Example::operator=(Example)’ 45 | Example& operator=(Example anExample) { | ^~~~~~~~ Why is the right hand side's type std::remove_reference<Example&>::type. What am I doing wrong here and how to invoke the move-assignement operator properly? Every other comment is welcome.
Example& operator=(Example anExample) is a general assignment operator. It copies lvalues and moves rvalues. If you want to distinguish copy from move assignment you need Example& operator=(const Example & anExample). Alternatively you could remove Example& operator=(Example&& anExample).
70,247,498
70,249,307
Reduce big O notation for faster runtime, now it doesnt execute because it is too long, anyone know a solution?
The code below is to calculate the exponential growth of fish. How can I reduce this to O(N) for a capable runtime? Now my code is O(N2) and it wont execute because it will take too long. Any suggestions? #include <fstream> #include <vector> #include <sstream> #include <numeric> void CalculateNewFish(std::vector <int64_t>& NewValues, int Days) { if (Days == 256) { std::cout << "Day " << Days << ": " << NewValues.size()<< std::endl; } else if(Days >= 0) { for (int l = 0; l < NewValues.size(); ++l) { NewValues.at(l)--; if(NewValues.at(l) < 0) { NewValues.at(l) = 6; NewValues.push_back(9); } } CalculateNewFish(NewValues, Days + 1); } } int main() { std::ifstream myfile; int a; std::vector <int64_t> Values; myfile.open("inputday6.txt"); while (myfile >> a) { Values.push_back(a); } myfile.close(); CalculateNewFish(Values, 0); return 0; }
Given that the number of fish grows exponentially, it is a bad idea to do a simulation that grows in space with the number of fish. We can avoid this by recognizing all fish with the same number of days remaining are identical and that there are only nine possible values, [0, ... , 8], of days remaining for a given fish. We can thus represent the state of the simulation as an array of nine counts of fish: #include <iostream> #include <vector> #include <sstream> #include <fstream> #include <algorithm> #include <numeric> #include <array> std::string file_to_string(const std::string& filename) { std::ifstream file(filename); std::stringstream buffer; buffer << file.rdbuf(); return buffer.str(); } std::vector<std::string> split(const std::string& s, char delim) { std::stringstream ss(s); std::string item; std::vector<std::string> elems; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<int> parse_to_ints(const std::string& input) { auto num_strs = split(input, ','); std::vector<int> nums; std::transform(num_strs.begin(), num_strs.end(), std::back_inserter(nums), [](const std::string& str)->int { return std::stoi(str); } ); return nums; } class school_o_fish { private: std::array<uint64_t, 9> counts_; public: school_o_fish(const std::vector<int>& initial_pop) { counts_ = { 0,0,0,0,0,0,0,0,0 }; for (int days : initial_pop) { counts_[days]++; } } void simulate_one_day() { auto reborn = counts_[0]; for (int i = 1; i < 9; i++) { counts_[i - 1] = counts_[i]; } counts_[8] = reborn; counts_[6] += reborn; } uint64_t total() { return std::accumulate(counts_.begin(), counts_.end(), 0ull); } uint64_t simulate_n_days(int n) { for (int i = 0; i < n; ++i) { simulate_one_day(); } for (int i = 0; i < 9; ++i) { std::cout << i << " : " << counts_[i] << "\n"; } std::cout << "\n"; return total(); } }; int main() { std::cout << "day 6\n\n"; school_o_fish s( parse_to_ints( file_to_string("c:\\test\\day6.txt") ) ); std::cout << s.simulate_n_days(256) << "\n"; } Inverting the simulation like this seems related in spirit to "the flyweight design pattern".
70,247,818
70,248,965
What is lldb's equivalent one of gdb's advance command?
When debugging C/C++ function that with many arguments, and each arguments may still call some functions, people have to repeated typing step and finish, then reach where this function's body part. e.g. I'm using OpenCV's solvePnP() function, it requires many arguments: solvePnP(v_point_3d,v_point_2d,K,D,R,T); Among which, each argument will be converted from cv::Mat to cv::InputArray, thus calling a init() function. What I expected is, directly go to where solvePnP() implemented, and I'm not interested in each argument type conversion. Luckily, there is advance command in gdb. Official document is here, writes: advance location Continue running the program up to the given location. An argument is required, which should be of one of the forms described in Specify Location. Execution will also stop upon exit from the current stack frame. This command is similar to until, but advance will not skip over recursive function calls, and the target location doesn’t have to be in the same frame as the current one. This gdb advance command really helps. And what's the equivalent command in LLDB? I've search in lldb official's gdb => lldb command mapping web page, https://lldb.llvm.org/use/map.html , but not found. Edit: I forgot to mention, the gdb usage for me is (gdb) b main (gdb) r (gdb) advance solvePnP
Checkout the sif command for lldb. sif means **Step Into Function Reference: How to step-into outermost function call in the line with LLDB? To get all the supported commands of LLDB, one should first go into lldb command, then type help, then there will be the explanations for sif: sif -- Step through the current block, stopping if you step directly into a function whose name matches the TargetFunctionName.
70,247,908
70,247,988
Standard Ways Of Passing Array of Arrays To Other Functions in C++ Failing
I am attempting to pass a 2D array of integers from my main function in a cpp program to another function, and to manipulate the 2D array in this other function. While I've done this before, it's been a while, so I was following this accepted answer: Direct link to answer in question the below program is modeled directly after However, while everything looks ok to me, 2/3 of the methods suggested in the answer are failing. I've stripped out anything unrelated to the error in what I've pasted below to hopefully make it easy to see what I mean. #include <iostream> #include <fstream> #include <string> using namespace std; int LINES_IN_FILE = 500; int NUMS_PER_LINE = 4; void change2dArrayMethod1(int (*lines)[LINES_IN_FILE][NUMS_PER_LINE]) { (* lines)[0][0] = 1; (* lines)[0][1] = 2; (* lines)[0][2] = 3; (* lines)[0][3] = 4; } void change2dArrayMethod2(int lines[][NUMS_PER_LINE]) { lines[0][0] = 1; lines[0][1] = 2; lines[0][2] = 3; lines[0][3] = 4; } void change2dArrayMethod3(int lines[]) { lines[0] = 1; //not sure how to access entire array here } int main() { int coordLines[LINES_IN_FILE][NUMS_PER_LINE]; // METHOD 1 // Fails with error: // Cannot initialize a variable of type 'int (*)[LINES_IN_FILE][NUMS_PER_LINE]' // with an rvalue of type 'int (*)[LINES_IN_FILE][NUMS_PER_LINE]'clang(init_conversion_failed) int (*p1_coordLines)[LINES_IN_FILE][NUMS_PER_LINE] = &coordLines; // Fails with error: // No matching function for call to 'change2dArrayMethod1'clang(ovl_no_viable_function_in_call) // test.cpp(10, 6): Candidate function not viable: no known conversion from 'int (*)[LINES_IN_FILE][NUMS_PER_LINE]' to // 'int (*)[LINES_IN_FILE][NUMS_PER_LINE]' for 1st argument change2dArrayMethod1(p1_coordLines); // METHOD 2 // Fails with error: // Cannot initialize a variable of type 'int (*)[NUMS_PER_LINE]' with an lvalue of type 'int [LINES_IN_FILE][NUMS_PER_LINE]'clang(init_conversion_failed) int (*p2_coordLines)[NUMS_PER_LINE] = coordLines; // Fails with error: // No matching function for call to 'change2dArrayMethod2'clang(ovl_no_viable_function_in_call) // test.cpp(17, 6): Candidate function not viable: no known conversion from 'int (*)[NUMS_PER_LINE]' to 'int (*)[NUMS_PER_LINE]' for 1st argument change2dArrayMethod2(p2_coordLines); // METHOD 3 // Doesn't fail - however not sure how to manipulate array in function called int *p3_coordLines = coordLines[0]; change2dArrayMethod3(p3_coordLines); } Additionally, when using the 3rd method suggested, I'm not sure how assignment works, or even how to access values in the array. I've pasted the errors the clang compiler gives in comments above each call to the second function. There are no errors in the functions other than main, which are the ones taken directly from the answer from the above link. However, I've also passed the 2D array in the same way the above link suggested for each method, so I'm really at a loss as to what is wrong here.
An array when used in an expression decays to a pointer to its first element. So a variable of type int [LINES_IN_FILE][NUMS_PER_LINE] decays to type int (*)[NUMS_PER_LINE], and the latter in a function declaration can also be expressed as int [][NUMS_PER_LINE] So you want to use this function: void change2dArrayMethod2(int lines[][NUMS_PER_LINE]) { And pass the array directly: change2dArrayMethod2(coordLines); Also, C++ doesn't allow non-const values for array indices. You'll need to make the values const: const int LINES_IN_FILE = 500; const int NUMS_PER_LINE = 4;
70,248,058
70,248,416
why does using cin function give me error?
so i'm pretty new at coding and was solving a problem that i found in the book. Here's the code- #include <iostream> #include <string> using namespace std; void hours(double hours, string subs) { if (hours > 12 || subs != "AM" || "PM") { int tries = 0; while (tries <= 50) ; { cout << "please check your input.\n"; tries++; } } int i; if (subs == "AM") { int i = 0; } else { int i = 1; } switch (i) { { case 0: int newhours1 = hours * 60; break; } { case 1: int newhours2 = hours + 12; int newhours3 = newhours2 * 60; break; } } } int main() { cout << "Welcome to the time convertor.\n"; cout << "What's your initial time?.\n"; cin >> hours >> subs; void hours(hours, subs); cout << "What's your second number?.\n"; cin >> hours2 >> subs2; void hours(hours2, subs2); if (newhours3 = > newhours1) { cout << "Your answer is" << "" << newhours3 - newhours1 << "\n"; } else if (newhours1 = > newhours3) { cout << "Your answer is" << "" << newhours1 - newhours3 << "\n"; } return 0; } whenever im trying to run it,it's showing the error- C:\Users\adhis\Documents\codes\Untitled1.cpp|30|error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'void(double, std::__cxx11::string)' {aka 'void(double, std::__cxx11::basic_string<char>)'})| can you tell me where i'm going wrong? thank you
There were many errors (see the comments above). I've fixed it for you, compare to your original code #include <iostream> #include <string> using namespace std; double calculate_hours(double hours, string subs) { if( hours <= 0 || hours > 12 || ( subs != "AM" && subs != "PM")){ cout << "please check your input.\n"; return -1; } if(subs == "AM"){ return hours * 60; }else{ return (hours + 12) * 60; } } int main(){ double h1,h2, t1,t2; std::string s1,s2; cout << "Welcome to the time convertor.\n"; cout << "What's your initial time?.\n"; do{ cin >> h1 >> s1; t1 = calculate_hours(h1,s1); } while (t1 < 0); cout << "What's your second number?.\n"; do { cin >> h2>>s2; t2 = calculate_hours(h2,s2); } while (t2 < 0); if(t2 >= t1){ cout << "Your answer is " << "" << t2 - t1 << "\n"; }else { cout << "Your answer is "<< "" << t1 - t2 << "\n"; } return 0; }
70,248,223
70,248,306
How can I make my function only accept odd numbers into my array, and reject even numbers? C++
Let me preface this by saying I am fairly new to functions and arrays. I have to make 3 functions: Function1 will be user input, Function2 will determine even/odd numbers, and Function3 will display the contents. I have Function1 and Function3 complete, and will post below, but I'm having a difficult time with Function2. What I have now will give the user an error message if they enter an even number, but it's messed up, and I just can't seem to figure out. #include <iostream> #include <iomanip> #include <string> using namespace std; void getUsrInput(int num[], int size) //function for user input (function 1 of 3) { int n; for (int i = 0; i < size; i++) { cout << "Enter five odd numbers: "; cin >> n; num[i] = n; if (num[i] % 2 != 0) //if the number is odd then store it, if it is even: //function for even or odd (function 2 of 3 *doesn't work) { i++; } else { cout << "Invalid input. Please only enter odd numbers!" << endl; //let the user know to enter only odd numbers. } } } int main() { const int size = 5; //array size is 5 numbers int num[size]; getUsrInput(num, size); cout << "D I S P L A Y - PART C/B" << endl; cout << "========================" << endl; for (int i = 0; i < size; i++) { cout << num[i] << endl; //function for display (function 3 of 3) } }
for (int i = 0; i < size; i++) increments i each time through the loop. if (num[i] % 2 != 0) { i++; } increments i each time the number is odd. So each time the user inputs an odd number, i gets incremented twice. Change the loop control to for (int i = 0; i < size; } so that i only gets incremented on valid input.
70,248,510
70,249,317
How do I load a bitmap into a Win32 application?
I am trying to load a bitmap in a Win32 application, but for some strange reason the bitmap does not load. Here is what I have so far: HANDLE hImg = LoadImageW( NULL, L"img.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); if (hImg == NULL) { std::cout << GetLastError(); } Compiled on GCC 8.1.0 with -Wall -municode. Nothing is output to the console, so there are no errors. However, the image never shows up. These questions seem to address a similar issue, but I have had a look at them and couldn't find a solution: I cannot load image from folder using win32 Win32 application. HBITMAP LoadImage fails to load anything Where could the problem be? Full code: #ifndef UNICODE #define UNICODE #endif #include <windows.h> #include <iostream> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { const wchar_t CLASS_NAME[] = L"Window Class"; WNDCLASS wc = {}; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = CLASS_NAME; RegisterClass(&wc); HWND hwnd = CreateWindowEx( 0, CLASS_NAME, L"My Application", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL ); if (hwnd == NULL) { return 0; } ShowWindow(hwnd, nCmdShow); HANDLE hImg = LoadImageW( NULL, L"img.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); if (hImg == NULL) { std::cout << GetLastError(); } MSG msg = {}; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1)); EndPaint(hwnd, &ps); break; } } return DefWindowProc(hwnd, uMsg, wParam, lParam); }
You just need to change the window procedure to do all the drawing in WM_PAINT. Once the image is loaded successfully, create a memory DC, select the bitmap into the memory DC, and draw the memory DC onto the target window DC. When the bitmap handle from LoadImage is no longer needed, it should be deleted DeleteObject (or DestroyCursor/DestroyIcon depending on what resource was loaded) HANDLE hImg = NULL; LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: if (!hImg) hImg = LoadImage(NULL, L"img.bmp", IMAGE_BITMAP,0,0,LR_LOADFROMFILE); if (!hImg) { DWORD err = GetLastError(); std::cout << err; } return 0; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1)); if (hImg) { BITMAP bm; GetObject(hImg, sizeof(bm), &bm);//get bitmap dimension auto memdc = CreateCompatibleDC(hdc); auto oldbmp = SelectObject(memdc, (HBITMAP)hImg); BitBlt(hdc, 0, 0, bm.bmWidth, bm.bmHeight, memdc, 0, 0, SRCCOPY); SelectObject(memdc, oldbmp);//restore memdc DeleteDC(memdc);//delete memdc, we don't need it anymore } EndPaint(hwnd, &ps); return 0; } case WM_DESTROY: if (hImg) DeleteObject(hImg);//release resource hImg = NULL; PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } When using GetLastError, make sure the function is called immediately after failure. Example: if (hImg == NULL) { DWORD err = GetLastError(); std::cout << err << '\n'; } If UNICODE is already defined, we can use LoadImage instead of LoadImageW
70,248,658
70,249,141
Perspective projection turns cube into weird tv shaped cuboid
This is my perspective projection matrix code inline m4 Projection(float WidthOverHeight, float FOV) { float Near = 1.0f; float Far = 100.0f; float f = 1.0f/(float)tan(DegToRad(FOV / 2.0f)); float fn = 1.0f / (Near - Far); float a = f / WidthOverHeight; float b = f; float c = Far * fn; float d = Near * Far * fn; m4 Result = { {{a, 0, 0, 0}, {0, b, 0, 0}, {0, 0, c, -1}, {0, 0, d, 0}} }; return Result; } And here is the main code m4 Project = Projection(ar, 90); m4 Move = {}; CreateMat4(&Move, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -2, 0, 0, 0, 1); m4 Rotate = Rotation(Scale); Scale += 0.01f; m4 FinalTransformation = Project * Move * Rotate; SetShaderUniformMat4("Project", FinalTransformation, ShaderProgram); Here are some pictures of the cube rotating. In the shader code I just multiply the transformation by the position (with the transformation being on the left). I am not sure if it's helpful but here is the rotation code: float c = cos(Angle); float s = sin(Angle); m4 R = { {{ c, 0, s, 0}, { 0, 1, 0, 0}, {-s, 0, c, 0}, { 0, 0, 0, 1}} }; return R; I tried multiplying the matricies in the shader code instead of on the c++ side but then everything disappeared.
OpenGL matrixes are stored with column major order. You have to read the columns from left to right. For example the 1st column of the matrix R is { c, 0, s, 0}, the 2nd one is { 0, 1, 0, 0} the 3rd is {-s, 0, c, 0} and the 4th is { 0, 0, 0, 1}. The lines in your code are actually columns (not rows). Therefore you need to to transpose you projection matrix (Project) and translation matrix (Move).
70,248,902
70,248,928
Fraction pattern in c++
I need to write a program to run this pattern in c++: S=1/2+2/3+3/4+4/5+...+N-1/N I have tried but my code is showing 0. And its the code that I have written: #include <iostream> using namespace std; int main() { unsigned int N; float S=0; cout << "Enter N:"; cin >> N; for (int I = 2; I <= N; I++) { S = S + (I - 1) / I; } cout << S; return 0; } I have to write it with for-loop, while and do-while
(I - 1) / I only contains integers, therefore any remainder is discarded. You can avoid this by simply subtracting - 1.f off of I instead.
70,249,058
70,249,332
why for loop is not work correctly for a simple multiplication numbers 1 to 50?
code: #include <iostream> using namespace std; int main() { int answer = 1; int i = 1; for (; i <= 50; i++){ answer = answer * i; } cout << answer << endl; return 0; } resault : 0 ...Program finished with exit code 0 Press ENTER to exit console. when i run this code in an online c++ compiler, it shows me zero(0) in console. why?
I will answer specifically the asked question "Why?" and not the one added in the comments "How?". You get the result 0 because one of the intermediate values of answer is 0 and multiplying anything with it will stay 0. Here are the intermediate values (I found them by moving your output into the loop.): 1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 1932053504 1278945280 2004310016 2004189184 -288522240 -898433024 109641728 -2102132736 -1195114496 -522715136 862453760 -775946240 2076180480 -1853882368 1484783616 -1375731712 -1241513984 1409286144 738197504 -2147483648 -2147483648 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 E.g. here https://www.tutorialspoint.com/compile_cpp_online.php Now to explain why one of them is 0 to begin with: Because of the values, the sequence of faculties, quickly leaves the value range representable in the chosen data type (note that the number decimal digits does not increase at some point; though the binary digits are the relevant ones). After that, the values are not really related to the correct values anymore, see them even jumping below zero and back... ... and one of them happens to be 0. For the "How?" please see the comments (and maybe other, valuable answers).
70,249,073
70,249,163
How to seperate definition and implementation of a derived class constructor?
I would like to learn how to define a derived class constructor in one file so that I could implement it in another file. public: Derived(std::string name) : Base(name); ~Derived(); Destructor works as expected, however with constructor I either add {} at the end (instead of a semicolon) and then get redefinition of 'Derived' error or I get asked to add {} instead of a semicolon. What is a way to separate definition and implementation in this case?
Base.h #include <string> class Base { protected: std::string name; ... public: Base(std::string name); virtual ~Derived(); ... }; Base.cpp #include "Base.h" Base::Base(std::string name) : name(name) { ... } Base::~Base() { ... } Derived.h #include "Base.h" class Derived : public Base { ... public: Derived(std::string name); ~Derived(); ... }; Derived.cpp #include "Derived.h" Derived::Derived(std::string name) : Base(name) { ... } Derived::~Derived() { ... }
70,249,647
70,252,123
The strong-ness of x86 store instruction wrt. SC-DRF?
I read about Herb's atomic<> Weapons talk and had a question about page 42: He mentioned that (50:00 in the video): (x86) stores are much stronger than they need to be... What I don't understand is: if the x86 "S" on the chart is a plain store, i.e. mov, I don't think it's stronger than SC-DRF because it's only a release store plus total store order (and that's why you need an xchg for a SC store). But if it means an SC store, i.e. xchg, it should fall on the "fully SC" bar because it's effectively a full barrier. How should I take this x86 "S"'s strong-ness on the chart? (SC-DRF is a guarantee of Sequentially Consistent execution for Data Race Free programs, as long as they don't use any atomics with orders weaker than std::memory_order_seq_cst. ISO C++ and Java, and other languages, provide this.)
Yes, he's showing xchg there (full barrier and an RMW operation), not just a mov store - a plain mov would be below the SC-DRF bar because it doesn't provide sequential consistency on its own without mfence or other barrier. Compare ARM64 stlr / ldar - they can't reorder with each other (not even StoreLoad), but stlr can reorder with other later operations, except of course other release-store operations, or some fences. (Like I mentioned in answer to your previous question). See also Does STLR(B) provide sequential consistency on ARM64? re: interaction with ldar for SC vs. ldapr for just acquire / release or acq_rel. Also Possible orderings with memory_order_seq_cst and memory_order_release for another example of how AArch64 compiles (without ARMv8.3 LDAPR). But x86 seq_cst stores drain the store buffer on the spot, even if there is no later seq_cst load, store, or RMW in the same thread. This lack of reordering with later non-SC or non-atomic loads/stores is what makes it stronger (and more expensive) than necessary. Herb Sutter explained this earlier in the video, at around 36:00. He points out xchg is stronger than necessary, not just an SC-release that can one-way reorder with later non-SC operations. "So what we have here, is overkill. Much stronger than is necessary" at 36:30 (Side note: right around 36:00, he mis-spoke: he said "we're not going to use these first 3 guarantees" (that x86 doesn't reorder loads with loads or stores with stores, or stores with older loads). But those guarantees are why SC load can be just a plain mov. Same for acq/rel being just plain mov for both load and store. That's why as he says, lfence and sfence are irrelevant for std::atomic.) So anyway, ARM64 can hit the sweet spot with no extra barrier instructions, being exactly strong enough for seq_cst but no stronger. (ARMv8.3 with ldapr is slightly stronger than acq_rel requires, e.g. ARM64 still forbids IRIW reordering, but only a few machines can do that in practice, notably POWER) Other ISAs with both L and S below the bar need extra barriers as part of their seq_cst load and seq_cst store recipes (https://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html).
70,249,721
70,249,867
type of input arguments depending on template boolean
My purpose is simple, data type of the input is depending on the template bool: template<bool isfloa> class example{ public: if (isfloa){ example(float p){printf("sizeof p: %d\n", sizeof(p))}; } else{ example(uint64_t p){printf("sizeof p: %d\n", sizeof(p))}; } }; This cannot pass the compliation and I have the following solution (haven't test it): using dataType = isfloa ? float : uint64_t; example(dataType p){printf("sizeof p: %d\n", sizeof(p))}; I'd like to know if this works? And are there any other solutions? Thanks a lot.
You can use std::conditional template<bool isfloat> class example{ public: using value_type = std::conditional_t<isfloat,float,int>; example(value_type p){printf("sizeof p: %d\n", sizeof(p));} };
70,250,038
70,250,518
Can I somehow elegantly forbid using unsingned variables in my template function?
Consider this piece of code: template <typename T> T abs(const T& n) { if (!std::is_signed<T>::value) throw logic_error; if (n < 0) return -n; return n; } I want to completely forbid the usage of my function with unsigned variables, since it doesn't make sense, and probably the user doesn't even know that he uses an unsigned variable. For example, I can somewhat avoid this problem: template <typename T> T abs(const T& n) { if constexpr(!std::is_signed<T>::value) n += ""; if (n < 0) return -n; return n; } But if I call abs(4u), the compiler errors are not very obvious. Something like "can't apply += const char[1] to double". Can I make it somehow more obvious? Or just make multiple overloads?
1. concepts Since C++20 you can use concepts for this. If you are fine with integer only parameters you could use std::signed_integral: #include <concepts> template <std::signed_integral T> T abs(const T& n) { if (n < 0) return -n; return n; } If you want to also allow double, etc... you'd have to make your own concept: template<class T> concept signed_value = std::is_signed_v<T>; template <signed_value T> T abs(const T& n) { if (n < 0) return -n; return n; } This would result in a compiler error like this if you try to use an unsigned type: error: no matching function for call to 'abs(unsigned int&)' note: candidate: 'template<class T> requires signed_integral<T> T abs(const T&)' Which makes it very clear that abs() only accepts signed types from just the signature. 2. SFINAE If C++20 is not available, you could use SFINAE, although the error messages you would get are quite cryptic: template <class T> std::enable_if_t<std::is_signed_v<T>, T> abs(const T& n) { std::cout << "HELLO" << std::endl; if (n < 0) return -n; return n; } But this would result in an error message like this: error: no matching function for call to 'abs(unsigned int&)' note: candidate: 'template<class T> std::enable_if_t<is_signed_v<T>, T> abs(const T&)' note: template argument deduction/substitution failed: In substitution of 'template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type [with bool _Cond = false; _Tp = unsigned int]': required by substitution of 'template<class T> std::enable_if_t<is_signed_v<T>, T> abs2(const T&) [with T = unsigned int]' So, you need to be comfortable with SFINAE errors for this one. 3. good old static_assert Alternatively, you could also just add a static_assert to your function. This won't be visible in the declaration at all though, only in the definition of the function. template <class T> T abs(const T& n) { static_assert(std::is_signed_v<T>, "T must be signed!"); if (n < 0) return -n; return n; } 4. using std::abs() C++ already provides a std::abs() implementation that handles all the potential edge cases for you, so if you can, I would recommend using that one instead. Your code also contains a potential bug if you pass in the minimum value for a given int type, e.g. INT_MIN. The smallest value a 32bit int can represent is -2147483648 But the largest it can represent is only 2147483647 So, a call to your abs() function with the minimal value, e.g. abs(-2147483648) would result in undefined behaviour (std::abs() has the same behaviour, but it's still worth pointing out).
70,250,524
70,251,009
C++ class template taking either type or non-type
I see a few similar questions, but they don't seem to get at this. I can overload a function on a template: template <typename T> void foo(); // Called as e.g., foo<int>(); template <std::size_t I> void foo(); // Called as e.g., foo<2>(); Is there a way to do something similar with a class, where I can have either MyClass<int> or MyClass<2>? I can't see a way to do it. (My real goal is to have a static constexpr instance of an invokable that acts like std::get. Whereas std::get is templated on its "indexing" parameter and on the argument type, I'd like to make one that is invokable on its own, so myns::get<2> and myns::get<int> are both invokable and when invoked act like std::get<2>(tup) and std::get<int>(tup) respectively. Naively you'd hope something like this would work, but the auto is a type: template <auto IndOrType> constexpr auto get = [](auto&& tup) { return std::get<IndOrType>(std::forward<decltype(tup)>(tup)); }; I can make a getter function that returns a lambda, but then it's called with () as in myns::get<2>()(tup) or myns::get<int>()(tup).
You could specialize the class using the helper type std::integral_constant<int,N>. Though unfortunately this doesn't exactly allow the MyClass<2> syntax: #include <type_traits> template<typename T> class MyClass { }; template<int N> using ic = std::integral_constant<int,N>; template<int N> class MyClass<ic<N>> { }; int main() { MyClass<int> a; MyClass<ic<2>> b; } https://godbolt.org/z/84xoE1Yd4
70,250,551
70,262,613
failure to compile imgui, glfw, opengl on linux with gcc 11.2
I've recently started coding with c++ and the project that im currently on requires imgui. so i set up the .h and .cpp libraries in a folder called "include" in the same folder as the source code. I'm currently trying to run the cpp in https://github.com/ocornut/imgui/tree/master/examples/example_glfw_opengl3 and compile it with gcc using gcc imgui.cpp -lstdc++ -lglfw -lGL -limgui but i just get /usr/bin/ld: cannot find -limgui collect2: error: ld returned 1 exit status yes i know there is a make file in the link but im using the file in another folder.
Assuming you downloaded imgui to a place called $IMGUI_DIR and the file that contains your main function is main.cpp, your compile commandline should look like the following: (the \ are just there to break up the command) g++ main.cpp -o main \ $IMGUI_DIR/imgui*.cpp $IMGUI_DIR/backends/imgui_impl_glfw.cpp $IMGUI_DIR/backends/imgui_impl_opengl3.cpp \ -I $IMGUI_DIR -I $IMGUI_DIR/backends \ -lglfw -lGL In order, you tell the compiler: Where your code is and where to put the output What Imgui code to include, namely the core library and the two backends you want to use Where Imgui code should look for its headers If all this sounds like a lot, know that you can simply build the example you linked and override IMGUI_DIR at compile time with make IMGUI_DIR=/path/to/imgui
70,251,054
70,251,112
c++ why do i get errors when using ternary operator
So here's my code, and I just can't find what's wrong. I would very much appreciate any help! #include <iostream> using namespace std; int main() { int x,I=2; for (x = 100 ; x <= 500; x++) { (x % 3 == 0 && x % 5 == 0)? (cout << x << endl) : (I = 2); } return 0; } errors: Update: I know I could use if ,else but it just made me curios, btw this program is supposed to find all numbers divisible by 3 and 5 from 100 to 500. Also if I run #include <iostream> using namespace std; int main() { int x,I=2; for (x = 100 ; x <= 500; x++) { ((x % 3 == 0) && (x % 5 == 0))? (cout << x << endl) : (cout<<"somthing"); } return 0; } It works fine so I guess the problem was in the second expression, is there a way to replace it with something that does nothing(that was the intent of I=2)
The ternary operator is not an if-else. It's for doing something like this: int i = (3 < 4) ? 3 : 4; Please use if-else for this usage.
70,251,105
70,261,539
Get each row of an arma::mat matrix as arma::vec in for loop
I am using RcppArmadillo to create a function using stochastic simulation. I have trouble pulling out each row of a arma::mat as an arma::vec. Below is a simplified example of my problem. I have used R nomenclature to illustrate what I am trying to achieve. I believe there should be a fairly simple way of achieving this in C++, but I'm afraid I haven't figured it out yet. Any help would be much appreciated. #include <RcppArmadillo.h> using namespace Rcpp; // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] List function(List params) { arma::mat c= params["c"]; arma::mat I= params["I"]; for (int istep = 0; istep < (I.n_elem); istep++) { arma::vec loopedrows = I[istep,] //Here I have used the R indexing method, but this does not work in C++ double product= accu(c*loopedrows) arma:vec newvec = stochastic_simulation(product) I[istep+1,] = newvec // store the output of the in matrix I, again the nomenclature is in R. } return wrap(I); };
Here is a simple (and very pedestrian, going step by step in the loop) answer for you. Code #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] arma::mat rowwiseAdd(arma::mat A, arma::mat B) { if (A.n_rows != B.n_rows || A.n_cols != B.n_cols) Rcpp::stop("Matrices must conform."); arma::mat C(A.n_rows, A.n_cols); for (size_t i=0; i < A.n_rows; i++) { arma::rowvec a = A.row(i); arma::rowvec b = B.row(i); arma::rowvec c = a + b; C.row(i) = c; } return C; } /*** R A <- matrix(1:9, 3, 3) B <- matrix(9:1, 3, 3) rowwiseAdd(A, B) */ Output > Rcpp::sourceCpp("~/git/stackoverflow/70251105/answer.cpp") > A <- matrix(1:9, 3, 3) > B <- matrix(9:1, 3, 3) > rowwiseAdd(A, B) [,1] [,2] [,3] [1,] 10 10 10 [2,] 10 10 10 [3,] 10 10 10 >
70,251,557
70,273,012
How to mock a vector of an arbitrary size?
I've defined a class that accepts a vector as a constructor input parameter and provides a method that uses vector's size() function: class Foo { vector<int> storedVector; public: explicit Foo(vector<int>); bool isSizeGreaterThanInt(); } Foo::Foo(vector<int> inputVector) : storedVector(std::move(inputVector)) { } bool Foo::isSizeGreaterThanInt() { if (storedVector.size() > INT32_MAX) { return true; } return false; } Now I would like to test the isSizeGreaterThanInt() method of this class. As part of that test I want to also validate that the size() call inside of the implementation returns the size() of the vector passed into the constructor and not some other vector/some other size. I'm using gtest and gmock as my testing and mocking framework respectively. All my attempts to create a mock of vector<int> which mocks the size() function to return a specific value seem to fail, my latest version of the mock is as follows: template <typename VectorValueType> class MockVector : public std::vector<VectorValueType> { public: MOCK_CONST_METHOD0_T(size, size_t()); }; TEST(Test,TestCase) { size_t fakeSize = static_cast<size_t>(INT32_MAX) + 1; MockVector<int> mockVector; EXPECT_CALL(mockVector, size()).WillRepeatedly(testing::Return(fakeSize)); size_t testSize = mockVector.size(); // here the value is correct Foo foo (mockVector); // if I debug here and check the size of the vector now stored in foo - it's 0. ASSERT_EQ(true, foo.isSizeGreaterThanInt()); } I had concerns about std::move and move behavior so I tried passing inputVector by reference, tried passing pointers, tried storing vector<int>& storedVector instead of having a value member... nothing worked. Is what I'm trying to do possible? What am I doing wrong? Update One of the commenters suggested it happens due to splicing of the MockVector type into vector<int>, and when it's spliced the mocked methods are no longer called... but still, how should I go about mocking the vector? There is no interface for vector<> in C++ STL, so I can't make that a parameter to the constructor... Update 2 As suggested in one of the answers, yes, I can add a getSize() to Foo and mock that... But it changes Foo's contract and I'd prefer not to do that. Furthermore, if I was willing to do that, I still would need to mock my vector to test the getSize() behavior to ensure that getSize() truly returns the size() of the vector and not some other value. Basically, doing that is just moving the same problem to a different place. Update 3 Yes, theoretically I can create a vector in my test, just pass it in and not mock it. The issue here is that to test the specific behavior described above I'll need to create a vector with (INT32_MAX + 1) elements in it, which is prohibitively expensive (resources/time/memory) for the test.
You cannot mock methods of std::vector, because mocking system in GoogleTest is based on polymorphism and std::vector is not prepared for use in polymorphism - none of its methods are virtual. Since size() method is not virtual, the mock implementation will never be called and GoogleMock cannot register that call or execute actions. The only way to test that would be to pass the vector of size INT32_MAX to the tested class (perhaps this test should be disabled by default and only enabled in CI envireonment) or to create a wrapper for std::vector which will have virtual methods in its interface.
70,251,722
70,251,855
Does not name a type C++
I am making a program that hopefully removes tags from html files. But when I am copiling the program I get the following error message : tag_remover.cc:11:1: error: ‘TagRemover’ does not name a type 11 | TagRemover::TagRemover(std::istream& in) { | ^~~~~~~~~~ tag_remover.cc:21:14: error: ‘TagRemover’ has not been declared 21 | std::string& TagRemover::remove(std::string& s) { | ^~~~~~~~~~ tag_remover.cc: In function ‘std::string& remove(std::string&)’: tag_remover.cc:32:1: warning: no return statement in function returning non-void [-Wreturn-type] 32 | } | ^ tag_remover.cc: At global scope: tag_remover.cc:34:13: error: ‘TagRemover’ has not been declared 34 | std::string TagRemover::print(std::ostream& out) const { | ^~~~~~~~~~ tag_remover.cc:34:50: error: non-member function ‘std::string print(std::ostream&)’ cannot have cv-qualifier 34 | std::string TagRemover::print(std::ostream& out) const { | ^~~~~ tag_remover.cc: In function ‘std::string print(std::ostream&)’: tag_remover.cc:35:9: error: ‘str’ was not declared in this scope; did you mean ‘std’? 35 | out << str << endl; | ^~~ | std make: *** [<builtin>: tag_remover.o] Error 1 And I can´t figure it out. Any help would be greatly appreciated. This is my main for testing the tag remover: #include <iostream> #include <fstream> #include <string> #include "tag_remover.h" using std::string; int main() { std::cout << "Opening html file" << std::endl; std::ifstream in1("tags.html"); std::cout << "Removing tags ....." << std::endl; TagRemover test1(in1); test1.print(std::cout); std::cout << "Test Done!" << std::endl; } This is tag_remover.cc script: #include <iostream> #include <istream> #include <ostream> #include <fstream> #include "tag_remover.h" using std::endl; using std::cout; using std::string; using std::istream; TagRemover::TagRemover(std::istream& in) { //remove white spaces std::noskipws(in); std::istream_iterator <char> itr1(in); std::istream_iterator <char> itr2{}; std::string s(itr1, itr2); str = remove(s); } std::string& TagRemover::remove(std::string& s) { while(s.find("<") != std::string::npos) { auto startpos = s.find("<"); auto endpos = s.find(">"); if(endpos == std::string::npos) { break; } auto eraseTo = (endpos - startpos) +1; s.erase(startpos, eraseTo); } return s; } std::string TagRemover::print(std::ostream& out) const { out << str << endl; return str; } This is the header file : #ifndef TAG_REMOVER #define TAG_REMOVER #include <string> #include <iostream> //#include <iterator> class TagRemover { public: TagRemover(); TagRemover(std::istream& in); std::string print(std::ostream& out) const; std::string& remove(std::string& s); private: std::string str; //const std::string inLine; }; #endif
First thing I notice: #include <iterator> Is nowhere to be found. It should be in tag_remover.cc std::istream_iterator<> Is defined in… <iterator> Also the TagRemover default constructor seems to be declared but not defined. Furthermore, you can define TagRemover::TagRemover(std::istream&) like this: TagRemover::TagRemover(std::istream& in) : str{ [] (auto& is) { std::skipws(is); // ignore spaces using iser = std::istream_iterator<char>; return std::string(iser(is), iser()); }(in) } {}
70,252,406
70,252,475
Why am I getting values that are outside of my rand function parameters?
I am trying to output 25 random values between 3 and 7 using a function. Every time I run my program, I receive two values that are within those parameters, but the rest are out of range. #include <iostream> #include <iomanip> using namespace std; void showArray(int a[], int size); void showArray(int a[], const int size) { int i; for (i = 0; i < size; i++) { cout << a[i] << ", "; } } int main() { //int iseed = time(NULL); //srand(iseed); srand(time(NULL)); int randomNumb = rand() % 3 + 4; int array[] = {randomNumb}; showArray(array, 25); } This is my Output: 4, 4, -300313232, 32766, 540229437, 32767, 0, 0, 1, 0, -300312808, 32766, 0, 0, -300312761, 32766, -300312743, 32766, -300312701, 32766, -300312679, 32766, -300312658, 32766, -300312287,
You are calling rand() only 1 time, and storing the result in randomNumb, which is a single integer. Your array is being created with only 1 element in it - the value of randomNumb. But, you are telling showArray() that the array has 25 elements, which it doesn't. So, showArray() is going out of bounds of the array and displaying random garbage from surrounding memory. Which is undefined behavior. If you want 25 random numbers, then you need to allocate an array that can hold 25 numbers, and then call rand() 25 times to fill that array, eg: #include <iostream> using namespace std; void showArray(int a[], const int size) { for (int i = 0; i < size; ++i) { cout << a[i] << ", "; } } int main() { srand(time(NULL)); int array[25]; for(int i = 0; i < 25; ++i) array[i] = rand() % 3 + 4; showArray(array, 25); }
70,252,660
70,254,426
C++: Initialize a variable of a specific type, logic. Consise way of approaching these problems
I have this problem generally, but my specific example is: When dealing with .wav data,for 16 bit waves, one uses a signed integer, whereas the 8 bit waves are unsigned. I would like to do something like the following: if (bytesPerSample == 2){ int16_t* buffer = new int16_t[1]; } else if (bytesPerSample == 1){ uint8_t* buffer = new uint8_t[1]; } else { cout << "bytesPerSample: " << bytesPerSample << " is unsupported" << endl; } Which I know is invalid, because the variable declared inside the scope of the if statement is destroyed when the block is exited. I also know I could initialize both and then I could create 2 if statements and copy the rest of my code twice, change variable names and then execute one block only if #bytes is 2 and the other if #bytes is 2. However, this method is not concise and can lead to me introducing issues as I change the second code block around. Is there any concise method of specify the use of a variable of identical name but different type, for multiple potential type cases?
C++17's std::variant type can hold multiple data types in the same space. You can then use std::visit to dispatch based on the type inside. If you combine this with templates, you only have to write one version of each function that processes the variable. template <typename T> void processSamples(const std::vector<T>& buffer) { /* do your processing here */ } std::variant< std::vector<uint8_t>, std::vector<uint16_t>> buffer; if (bytesPerSample == 2) { buffer = std::vector<uint16_t>(numSamples); } else if (bytesPerSample == 1) { buffer = std::vector<uint8_t>(numSamples); } std::visit([](const auto& buffer) { processSamples(buffer); }, buffer); std::visit isn't magic. It uses a data structure similar to a tagged union: there is a field that indicates which type is currently stored, and a union with the different datatypes. When you call std::visit, the template function generates, when optimized, something roughly equivalent to a switch which tests the type and calls a different function for each option: void processSamples(uint8_t*); void processSamples(uint16_t*); struct Buffer { int bytesPerSample; union { uint8_t* u8; uin16_t* u16; } } Buffer buffer; buffer.bytesPerSample = bytesPerSample; if (buffer.bytesPerSample == 2) { buffer.u16 = new uint16_t[16000]; } else if (buffer.bytesPerSample == 1) { buffer.u8 = new uint8_t[16000]; } if (buffer.bytesPerSample == 2) { processSamples(buffer.u16); } else if (buffer.bytesPerSample == 1) { processSamples(buffer.u8); } ...except when you use std::variant, everything is type-safe, accepts non-trivial types, and you don't have to check each switch block for exhaustiveness when you make a change. If you do not have C++17, there are C++11 compatible implementations: https://github.com/mpark/variant
70,253,485
70,253,545
Is the main purpose of object serialization in C++ for faster object loading?
I am reading code for a project written by others. The main task of the project is to read contents from a large structured text file (.txt) with 8 columns into a KnowledgeBase object, which have a number of methods and variables. The KnowledgeBase object is then output into a binary file. For example, the KnowledgeBase class has at least these two variables: map<string, pair<string, string>> key_info vector<ObjectInfo> objects ... These variables are easy to understand when I track the code with gdb. Then, it seems it is converting such vectors and maps into binary forms. And the two variables above have their corresponding binary forms: BinaryKeyInfo *bkeys BinaryObjectInfo *bObjects Later on when outputting to binary file, it has such code: fwrite((char*)(&wcount),sizeof(int32_t),1,output); fwrite((char*)bkeys,sizeof(KeyInfo_t),wcount,output); The converting code from the original KnowledgeBase to binary is complicated. My question is, what's the main purpose of this conversion? Is it for faster loading of binary file into memory than plain text file? The plain text file is large. I learnt that object serialization is primarily for transmitting objects over the net, but I don't think the purpose here is for that. It is more like for speeding up data loading and memory saving. Could that be part of object serialization in C++?
Is the main purpose of object serialization in C++ for faster object loading? No. The most important purpose of serialisation is to transform the state of the program into a format that can be stored on the filesystem, or that can be communicated across a network, and that can be de-serialised back. Often, the purpose of either is for another program to do the de-serialisation. Sometimes the de-serialiser is another instance of the same program. The speed of de-serialisation is one metric that can be used to gauge whether one particular serialisation format is a good one. The ability to quickly undo what you have done is not the reason why you do it in the first place. what's the benefit of converting them into binary vectors or maps? As I mention above, the benefit of serialisation is the ability to store the serialised data on the filesystem, or to send it over a network. what' the benefit between plain text files VS binary files? Pros of text serialisation format: Humans are able to read and write plain text. Humans generally are not able read nor write binary files. It's generally easier to implement a plain text format de-/serialiser in a way that works across differing computers than it is to implement a binary format de-/serialiser that achieves the same. Pros of binary serialisation format: Typically faster and uses less storage and bandwidth. Can be easier to implement if there is no need for communication between differing systems. This is typically only the case in very simple cases. (Furthermore, there usually is a need for cross-system compatibility, even if the need haven't been realised yet).
70,253,537
70,253,637
GLUT - Undefined reference to pressedButton(int, int)
I have a main method that contains the glutMotionFunc that receives the function movimentoMouseBotaoApertado that the signature is void movimentoMouseBotaoApertado(int, int). I have a .h and .cpp file, but when I import the .h at the main file and try to execute the code, the error appears undefined reference to movimentoMouseBotaoApertado(int, int) main.cpp ... #include "mouse/mouse.h" #include "desenha/desenha.h" ... int main(int argc, char *argv[]) { glutInit(&argc, argv); // Always needs glutInit glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); inicializa(); nomeDoPrograma(); glutDisplayFunc(desenha); glutKeyboardFunc(teclado); glutSpecialFunc(teclasEspeciais); criarMenu(); glutMouseFunc(gerenciaMouse); glutMotionFunc(movimentoMouseBotaoApertado); glutPassiveMotionFunc(movimentoMouse); glutReshapeFunc(alterarTamanhoJanela); glutMainLoop(); // Redesenhando } movimentoMouseBotaoApertado.h #ifndef MOVIMENTOMOUSEBOTAOAPERTADO_H_INCLUDED #define MOVIMENTOMOUSEBOTAOAPERTADO_H_INCLUDED void movimentoMouseBotaoApertado(int, int); #endif // MOVIMENTOMOUSEBOTAOAPERTADO_H_INCLUDED movimentoMouseBotaoApertado.cpp #include <stdio.h> void movimentoMouseBotaoApertado(int x, int y) { printf("Botão apertado [%d,%d]", x, y); }
I clicked with the right button and selected Add files recursively... and I chose the folders/files and worked it.
70,253,925
70,257,171
std::accumulate vs for loop, raytracing application
This question is based on this video on YouTube made with the purpose of reviewing this project. In the video, the host is analyzing the project and found out that the following block of code is a cause of performance issues: std::optional<HitRecord> HittableObjectList::Hit(const Ray &r, float t_min, float t_max) const { float closest_so_far = t_max; return std::accumulate(begin(objects), end(objects), std::optional<HitRecord>{}, [&](const auto &temp_value, const auto &object) { if(auto temp_hit = object -> Hit(r, t_min, closest_so_far); temp_hit) { closest_so_far = temp_hit.value().t; return temp_hit; } return temp_value; }); } I would assume that the std::accumulate function would function similarly to a for loop. Unhappy with the performance hit there (and because, for some reason, the profiler wouldn't profile the lambda code[a limitation, perhaps?]), the reviewer changed the code to this: std::optional<HitRecord> HittableObjectList::Hit(const Ray &r, float t_min, float t_max) const { float closest_so_far = t_max; std::optional<HitRecord> record{}; for(size_t i = 0; i < objects.size(); i++) { const std::shared_ptr<HittableObject> &object = objects[i]; if(auto temp_hit = object -> Hit(r, t_min, closest_so_far); temp_hit) { closest_so_far = temp_hit.value().t; record = temp_hit; } } return record; } With this change the time to completion went from 7 minutes and 30 seconds to 22 seconds. My questions are: Aren't both blocks of code identical? Why does std::accumulate give such enormous penalty here? Would the performance be better if instead of using autos, using the explicit type? The reviewer did mention suggestions such as avoiding the use of std::optionals and std:shared_ptrs here due to the amount of calls made and to execute this code on the GPU instead, but for now I'm only interested in those points mentioned earlier.
Desclaimer: I did not run advanced tests, this is just my analysis based on the video and the code. From what I see in the profiling in the video, the hotspot in accumulate is here: _Val = _Reduce_op(_Val, *_UFirst); Since _Reduce_op is just our lambda, and the profiling shows this lambda is not the bottleneck, then it means the only expensive operation here is the copy assignment operator =. Looking at HitRecord: struct HitRecord { point3 p; vec3 normal; std::shared_ptr<Material> mat_ptr; float t; bool front_face; ... We see there is a bunch of stuff including a shared_ptr. Chances are the optimizer would remove the copy when it is not needed if the shared_ptr was not here. Copying a shared_ptr is relatevely expensive in a hot loop because it involves atomic operations. Note that in the profiled accumulate code, we see that they tried to fix this in c++20 by introducing a move. #if _HAS_CXX20 _Val = _Reduce_op(_STD move(_Val), *_UFirst); #else // ^^^ _HAS_CXX20 ^^^ // vvv !_HAS_CXX20 vvv _Val = _Reduce_op(_Val, *_UFirst); #endif // _HAS_CXX20 Though for this move to work, the compiler would have to properly use the named return value optimization which it does not always do when there are multiple return in a function. You would also have to change the signature of the lambda so that it takes a value or an r-value instead of a reference. Changing from auto to a named type would not fix the issue.
70,253,960
70,254,028
How can I access the define macro in the header file from other files with Conditional Compilation?
I have a macro in a header file: header.h #ifndef HEADER_H #define HEADER_H #define vulkan #endif I want to use this macro with #ifdef from other headers and sources files. game.h #ifndef GAME_H #define GAME_H #include "header.h" #ifdef vulkan //use vulkan api #else //use opengl api #endif #endif I also want to use #ifdef in the game.cpp source file, but I can't reach the vulkan macro with #ifdef, neither from the header nor from the source. What is the right way to do this? EDIT: I am uploading pictures: header.h game.h game.cpp EDIT 2: minimal reproducible example: header.h game.h game.cpp main.cpp EDIT 3: here is the code: header.h #ifndef HEADER_H #define HEADER_H #define macro #endif game.h #ifndef GAME_H #define GAME_H #include "header.h" class game { public: #ifdef macro int test; #else int test; #endif void init(); }; #endif game.cpp #include "header.h" #include "game.h" void game::init() { #ifdef macro int test; #else int test; #endif } main.cpp #include "header.h" #include "game.h" int main() { game g; g.init(); }
i also want to use #ifdef in game.cpp source ... What is right way ? This is a right way: // game.cpp #include "header.h" If "header.h" defines a macro, then including it will bring the macro definition to the translation unit.
70,254,325
70,254,469
C++ dynamic linking to libraries upgrade
I have a question regarding dynamic linking libraries. Say I have a libfoo.so that requires libbar.so. Currently it links with libbar.so.100 (version 1.0.0). There's a new version of bar, libbar.so.200, and foo does not use any new features of bar v2.0.0. and APIs which it was using are unchanged. Can I straightaway upgrade to libbar.so.200 and can libfoo dynamically link to it?
This is a question of ABI stability. Often "major" versions of libraries break ABI stability and it won't work. That is one common way to distinguish between major and minor version bumps; minor version bumps are backwards compatible, major ones are not. There is no guarantee at all either way. Many minor details could make it work or not, and it requires some effort on the part of the library developer to ensure it does work.
70,254,822
70,254,986
passing vector of pointers
I'm having a problem with my vector passed in a function as a parameter. I'm getting the following error: void checkout(std::vector<InvoiceItem,std::allocator<InvoiceItem>>)': cannot convert argument 1 from 'std::vector<InvoiceItem *,std::allocator<InvoiceItem *>>' to 'std::vector<InvoiceItem,std::allocator<InvoiceItem>>' classwork15 C:\Users\dhuan\source\repos\classwork15\classwork15\main.cpp I called the vector vector<InvoiceItem*> order; I'm calling the function in my main, in a while loop. while (choice <= 4 && again == 'y') { if (choice == 1) { invoice = addToCart(); cart.append(invoice); InvoiceItem* ptr = new InvoiceItem(invoice); order.push_back(ptr); } else if (choice == 2) { cart.display(); } else if (choice == 3) { checkout(order); // <-here } cout << "1: add to order, 2: view cart, 3: checkout" << endl; cout << "Your choice: " << endl; cin >> choice; cout << endl; } This is the function, if it helps: void checkout(vector<InvoiceItem*> order) { string name; char again = 'y'; int orderNum = 1000; double total; cout << "Checking out" << endl; cout << "Enter name: "; cin >> name; cout << endl; cout << "INVOICE" << endl; cout << "Order Number: " << orderNum++ << endl; cout << "Customer: " << name << endl; cout << endl; cout << "QTY \tDescription \t\tEach \tSubtotal" << endl; for (int i = 0; i < order.size(); i++) { cout << i + 1 << "\t" << order[i]->getDescription() << "\t\t" << order[i]->getPrice() << "\t" << order[i]->getTotal() << endl; total += order[i]->getTotal(); } cout << "Total Due: "; cin >> total; cout << endl; }
I've distilled your question down to a minimum reproducible example. If you were to remove all unnecessary junk from your program, you would have something like this: #include <vector> using std::vector; class InvoiceItem {}; // (A) void checkout(vector<InvoiceItem> order); int main() { vector<InvoiceItem*> order; checkout(order); //<-- error occurs here } // (B) void checkout(vector<InvoiceItem*> order) { } Indeed, this gives the same compiler error. The problem is that the declaration of the function that main() knows about contains an error. So before the compiler even reaches your function definition, it parses main and immediately has a type mismatch. The error message should not only tell you what line that happened on, but should also direct you to the line where it got the declaration in the first place. Fast-forward to your function definition at (B). Well, that's an entirely different function from what main knew about. As such, it's called an overload -- it's a different function that happens to have the same name as (A). void checkout(vector<InvoiceItem> order); So, in case it's not now obvious, the function signature at (A) should be made to match the one at (B). That way, it refers to the same function that main knows about. And so even though the function hasn't yet been defined while the compiler is parsing main, it at least refers to the correct function with the correct parameter type.
70,255,312
70,255,344
When printing X variable it prints "123" then the actual variable value
When you type in 4 it should output only 2 but instead it outputs 12, same goes for 6 it outputs 123 and so on and so forth int main() { int salary, yearsOfService, X; //rounded off for computation of bonuse string companyName; std::cin >> yearsOfService; if (yearsOfService >= 1){ //X is rounded off case number for amount of years X = 0; X = 1; std::cout << X; if (yearsOfService>=2){ X = 0; X = 2; std::cout << X; } if (yearsOfService>=5){ X = 0; X = 3; std::cout << X; } if (yearsOfService>=6){ X = 0; X = 4; std::cout << X; } if (yearsOfService>=11){ X = 0; X = 5; std::cout << X; } } }
Your program is doing exactly what you told it to do. It will run down and execute those statements in sequence. It sounds like what you're trying to do is this: X = 0; if (yearsOfService >= 11) X = 5; else if (yearsOfService >= 6) X = 4; else if (yearsOfService >= 5) X = 3; else if (yearsOfService >= 2) X = 2; else if (yearsOfService >= 1) X = 1; if (X != 0) std::cout << X; Another way instead of using else is to just add 1 to X any time one of these conditions is satisfied. Then you can run them in any order.
70,255,549
70,255,645
return std::move a class with a unique_ptr member
Why can't I return a class containing a std::unique_ptr, using std::move semantics (I thought), as in the example below? I thought that the return would invoke the move ctor of class A, which would std::move the std::unique_ptr. (I'm using gcc 11.2, C++20) Example: #include <memory> class A { public: explicit A(std::unique_ptr<int> m): m_(std::move(m)) {} private: std::unique_ptr<int> m_; }; A makit(int num) { auto m = std::make_unique<int>(num); return std::move(A(m)); // error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'x86-64 gcc 11.2 #1 } int main() { auto a = makit(42); return 0; } I believe the solution is to return a std::unique_ptr, but before I give in I wonder why the move approach doesn't work.
I thought that the return would invoke the move ctor of class A, which would std::move the std::unique_ptr. All true, but the move constructor only moves the members of A. It cannot move unrelated satellite unique pointers for you. In the expression A(m), you use m as an lvalue. That will try to copy m in order to initialize the parameter m of A::A (btw, terrible naming scheme to reason about all of this). If you move that, i.e. A(std::move(m)), the expression becomes well-formed. And on that subject, the outer std::move in std::move(A(...)) is redundant. A(...) is already an rvalue of type A. The extra std::move does nothing good here.
70,255,833
70,255,882
Two different enums have same items not working in c++
I really want to be able to do this in my code, but this error: redefinition of enumerator 'TEST' enum test1 { TEST }; enum test2 { TEST }; Is there a way to get around this since I really want the same names inside the different enums. Also why is this happening?
This can be solved by defining your enums as enum class instead of plain enums. By defining as a plain enum, the names are unscoped and therefore conflict with each other. If they are defined as enum classes, the names are contained within the scope of the enum. Note, however, that as a result of this change, you will also need to use the scope resolution operator, e.g. test1::TEST and test2::TEST.
70,255,986
70,263,509
I need UTF8 encoded representation of a hex string, not UTF16
I need to get UTF8 representation of the following hex value, not UTF16. I am using C++ builder 11 setlocale(LC_ALL, ".UTF8"); String tb64 = UTF8String(U"D985");//Hex value of the letter م or M in arabic std::wstring hex; for(int i =1; i < tb64.Length()+1; ++i) hex += tb64[i]; int len = hex.length(); std::wstring newString; std::wstring byte; String S; for(int i=0; i< len; i+=4) { byte = hex.substr(i,4); wchar_t chr =( wchar_t ) ( int) wcstol(byte.c_str(), 0, 16); newString.push_back(chr); S = newString.c_str(); } the output should be م which is M in Arabic not garbage https://dencode.com/en/string?v=D985&oe=UTF-8&nl=crlf
You are assigning the hex string to a UTF8String, and then assigning that to a (Unicode)String, which will convert the UTF-8 to UTF-16. Then you are creating a separate std::wstring from the UTF-16 characters. std::wstring uses UTF-16 on Windows and UTF-32 on other platforms. All of those string conversions are unnecessary, since you are dealing with hex characters in the ASCII range. So just iterate the characters of the original hex string as-is, no conversion needed. In any case, you are trying to decode each 4-digit hex sequence directly into a binary Unicode codepoint number. But in this case, codepoint U+D985 is not a valid Unicode character. "D985" is actually the hex-encoded UTF-8 bytes of the Unicode character م (codepoint U+0645), so you need to convert each pair of 2 hex digits into a single byte, and store the bytes as-is into a UTF8String, not a std::wstring. The RTL has a StrToInt() function that can decode a hex-encoded UnicodeString into an integer, which you can then treat as a byte in this case. Try something more like this instead: String hex = _D("D985"); int len = hex.Length(); UTF8String utf8; for(int i = 1; i <= len; i += 2) { utf8 += static_cast<char>(StrToInt(_D("0x") + hex.Substring(i, 2))); } /* alternatively: UTF8String utf8; utf8.SetLength(len / 2); for(int i = 1, j = 1; i <= len; i += 2, ++j) { utf8[j] = static_cast<char>(StrToInt(_D("0x") + hex.Substring(i, 2))); } */ // use utf8 as needed... If you need to convert the decoded UTF-8 to UTF-16, just assign the UTF8String as-is to a UnicodeString, eg: UnicodeString utf16 = utf8; Or, you can alternatively store the decoded bytes into a TBytes and then use the GetString() method of TEncoding::UTF8, eg: String hex = _D("D985"); int len = hex.Length(); TBytes utf8; utf8.Length = len / 2; for(int i = 1, j = 0; i <= len; i += 2, ++j) { utf8[j] = static_cast<System::Byte>(StrToInt(_D("0x") + hex.Substring(i, 2))); } UnicodeString utf16 = TEncoding::UTF8->GetString(utf8); // use utf16 as needed... I just thought of a slightly simpler solution - the RTL also has a HexToBin() function, which can decode an entire hex-encoded string into a full byte array in one operation, eg: String hex = _D("D985"); UTF8String utf8; utf8.SetLength(hex.Length() / 2); HexToBin(hex.c_str(), &utf8[1], utf8.Length()); /* or: TBytes utf8; utf8.Length = hex.Length() / 2; HexToBin(hex.c_str(), &utf8[0], utf8.Length); */ // use utf8 as needed...
70,256,871
70,330,454
In C++, how to detect that file has been already opened by own process?
I need to create a logger facility that outputs from different places of code to the same or different files depending on what the user provides. It should recreate a file for logging if it is not opened. But it must append to an already opened file. This naive way such as std::ofstream f1(“log”); f1 << "1 from f1\n"; std::ofstream f2(“log”); f2 << "1 from f2\n"; f1 << "2 from f1\n"; steals stream and recreates the file. Log contains 1 from f2 With append, it will reuse file, but the second open steals stream from f1. Log contains 1 from f1 1 from f2 Try to guess which files will be used and open them all in the very begging will work but may create a lot of files that are not actually used. Open for append and closing on each logging call would be an almost working solution, but it seems to be a slow solution due to a lot of system calls and flushing on each logging action. I’m going to create a static table of opened files, hoping that std::filesystem::canonical will work in all of my cases. But as far as I understand such a table should already exist somewhere in the process. I've read that in Fortran people can check if a file was opened using inquire. Check whether file has been opened already But that answer did not give me any insight on how to achieve the same with С/C++. Update A scratch of the logger with a "static" table of open logs can look like //hpp class Logger { static std::mutex _mutex; static std::unordered_map<std::string, std::ofstream> _openFiles; std::ostream& _appender; std::ostream& _createAppender(const std::filesystem::path& logPath); public: Logger(const std::filesystem::path& logPath): _appender(_createAppender(logPath)) { } template<class... Args> void log(const Args&... args) const { std::scoped_lock<std::mutex> lock(_mutex); (_appender << ... << args); } }; //cpp #include "Logger.hpp" std::mutex Logger::_mutex; std::unordered_map<std::string, std::ofstream> Logger::_openFiles; std::ostream& Logger::_createAppender(const std::filesystem::path& logPath) { if (logPath.empty()) return std::cout; const auto truePath{std::filesystem::weakly_canonical(logPath).string()}; std::scoped_lock<std::mutex> lock(_mutex); const auto entry{_openFiles.find(truePath)}; if (entry != _openFiles.end()) return entry->second; _openFiles.emplace(truePath, logPath); std::ostream& stream{_openFiles[truePath]}; stream.exceptions(std::ifstream::failbit|std::ifstream::badbit); return stream; } maybe it will help someone. Yet, I still wonder if it is possible to get table mapping handles/descriptors from OS mentioned by @yzt, and will accept as an answer if someone explains how to do that inside the program.
So here is a simple Linux specific code that checks whether a specified target file is open by the current process (using --std=c++17 for dir listing but any way can be used of course). #include <string> #include <iostream> #include <filesystem> #include <sys/types.h> #include <unistd.h> #include <limits.h> bool is_open_by_me(const std::string &target) { char readlinkpath[PATH_MAX]; std::string path = "/proc/" + std::to_string(getpid()) + "/fd"; for (const auto & entry : std::filesystem::directory_iterator(path)) { readlink(entry.path().c_str(), readlinkpath, sizeof(readlinkpath)); if (target == readlinkpath) return true; } return false; } Simply list the current pid's open handles via proc, then use readlink function to resolve it to the actual file name. That is the best way to do it from the userspace I know. This information is not known by the process itself, it is known by the kernel about the process, hence the process has to use various tricks, in this case parsing procfs, to access it. If you want to check whether a different process hold an open handle to a file, you will have to parse all the procfs for all processes. That may not be always possible since other processes may be run by different users. All that said - in your specific case, when you are the one owner, opening and closing the files - maintaining a table of open handles is a much cleaner solution.
70,257,218
70,269,061
"Could Not Load SSL Library" error in C++Builder
This has already been discussed several times, but this time I'm here to ask you because it's the same case. First of all, the point of the problem is that when using the Get() function of TIdHTTP on an HTTPS web page, a message appears that the SSL library cannot be loaded. So I added TIdSSLIOHandlerSocketOpenSSL to TIdHTTP::IOHandler, changed the TIdHTTP::HandleRedirects property to true, moved the libeay32.dll and ssleay32.dll files to the location of the executable file, and it worked normally in C++Builder Berlin. However, in C++Builder 2007, even if I set it up with the same environment and Get() code, the "Could Not Load SSL Library" error appears. If anyone has experienced similar problems, can you please give me your solution?
In comments, you mention that Indy's WhichFailedToLoad() function is reporting various ..._indy functions are missing in the OpenSSL DLLs. The fact that Indy is looking for those functions means you are using Indy v8 or v9, not v10. You can verify that by looking at the gsIdVersion global variable in the IdGlobal unit. Indy v8 and v9 require custom-built OpenSSL 0.9.6 DLLs. At the time, Indy needed access to various OpenSSL internals that OpenSSL did not expose public access to yet (that was rectified in later OpenSSL versions), so Indy needed to add some custom functions to the DLLs. You can get those DLLs from the Archive folder of Indy's OpenSSL-Binaries repository. However, Indy v8 and v9 are OLD and no longer supported. They DO NOT support OpenSSL 1.0.x and later versions. You will have to upgrade to Indy v10, which uses standard OpenSSL DLLs, and officially supports up to OpenSSL 1.0.2u (support for OpenSSL 1.1.x is work in progress, but you can try it if you need to use OpenSSL 1.1.x, such as for TLS 1.3).
70,257,579
70,257,730
How to set inverval in milisecond between gif frames with Imagemagick++
Creating a Gif using ImageMagick 6.9.7.4. I convert a vector of QImage, to ImageMagick image type and create a gif using the static method. But resulted gif is so fast, how can set I an interval between frames, or make by gif some slow? std::vector<Magick::Image> listOfImages; for (QImage &image:m_listOfImages) { qDebug()<< image.size(); { listOfImages.push_back(QImageToImage(image)); } } qDebug()<< listOfImages.size(); QString gifName=QDateTime::currentDateTime().toString(QStringLiteral("hh-mm-ss"))+".gif"; Magick::writeImages(listOfImages.begin(), listOfImages.end(), gifName.toStdString()); qDebug()<< "Done"; and QImage to Magick::Image Magick::Image DspPresenter::QImageToImage(QImage &qimage) { qDebug() << "toImage:" << qimage.width() << qimage.height(); const Magick::Geometry geometry(qimage.width(), qimage.height()); const Magick::ColorRGB color(0.5, 0.2, 0.3); Magick::Image newImage(geometry, color); double scale = 1 / 256.0; newImage.modifyImage(); Magick::PixelPacket *pixels; Magick::ColorRGB mgc; for (int y = 0; y < qimage.height(); ++y) { pixels = newImage.setPixels(0, y, newImage.columns(), 1); for (int x = 0; x < qimage.width(); ++x) { QColor pix = qimage.pixel(x, y); mgc.red(scale *pix.red()); mgc.green(scale *pix.green()); mgc.blue(scale *pix.blue()); *pixels++ = mgc; } newImage.syncPixels(); } return newImage; }
Image img1( "100x100", "white" ); img1.pixelColor( 49, 49, "red" ); frames.push_back(img1); Image img2( "100x100", "red" ); img2.pixelColor( 49, 49, "white" ); frames.push_back(img2); img1.animationDelay(2000); img2.animationDelay(2000);*/ Magick::writeImages(frames.begin(), frames.end(), "f:\\2.gif"); Sure, you should set an animationDelay property in Magick::Image object
70,257,751
70,258,061
Move a file or folder to the RecycleBin/Trash (C++17)
I am trying to write function to move files to trash. For example when I use a file path with unicode and whitespace I cannot send it to the Recycle Bin. ...\Yönü Değiştir\Yönü Değiştir Sil.txt I found many examples on the forum. But I couldn't run it correctly. Where did I go wrong, Can you help me write the function correctly? My function and code is like this: . includes... . . bool recycle_file_folder(std::string path) { std::wstring widestr = std::wstring(path.begin(), path.end()); const wchar_t* widecstr = widestr.c_str(); SHFILEOPSTRUCT fileOp; //#include <Windows.h>; fileOp.hwnd = NULL; fileOp.wFunc = FO_DELETE; fileOp.pFrom = widecstr; /// L"C:\\Users\\USER000\\Documents\\Yönü Değiştir\\Yönü Değiştir Sil.txt"; fileOp.pTo = NULL; fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_NOCONFIRMATION | FOF_SILENT; int result = SHFileOperation(&fileOp); if (result != 0) { return false; } else { return true; } } int main() { std::filesystem::path p("C:\\Users\\USER000\\Documents\\Yönü Değiştir\\Yönü Değiştir Sil.txt"); recycle_file_folder(p.string()); return 0; } Now it works successfully when you specify the file like this: fileOp.pFrom = L"C:\\Users\\USER000\\Documents\\Yönü Değiştir\\Yönü Değiştir Sil.txt"; How do I adapt this to function for all files?
I think your conversion between wstring and string has problem. Note that std::filesystem supports converting to both string and wstring so let's re-write your code a bit bool recycle_file_folder(std::wstring path) { std::wstring widestr = path + std::wstring(1, L'\0'); SHFILEOPSTRUCT fileOp; fileOp.hwnd = NULL; fileOp.wFunc = FO_DELETE; fileOp.pFrom = widestr.c_str(); fileOp.pTo = NULL; fileOp.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_NOCONFIRMATION | FOF_SILENT; int result = SHFileOperation(&fileOp); if (result != 0) { return false; } else { return true; } } int main() { std::filesystem::path p("C:\\Users\\USER000\\Documents\\Yönü Değiştir\\Yönü Değiştir Sil.txt"); recycle_file_folder(p.wstring()); return 0; }
70,257,914
70,257,994
Clang generates strange output when dividing two integers
I have written the following very simple code which I am experimenting with in godbolt's compiler explorer: #include <cstdint> uint64_t func(uint64_t num, uint64_t den) { return num / den; } GCC produces the following output, which I would expect: func(unsigned long, unsigned long): mov rax, rdi xor edx, edx div rsi ret However Clang 13.0.0 produces the following, involving shifts and a jump even: func(unsigned long, unsigned long): # @func(unsigned long, unsigned long) mov rax, rdi mov rcx, rdi or rcx, rsi shr rcx, 32 je .LBB0_1 xor edx, edx div rsi ret .LBB0_1: xor edx, edx div esi ret When using uint32_t, clang's output is once again "simple" and what I would expect. It seems this might be some sort of optimization, since clang 10.0.1 produces the same output as GCC, however I cannot understand what is happening. Why is clang producing this longer assembly?
The assembly seems to be checking if either num or den is larger than 2**32 by shifting right by 32 bits and then checking whether the resulting number is 0. Depending on the decision, a 64-bit division (div rsi) or 32-bit division (div esi) is performed. Presumably this code is generated because the compiler writer thinks the additional checks and potential branch outweigh the costs of doing an unnecessary 64-bit division.
70,258,201
70,258,308
Inputs of a method depending on the template structure
template <typename Stru_> class templateClasse{ public: using stru = Stru_; static void method_0(int sk, int sl){ printf("class templateClass method_0 sk: %d sl: %d\n", sk, sl); } static void method_1(int a){ if (stru::isvec){ method_0(0, a); } else{ method_0(a, 0); } } }; I would like to change the inputs in the method_0 depending on the bool stru::isvec as the code shows, meanwhile, I wish that the choice of if (stru::isvec) else branch is made during compilation rather than the runtime. My questions are: Does this code choose the method_0 during compilation? The code is successfully compiled only when I add the keyword staticbefore those two methods. Why should staticworks in this case? Usally, my understanding of staticis like this: These static variables are stored on static storage area, not in stack. and I know when I use static const int tmp = 50; this tmp is computed in compiled-time. So can static be roughly understood as a keyword to help compile-time computation? Do we have other solutions in this case? Thanks in advance!
Does this code choose the method_0 during compilation? No, the dispatch happens at run-time. You can use constexpr if (since C++17) to make the dispatch performed at compile-time. void method_1(int a){ if constexpr (stru::isvec){ method_0(0, a); } else{ method_0(a, 0); } } The code is successfully compiled only when I add the keyword static before those two methods. No, you don't have to. This is a side issue; in class definition static is used to declare static members that are not bound to class instances. LIVE With C++11, you can perform overloading with SFINAE. E.g. template <typename T = Stru_> typename std::enable_if<T::isvec>::type method_1(int a){ method_0(0, a); } template <typename T = Stru_> typename std::enable_if<!T::isvec>::type method_1(int a){ method_0(a, 0); } LIVE
70,258,239
70,259,030
LED blinking only when Serial Monitor is not open
I have a really simple code that is not behaving how I would expect it to. Here's the code: int i; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { //digitalWrite(13, HIGH); i = random(1,5); Serial.println(i); digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); } With this code the LED only blinks when Serial Monitor is on and stays on while Serial Monitor is off. Another problem I have is that if I comment out the current digitalWrite(LED_BUILTIN, HIGH) and replace it with the one I have commented out then the LED wont blink even if Serial Monitor is off. I have Arduino Micro
If you want to blink a LED, you need to add an extra delay when the LED is going from OFF to ON. Currently you have: LED ON -> wait -> LED OFF -> (instantly) LED ON -> wait etc So what you see is just the LED continuously ON, to make it work add another delay(1000) before digitalWrite(13, HIGH) for example: int i; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { //digitalWrite(13, HIGH); i = random(1,5); Serial.println(i); delay(1000); digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); } I tested it on my Arduino Nano and it worked fine.
70,258,418
70,258,852
Why is a segmentation fault not recoverable?
Following a previous question of mine, most comments say "just don't, you are in a limbo state, you have to kill everything and start over". There is also a "safeish" workaround. What I fail to understand is why a segmentation fault is inherently nonrecoverable. The moment in which writing to protected memory is caught - otherwise, the SIGSEGV would not be sent. If the moment of writing to protected memory can be caught, I don't see why - in theory - it can't be reverted, at some low level, and have the SIGSEGV converted to a standard software exception. Please explain why after a segmentation fault the program is in an undetermined state, as very obviously, the fault is thrown before memory was actually changed (I am probably wrong and don't see why). Had it been thrown after, one could create a program that changes protected memory, one byte at a time, getting segmentation faults, and eventually reprogramming the kernel - a security risk that is not present, as we can see the world still stands. When exactly does a segmentation fault happen (= when is SIGSEGV sent)? Why is the process in an undefined behavior state after that point? Why is it not recoverable? Why does this solution avoid that unrecoverable state? Does it even?
When exactly does segmentation fault happen (=when is SIGSEGV sent)? When you attempt to access memory you don’t have access to, such as accessing an array out of bounds or dereferencing an invalid pointer. The signal SIGSEGV is standardized but different OS might implement it differently. "Segmentation fault" is mainly a term used in *nix systems, Windows calls it "access violation". Why is the process in undefined behavior state after that point? Because one or several of the variables in the program didn’t behave as expected. Let’s say you have some array that is supposed to store a number of values, but you didn’t allocate enough room for all them. So only those you allocated room for get written correctly, and the rest written out of bounds of the array can hold any values. How exactly is the OS to know how critical those out of bounds values are for your application to function? It knows nothing of their purpose. Furthermore, writing outside allowed memory can often corrupt other unrelated variables, which is obviously dangerous and can cause any random behavior. Such bugs are often hard to track down. Stack overflows for example are such segmentation faults prone to overwrite adjacent variables, unless the error was caught by protection mechanisms. If we look at the behavior of "bare metal" microcontroller systems without any OS and no virtual memory features, just raw physical memory - they will just silently do exactly as told - for example, overwriting unrelated variables and keep on going. Which in turn could cause disastrous behavior in case the application is mission-critical. Why is it not recoverable? Because the OS doesn’t know what your program is supposed to be doing. Though in the "bare metal" scenario above, the system might be smart enough to place itself in a safe mode and keep going. Critical applications such as automotive and med-tech aren’t allowed to just stop or reset, as that in itself might be dangerous. They will rather try to "limp home" with limited functionality. Why does this solution avoid that unrecoverable state? Does it even? That solution is just ignoring the error and keeps on going. It doesn’t fix the problem that caused it. It’s a very dirty patch and setjmp/longjmp in general are very dangerous functions that should be avoided for any purpose. We have to realize that a segmentation fault is a symptom of a bug, not the cause.
70,258,567
70,291,681
Old task from local ICPC "Computer Class"
There is a task on which I have been racking my brains for three days. The task is called Computer Class (not to be confused with other tasks from ICPC, there are many similarly named tasks). Problem conditions: There are n * m (arranged respectively in m rows and n desks in each row) desks and students. Each student from 1 to n * m has a unique (including n * m) number. It is necessary to arrange the students so that the difference between the numbers of neighbors is more than one (those who are from above, from below and those who are from the left, the right are also neighbors). ///////////////////////////////////////////////////////////// forgot to mention: numbers are limited to a radius of 1≤n, m ≤50. And the time for the program to work is half a second (and 5 seconds in real time). ///////////////////////////////////////////////////////////// As a result: need to write a program (preferably in the languages ​​python and C ++) an algorithm capable of accepting two numbers (n and m) to give any suitable order of the students' arrangement (if it is impossible to give such an arrangement -1). For example: given: 3, 4 taked: Or given: 1, 2 taked: -1 My attempts to solve the problem: I used the method of creating all sequences from n numbers (the method is taken from one book) and using checking functions to find the desired sequence. When I did it with a dynamic array, I succeeded, or so I thought. The program taking toooo long when it was necessary to find an answer from a sequence of 15 (3 * 5) or more numbers. After the advice I received and much thought, I broke my head and came up with a code that would completely solve this problem. And now how to close the question? (there is code): #include <iostream> using namespace std; void CClass(int n, int m); int main(void) { while (true) { cout << "\n Numbers please:\n"; int n, m; cin >> n; cin >> m; cout << endl; CClass(n, m); } } void CClass(int n, int m) { int len = n * m; if (len == 6) { cout << "1.\t3.\t5.\n4.\t6.\t2.\n"; return ; } if (len == 9) { cout <<"1.\t3.\t5.\n4.\t6.\t2.\n7.\t9.\t11.\n"; return ; } if (n < 4) { if (m < 4) { cout << "- 1\n"; return ; } } for (int i = 0, j = 2, k = 1; i < len; i++) { if (len >= j) { cout << j << ".\t"; j += 2; } else { cout << k << ".\t"; k += 2; } if ((i + 1) % n == 0) { cout << endl; } } }
I decided to just first collect all even and then odd ones on the screen as an answer, and in those units of cases in which this did not work, I simply hardcode (there were only two of them: 3x3; 2x3). You can see the code above.
70,258,578
70,285,800
c++ interface throws "undefined reference to `vtable for 'interface'" error
I am building a sound generator program in Java and I am trying to port it to c++ I can easily do this in Java, but I am new to c++ In c++ I have an interface called iSamplePlayer and this is the iSample.h file: class ISamplePlayer { public: virtual double GetFrequency() virtual void SetFrequencyAtZero(double frequency) virtual void SetSampleRate(uint32_t sampleRate) virtual void SetAmplitude(double amplitude) //virtual void SetAdsrEnvelope(AdsrEnvelope adsrEnvelope) virtual void SetOffset(double offset) virtual void AddToFrequency(double offset) virtual void SubtractFromFrequency(double offset) virtual double GenerateWaveformPoint() = 0; }; a base class called AWaveform, this is the AWaveform.h file: class AWaveform : public ISamplePlayer{ public: // constants const uint32_t SAMPLE_RATE = 44100; // constructors AWaveform(double frequency, uint32_t sampleRate); AWaveform(double frequency); AWaveform(const AWaveform& orig); virtual ~AWaveform(); // getters setter and other methods are here // generateWaveForm method virtual double GenerateWaveformPoint() override = 0; private: // instance variables double amplitude; // volume double frequency; // pitch double point; // current sample uint32_t sampleRate; // rate of samples per second double holdFrequency; // hold frequency till it can be changed. double waveLength; // length of one waveform in samples double waveSampleIndex; // keeps track of the waveLength }; and Finally in the class SineGenerator, I have the GenerateWaveformPoint() function in the SineGenerator.h that actualy overrides with code: class SineGenerator : AWaveform{ public: // constants const double DEF_PEAK_PERCENTAGE = 0.5; const double DEF_HORIZONTAL_OFFSET = 0; // constructors SineGenerator(double frequency, double peakPercentage, double offset); SineGenerator(double frequency, double peakPercentage); SineGenerator(double frequency); SineGenerator(const SineGenerator& orig); virtual ~SineGenerator(); // methods double GenerateWaveformPoint() override { // check frequency CheckFrequency(); // genorate point. DrawSinePoint(); // checks if waveSampleIndex is equal to wavelength CheckWaveLength(); // apply ADSR amplitude //if (getAdsrEnvelope() != null) { // setPointVolume(getAdsrEnvelope().getADSRvolume()); //} // set volume SetPointVolume(GetAmplitude()); // return the sample data return GetPoint(); } protected: void DrawSinePoint() { // code goes here } private: // instance variables double peakPercentage; double smallWaveFrequency; // used for != 50% waves double smallWaveIndex; // index of smallwave double smallWaveLength; // use to hold small wave length for != 50% double holdIndex; // used to keep track of hold time double holdLength; // use to hold hold length for != 50% double updatePeakPercentage; // holds the update value }; It gives this error "undefined reference to `vtable for ISamplePlayer'". How do I properly make a virtual function that overrides an interface's virtual function?
OK, I was a dummy. I forgot to add = 0; to the other functions in the interface. Everyone that is learning c++ and already knows java or c#, all functions that you intend to be abstract need to be virtual and end in = 0; These are called pure virtual functions. Learn from my mistake.
70,259,260
70,259,283
Difference between a `vector` created from the std `<vector>` library, and an `STL vector` created from: `<stl_vector.h>`
Why are there two different vector libraries in the STD library?   stl_vector.h   vector.h What's the difference between the two?
If you look into the file itself you will see /** @file bits/stl_vector.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{vector} */ Your code should not directly include stl_vector.h. It's an implementation detail of libstdc++ and could be absent in other standard library implementations.
70,259,749
70,259,892
How to replace a number in a file with its sum?
I'd like to write a program that gets an integer in a file, sums it with a input number and replace the previous integer in the file with the result of the sum. I thought the following code would work, but there's a 0 written in the file that remains 0, no matter the integer I input. What am I doing wrong? #include <iostream> #include <fstream> using namespace std; int main() { fstream arq; arq.open("file.txt"); int points, total_points; cin >> points; arq >> total_points; total_points += points; arq << total_points; }
You can try reading and writing the input file separately as shown below: #include <iostream> #include <fstream> using namespace std; int main() { ifstream arq("file.txt"); int points=0, total_points=0; cin >> points; arq >> total_points; total_points += points; arq.close(); ofstream output("file.txt"); output << total_points; output.close(); } The output of the above program can be seen here.
70,259,909
70,260,674
partial class template argument deduction in C++
I have a templated class but only part of the template arguments can be deduced from the constructor. Is there a way to provide the rest of the template arguments inside angle brackets when calling the constructor? Assume we're using C++17. template<typename T1, typename T2> struct S { T2 t2; S(const T2& _t2) : t2{_t2} {} void operator()(const T1& t1) { std::cout << t1 << ", " << t2 << '\n'; } }; int main() { S<int, double> s {3.14}; std::function<void(int)> func = s; func(42); // What I want: //S<int> s2 {3.14}; <- T1 is provided in the angle brackets, T2 is deduced //std::function<void(int)> func2 = s; //func2(42); } As far as I know we need to either provide all the template arguments in angle brackets or none of them and use CTAD. The problem is that I don't want to write all the template arguments (in my actual use case there's like 5-6 of them and they are quite verbose) but I also don't want to pass all the arguments in the constructor because some of them are not used to construct the object. I just need their types for the operator() method. I cannot make the operator() method templated because I want to bind it to a std::function object and I cannot deduce the template parameter types during the bind. So that's why I need all the types in the wrapping class. This partial template deduction exists for functions. For example: template<typename T1, typename T2> void foo(const T2& t2) { T1 t1{}; std::cout << t1 << ", " << t2 << '\n'; } int main() { foo<int>(3.4); //T1 is explicitly int, T2 is deduced to be double } My current solution is to exploit this feature and construct the object through a function: template<typename U1, typename U2> S<U1, U2> construct_S(const U2& t2) { return S<U1, U2>{t2}; } int main() { auto s2 = construct_S<int>(1.5); std::function<void(int)> func2 = s2; func2(23); } I find this solution clumsy because we're using an external function to construct the object. I was wondering if there's a cleaner solution for doing this. Maybe something with deduction guides? I'm not sure.
As mentioned in a comment, you can use a nested class such that the two parameters can be provided seperately (one explicitly the other deduced): template<typename T1> struct S { template <typename T2> struct impl { T2 t2; impl(const T2& _t2) : t2{_t2} {} }; template <typename T2> impl(const T2&) -> impl<T2>; }; int main() { S<int>::impl<double> s {3.14}; S<int>::impl s2 {3.14}; // <- T1 is provided in the angle brackets, T2 is deduced } I found this How to provide deduction guide for nested template class?. Though, the above code compiles without issues with both gcc and clang: https://godbolt.org/z/MMaPYGbe1. If refactoring the class template is not an option, the helper function is a common and clean solution. The standard library has many make_xxx functions, some of them were only needed before CTAD was a thing.
70,260,994
70,261,259
Automatic template deduction C++20 with aggregate type
I am puzzled about this C++ code: template <class T> struct Foo { T value; }; int main() { return Foo<int>(0).value; // Below code works as well in gcc // return Foo(0).value; } It compiles with GCC 10 in C++20 standard (but not in C++17 standard) and latest MSVC, but not with clang 13 or 14, even in C++20. According to the standard (from cppreference) it should be possible to instantiate Foo at least when specifying the templated type. Why is this related to C++20 ? I see nothing that change in the template deduction specification (I maybe missed something). Also (this is strange), GCC in C++20 mode even compiles when we call Foo without specifying templated type (Foo(0)). godbolt link here
It compiles with GCC 10 in C++20 standard (but not in C++17 standard) and latest MSVC. This is because GCC 10 and the latest MSVC implement allow initializing aggregates from a parenthesized list of values, which allows us to use parentheses to initialize aggregates. Also (this is strange), GCC in C++20 mode even compiles when we call Foo without specifying templated type (Foo(0)). This is because GCC 10 implements class template argument deduction for aggregates, which makes T automatically deduced to int. Please note that clang does not currently implement these two C++20 features, so your code cannot be accepted by clang. You can refer to cppreference to get the current compiler's support for C++20 features.
70,261,289
70,261,355
How to get the total 'percentage' of RAM in C++?
Hi I am building an application in C++. I want get the percentage of RAM that a windows machine is using. I tried a few codes like: string getRamUsage() { MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; return to_string(physMemUsed); } but it just returns some assembly value. Can I get a solution?
You need to call GlobalMemoryStatusEx to get the data. MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); GlobalMemoryStatusEx (&statex); // it already contains the percentage auto memory_load = statex.dwMemoryLoad; // or calculate it from other field if need more digits. auto memory_load = 1 - (double)statex.ullAvailPhys / statex.ullTotalPhys; note: you should check the return value of GlobalMemoryStatusEx in case it fail.
70,261,320
70,261,442
Visual Studio, How to SEPARATE the input and the output IN C++ Competitive Programming
I want to separate the input and the output this is MY CONSOLE and I want Like this WANTED OR in seperate files
You can store your answers in a container (vector, array, etc) and print all of them when no new inputs are expected. Keep in mind that in competitive programming, most of the times the judge doesn't care when you produce your output, unless specifically said so.
70,261,360
70,261,751
Warn against missing std:: prefixes due to ADL
It is possible to omit the std:: namespace for <algorithm>s when the argument types are in that namespace, which is usually the case. Is there any warning or clang-tidy rule that finds such omissions? #include <vector> #include <algorithm> std::vector<int> v; for_each(v.begin(), v.end(), [](auto){}); return 0; The above example, compiled with the latest clang and -Wall, -Wextra and -Wpedantic does not emit any diagnostic: https://godbolt.org/z/dTsKbbEKe
There is an open change in tidy that could be used to flag this: D72282 - [clang-tidy] Add bugprone-unintended-adl [patch] Summary This patch adds bugprone-unintended-adl which flags uses of ADL that are not on the provided whitelist. bugprone-unintended-adl Finds usages of ADL (argument-dependent lookup), or potential ADL in the case of templates, that are not on the provided lists of allowed identifiers and namespaces. [...] .. option:: IgnoreOverloadedOperators If non-zero, ignores calls to overloaded operators using operator syntax (e.g. a + b), but not function call syntax (e.g. operator+(a, b)). Default is 1. .. option:: AllowedIdentifiers Semicolon-separated list of names that the check ignores. Default is swap;make_error_code;make_error_condition;data;begin;end;rbegin;rend;crbegin;crend;size;ssize;empty. .. option:: AllowedNamespaces Semicolon-separated list of namespace names (e.g. foo;bar::baz). If the check finds an unqualified call that resolves to a function in a namespace in this list, the call is ignored. Default is an empty list. There seems to have been no activity on the patch since July 2020, though, but if this is of interest of the OP, the OP could try to resuscitate the patch.
70,261,395
70,263,071
Environment variable error while trying to create a solver in OpenFOAM 9
I'm trying to create a solver in my /opt/OpenFOAM/OpenFOAM-9/applications/solvers/electromagnetics directory using sudo foamNewSource App newSolver. But, I keep getting the following error: foamNewSource: Creating new interface file newSolver.C wmakeFilesAndOptions error: environment variable $WM_OPTIONS not set And then, although I can see a newSolver.C file, I cannot see a Make directory and neither the rest of the files. I'm running EndeavourOS Linux x86_64 with kernel 5.15.6-arch2-1 and shell bash 5.1.12. I installed the openfoam-org package from the AUR, and in order to set it up, I have the following in my .bashrc config file: source /opt/OpenFOAM/OpenFOAM-9/etc/bashrc At first, when I did env | grep WM I couldn't find WM_OPTIONS in my system. So, after googling a little bit, I added this to my .bashrc file: source /opt/OpenFOAM/OpenFOAM-9/etc/bashrc export WM_OPTIONS=linux64GccDPOpt And now, doing env | grep WM I get: WM_COMPILER=Gcc WM_PRECISION_OPTION=DP WM_PROJECT_USER_DIR=/home/username/OpenFOAM/username-9 WM_MPLIB=SYSTEMOPENMPI WM_OPTIONS=linux64GccDPOpt WM_ARCH=linux64 WM_LABEL_SIZE=32 WM_PROJECT=OpenFOAM WM_THIRD_PARTY_DIR=/opt/OpenFOAM/ThirdParty-9 WM_LABEL_OPTION=Int32 WM_CC=gcc WM_CFLAGS=-m64 -fPIC WM_LINK_LANGUAGE=c++ WM_OSTYPE=POSIX WM_PROJECT_VERSION=9 WM_DIR=/opt/OpenFOAM/OpenFOAM-9/wmake WM_ARCH_OPTION=64 WM_CXXFLAGS=-m64 -fPIC -std=c++0x WM_PROJECT_INST_DIR=/opt/OpenFOAM WM_LDFLAGS=-m64 WM_CXX=g++ WM_COMPILE_OPTION=Opt WM_PROJECT_DIR=/opt/OpenFOAM/OpenFOAM-9 WM_COMPILER_TYPE=system WM_COMPILER_LIB_ARCH=64 Now I can see the WM_OPTIONS environment variable (just above WM_ARCH=linux64 and below WM_MPLIB=SYSTEMOPENMPI), but I still get the same wmakeFilesAndOptions error. I don't know what configuration I'm messing up, so I'd appreciate some help! Thanks!
Using sudo in this case is not a good idea, instead run the scripts on your home directory: mkdir -p $FOAM_RUN cd $FOAM_RUN foamNewSource App newSolver For WM_OPTIONS environment variable, don't set it manually, instead use: export WM_OPTIONS=$WM_ARCH$WM_COMPILER$WM_PRECISION_OPTION$WM_LABEL_OPTION$WM_COMPILE_OPTION
70,261,453
70,261,840
Unable to use initializer list to assign values if structure contains a constructor
I was using initializer list to create object and assign it to the map with int key. In case of a simple structure the temporary structure can be created using initializer list. hence me doing something like this is totally valid struct fileJobPair { int file; int job; }; map<int, fileJobPair> mp; mp[1] = {10, 20}; mp[2] = {100, 200}; mp[3] = {1000, 2000}; But if I add constructor to the structure, I am getting error file.cpp: In function ‘int main()’: file.cpp:18:21: error: no match for ‘operator=’ (operand types are ‘std::map<int, fileJobPair>::mapped_type’ {aka ‘fileJobPair’} and ‘<brace-enclosed initializer list>’) 18 | mp[1] = {10, 20}; | ^ file.cpp:4:8: note: candidate: ‘constexpr AfileJobPair& AfileJobPair::operator=(const AfileJobPair&)’ 4 | struct fileJobPair { | ^~~~~~~~~~~~ file.cpp:4:8: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘const fileJobPair&’ file.cpp:4:8: note: candidate: ‘constexpr fileJobPair& fileJobPair::operator=(fileJobPair&&)’ file.cpp:4:8: note: no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘fileJobPair&&’ This is what I have tried : struct fileJobPair { int file; int job; fileJobPair() { file = job = 0; } }; int main() { map<int, fileJobPair> mp; mp[1] = {10, 20}; mp[2] = {100, 200}; mp[3] = {1000, 2000}; for(int i =1;i<=3;i++) { cout<< mp[i].file <<" "<< mp[i].job<<endl; } return 0; } Why am I getting error and how exactly is it working internally?
When you make a new fileJobPair, it will use by default your empty constructor, so will not be available anymore to be completed with {}. But you can add a new constructor to it, that receive 2 integers and bind them to the respective values, like this: #include <iostream> #include <map> using namespace std; struct fileJobPair { int file; int job; fileJobPair() { file = job = 0; } fileJobPair(int a, int b) { file = a; job = b; } }; int main() { map<int, fileJobPair> mp; mp[1] = {10,10}; mp[2] = {100, 200}; mp[3] = {1000, 2000}; for(int i =1;i<=3;i++) { cout<< mp[i].file <<" "<< mp[i].job<<endl; } return 0; }
70,261,664
70,262,481
Can atomic read operations lead to deadlocks?
I am watching this Herb Sutter's talk about atomics, mutexes and memory barriers, and I have a question regarding it. Since 47:33 Herb explains how mutexes and atomics are related to memory ordering. On 49:12 he says, that with the default memory order, which is memory_order_seq_cst, atomic load() operation is equivalent of locking a mutex, and atomic store operation is equivalent of unlocking a mutex. On 53:15 Herb was asked what would happen if the atomic load() operation in his example was not followed by subsequent store() operation, and his answer really confused me: 54:00 - If you don't write this release(mutex.unlock()) or this one(atomic.store()), that person will never get a chance to run... Maybe I completely misunderstood him due to my not very good English skills, but this is how I interpret his words: If a thread A reads an atomic variable without subsequent write into it, no other thread will be able to work with this variable due to it being deadlocked by the thread A like as if a mutex was locked by this thread without further unlocking. But is it really what he meant? It doesn't seem to be true. In my understanding release happens automatically right after an atomic variable was either loaded or stored. Just an example: #include <atomic> #include <iostream> #include <thread> std::atomic<int> number{0}; void foo() { while (number != 104) {} std::cout << "Number:\t" << number << '\n'; } int main() { std::thread thr1(foo); std::thread thr2(foo); std::thread thr3(foo); std::thread thr4(foo); number = 104; thr1.join(); thr2.join(); thr3.join(); thr4.join(); } In the above example there are 4 threads successfully reading the same atomic variable, and no any writes are needed in these threads to release the variable for other threads. Apparently, atomic.load() != mutex.lock() as well as atomic.store() != mutex.unlock(). They may behave the same way in terms of memory barriers, but they are not the same, aren't they? Could you please explain to me, what did Herb actually mean by saying they are equal?
There's a misunderstanding here. An atomic read, regardless of memory order, is not "equivalent to locking a mutex". In terms of visibility it might have the same effects, but a mutex is much heavier. Here's a typical problem with a mutex: std::mutex mtx1; std::mutex mtx2; void thr1() { mtx1.lock(); mtx2.lock(); mtx2.unlock(); mtx1.unlock(); } void thr2() { mtx2.lock(); mtx1.lock(); mtx1.unlock(); mtx2.unlock(); } Note that the two function lock the two mutexes in the opposite order. So it's possible that thr1 locks mtx1, then thr2 locks mtx2, then thr1 tries to lock mtx2 and thr2 tries to lock mtx1. That's a deadlock; neither thread can make progress, because the resource it needs is held by the other thread. Atomics don't have that problem, because you can't run code "inside" an atomic access. You can't get that sort of resource conflict. The issue that seems to underly that discussion is the possibility that the thread running while (number != 104) {} won't see the updated value of number, and so the code will be an infinite loop. That's not a deadlock. Which isn't to say that it's not a problem, but the problem is with visibility.
70,261,859
70,262,077
Is my inheritance the same as the problematic "diamond inheritance"
I have multiple virtual base classes that create interfaces for my implementation classes. I however want them all to be able to serialize and deserialize themselves. This resultes in the following ABC inheritance: Lets say I have class A which allows for serialisation and deserialisation of the class. class A{ virtual void serialize() = 0; virtual void deserialize() = 0; } I have a class B which adds some virtual calls but must also be able to handle it's own serialization operations: class B : public A { B() : A() { some_variable_B_is_responisble_for = 0; } // inherited from A virtual void serialize() {} virtual void deserialize() {} virtual void Bfunction() = 0; private: int some_variable_B_is_responisble_for; } Now I have a class C which implements both functionality from A and B. In the pattern of: A ^ ^ | | | B | ^ | | C class C : public A, public B{ C() : A(), B() { } virtual void serialize() { // do my own serialize B::serialize(); // call B's serialize } virtual void deserialize() { // do my own deserialize B::deserialize(); // call B's deserialize } virtual void Bfunction() { // implement the interface } Will this work or is there something wrong in my reasoning? I want to delegate the serialization and deserialization to all class implementations so there won't be different representations for the same base class.
What makes diamond inheritance "problematic" is that programmers new to C++ haven't yet learned about virtual inheritance and thus don't know how to achieve the diamond. Your inheritance is what people attempting the diamond inheritance end up with when they don't know how to make the diamond. However, what your inheritance lacks is the apparent need for the diamond. It's unclear why you need to inherit A a second time. If you inherit B, then you indirectly have inherited all its bases. I recommend trying out following instead: class C : public B { virtual void serialize() { // do my own serialize B::serialize(); // call B's serialize } virtual void deserialize() { // do my own deserialize B::deserialize(); // call B's deserialize } virtual void Bfunction() { // implement the interface }
70,262,414
70,262,474
C++ multiple inheritance problem using FLTK
i've a problem drawing basic shape with fltk. I've made 2 classes'Rectangle' and 'Circle' that show normally. Then i've created a third class that inherit from 'Rectangle' and 'Circle' called 'RectangleAndCircle' : //declaration in BasicShape.h class Rectangle: public virtual BasicShape, public virtual Sketchable{ int w,h; public: Rectangle(Point center, int width=50, int height=50, Fl_Color fillColor=FL_WHITE, Fl_Color frameColor=FL_BLACK); void setPoint(Point new_p){center=new_p;} virtual void draw() const override; }; class Circle:public virtual BasicShape, public virtual Sketchable{ int r; public: Circle(Point center, int rayon=50, Fl_Color fillColor=FL_WHITE, Fl_Color frameColor=FL_BLACK); virtual void draw() const override; }; class RectangleAndCircle: public virtual Rectangle, public virtual Circle{ public: RectangleAndCircle(Point center,int w, int h, int r, Fl_Color CircFillColor, Fl_Color CircFrameColor, Fl_Color RectFillColor, Fl_Color RectFrameColor); void draw() const override; When i try to draw a 'RectangleAndCircle' instance, the rectangle and the circle share the same color even if i the rectangle color is set. Here is the code for the constructor of 'RectangleAndCircle' and the drawing of the shapes : RectangleAndCircle::RectangleAndCircle(Point center, int w, int h, int r, Fl_Color CircFillColor, Fl_Color CircFrameColor, Fl_Color RectFillColor, Fl_Color RectFrameColor) :Rectangle(center,w,h,RectFillColor,RectFrameColor) , Circle(center,r,CircFillColor,CircFrameColor){} void Rectangle::draw() const { fl_begin_polygon(); fl_draw_box(FL_FLAT_BOX, center.x+w/2, center.y+h/2, w, h, fillColor); fl_draw_box(FL_BORDER_FRAME, center.x+w/2, center.y+h/2, w, h, frameColor); fl_end_polygon(); } void Circle::draw() const { fl_color(fillColor); fl_begin_polygon(); fl_circle(center.x, center.y, r); fl_end_polygon(); } void RectangleAndCircle::draw() const { Rectangle::draw(); Circle::draw(); } I create a instance of 'RectangleAndCircle' in my MainWindow class, and i draw it. RectangleAndCircle r{Point{50,50},50,50,12,FL_RED,FL_BLACK, FL_WHITE, FL_BLACK}; ... r.draw() Am i doing something wrong ?
You're using virtual inheritance. This means there will be only one instance of BasicShape in RectangleAndCircle. This BasicShape will have its fillColor set by both the Rectangle and Circle constructors, whichever being called last overwriting the value. My advice would be to not inherit here, and instead have two fields of type Circle and Rectangle in RectangleAndCricle and then call draw on those separately in draw. Inherit to be reused, not reuse (you presumably wouldn't want to pass a RectangleAndCricle as a Circle or Rectangle)
70,262,443
70,262,485
How to switch from vector::at() to [] when building Release
I find vector::at() useful for alerting against out-of-bounds bugs while debugging, but it's painfully slow and unsuited for release code. Is there a known compiler flag or some method to automatically convert vector::at() to vector::operator[] when compiling in release mode, sort of like how asserts() are stripped in release with DNDEBUG? Edit: Follow the linked question for a solution to this, or check the accepted answer (+ the comments below this question for some compiler specific stuff). Basically, this problem can be solved in reverse (there are options to allow bounds checking for vector::operator[] in debug mode).
If you want no bounds checking overhead at runtime, then use the subscript operator. With most standard library implementations, you can enable non-standard bounds checking in subscript operator. Usually by defining a macro. This has a caveat, that the entire program must be compiled in the same mode, including any linked libraries. Address/UB sanitisers should also be used when testing and debugging, and they may also detect typical buffer overflow conditions in absence of standard library support.
70,262,627
70,288,852
Is it safe to bind to C++ subobject's property in QML?
C++: database c++ object is exposed to QML as a context property. database c++ object has a method getDbpointObject() that returns pointer to databasePoint C++ object. databasePoint C++ object has a property named cppProp. main.cpp: // expose database object to qml database databaseObj; engine.rootContext()->setContextProperty("database", (QObject*)&databaseObj); // register databasePoint class qmlRegisterType<databasePoint>("DBPoint", 1, 0, "DBPoint"); database.h: databasePoint *database::getDbpointObject() databasePoint.h: Q_PROPERTY(QVariant cppProp READ cppProp WRITE setcppProp NOTIFY cppPropChanged) QML: qmlComp is a custom QML component. qmlComp has a QML property named qmlCompProp. On completion of qmlComp creation, databasePoint c++ object is assigned to qmlCompProp. qmlComp.qml: Item { property var qmlCompProp: ({}) // qml property Component.onCompleted: { qmlCompProp = database.getDbpointObject() // qml property holds the databasePoint c++ object } } Question: In binding.qml, QML property bindProp is binded to myQmlComp.qmlCompProp.cppProp Is this binding safe? Will the binding always be resolved? databasePoint c++ object is assigned to qmlCompProp in Component.onCompleted. Until then, qmlCompProp is an empty object. Will it have an impact on binding resolution? Will the order of properties evaluation in binding.qml have an impact on binding resolution? binding.qml: property int bindProp: myQmlComp.qmlCompProp.cppProp // is this binding safe? qmlComp{id: myQmlComp}
Response from Qt Support: In binding.qml, QML property bindProp is binded to myQmlComp.qmlCompProp.cppProp Is this binding safe? Looks like. Will the binding always be resolved? Assuming no reference issues, yes databasePoint c++ object is assigned to qmlCompProp in Component.onCompleted. Until then, qmlCompProp is an empty object. Will it have an impact on binding resolution? This case should work. However, the binding is initially made for the empty object in that case (depending on how this is all instantiated) and then after the onCompleted, it updates the binding to refer to that real cppProp (instead of dummy one it created to the empty object). Will the order of properties evaluation in binding.qml have an impact on binding resolution? Not in this case at least. You could have some issue if you had other dependent properties for the binding, like if you had an array in between and its index was another property.
70,262,742
70,262,821
How do I use std::rename with variables?
In my program, I store data in different text files. The data belongs to an object, which I call rockets. For example, the rocket Saturn 5 has a text file labeled "Saturn5R.txt". I want an option to rename the rocket, and so I will need to rename the text file as well. I am using std::rename in the library. I have gotten it working with something like this: char oldname[] = "Saturn5R.txt"; char newname[] = "Saturn6R.txt"; if (std::rename(oldname, newname) != 0) { perror("Error renaming file"); } This works, but I don't want to always be renaming Saturn5R.txt to Saturn6R.txt. What I want to do is to be able to rename any text file to any name, I have tried this and I get an error: char oldname[] = rocketName + RocketNumber + "R.txt"; char newname[] = NameChoice + NumberChoice + "R.txt"; if (std::rename(oldname, newname) != 0) { perror("Error renaming file"); } This returns the error "[cquery] array initializer must be an initializer list or string literal". How can I use std::rename or any other file renaming function that allows me to rename any files I want without hardcoding them in?
This has little to do with std::rename, and everything to do with how to interpolate variables into a string. A simple solution is to use std::string. It has overloaded operator + that can be used to concatenate substrings. If you want to make the program a bit fancier, C++20 added std::format: std::string oldname = std::format("{}{}R.txt", rocketName, RocketNumber); std::string newname = std::format("{}{}R.txt", NameChoice, NumberChoice); if (std::rename(oldname.c_str(), newname.c_str()) != 0) { P.S. I recommend using std::filesystem::rename instead since it has better ways of handling errors in my opinion.
70,263,094
70,263,306
How to implement parts of member functions of a Class in a static library while the rest functions implemented in a cpp file?
I have a C++ Class A like this: // in header file A.h class A { public: void foo1(); void foo2(); private: double m_a; }; // in cpp file A1.cpp void A::foo1(){ m_a = 0; //do something with m_a } // in cpp file A2.cpp void A::foo2(){ foo1(); // call foo1 } // in cpp file main.cpp int main(){ A obj; obj.foo2(); return 0; } In my occasion, the function foo1 and foo2 are implemented by two different people. For some reasons, I need to hide the implementation of foo1 so that the people who code A2.cpp cannot fetch the source code of foo1, and at the same time he can use Class A in his own application (like main.cpp above). I tried to archive A1.cpp as a static library, and of course, an 'unresolved external symbol' error for foo2 occurred. I built my static library using CMake plugins in Visual Studio 2019, and my CMakeLists.txt is like: add_library (my_lib STATIC A1.cpp) target_include_directories(my_lib PUBLIC path/to/A.h) Is there any solution or workaround for this issue?
You can compile A1.cpp without linking, which will give you a compiled object file, A1.o. You can hand this off, so the developers for A2.cpp won't be able to see the source, but will be able to link your object file to build the final project. With g++, that could look like: A.h class A { public: void foo1(); void foo2(); private: double m_a; }; A1.cpp #include "A.h" #include <iostream> void A::foo1() { std::cout << "foo1 called!" << std::endl; m_a = 72; } A2.cpp #include "A.h" #include <iostream> void A::foo2() { std::cout << "foo2 called!" << std::endl; foo1(); } main.cpp #include "A.h" int main() { A a; a.foo2(); } Building the project If you're using g++, then... g++ -c A1.cpp This will compile but not link A1.cpp, giving you the object file A1.o. You can hand that file off so that the other developers can build the whole project with g++ main.cpp A1.o A2.cpp
70,263,143
70,263,224
Unexpected default constructor call when using move semantics
I have two similar pieces of code. The first version unexpectedly calls the default constructor while the second doesn't. They both call the move operator / move constructor, respectively, as expected. class MyResource { public: MyResource() : m_data(0) { std::cout << "Default Ctor" << std::endl; } MyResource(int data) : m_data(data) { std::cout << "Int Ctor" << std::endl; } MyResource(MyResource const& other) = delete; MyResource& operator=(MyResource const& other) = delete; MyResource(MyResource&& other) noexcept : m_data(other.m_data) { std::cout << "Move Ctor" << std::endl; } MyResource& operator=(MyResource&& other) noexcept { std::cout << "Move Op" << std::endl; m_data = other.m_data; return *this; } ~MyResource() { std::cout << "Dtor" << std::endl; } private: int m_data = 0; }; class MyWrapper { public: MyWrapper(MyResource&& resource) // : m_resource(std::move(resource)) // Version 2 { // m_resource = std::move(resource); // Version 1 } private: MyResource m_resource; }; My test usage is: MyWrapper* wrapper = new MyWrapper(MyResource(1)); delete wrapper; With Version 1, I get: Int Ctor Default Ctor Move Op Dtor Dtor While Version 2 outputs: Int Ctor Move Ctor Dtor Dtor What's the reason behind this difference? Why does version 1 call the default constructor?
Members are initialized before the construct body runs. A much simpler example to see the same: #include <iostream> struct foo { foo(int) { std::cout << "ctr\n";} foo() { std::cout << "default ctr\n";} void operator=(const foo&) { std::cout << "assignment\n"; } }; struct bar { foo f; bar(int) : f(1) {} bar() { f = foo(); } }; int main() { bar b; std::cout << "---------\n"; bar c(1); } Output: default ctr default ctr assignment --------- ctr You cannot initialize a member in the body of the constructor! If you do not provide an initializer, either in the member initializer list or as an in class initializer, then f is default constructed. In the constructor body you can only assign to an already initialized member.
70,263,212
70,264,443
How do I input random numbers in C++ array?
#include <iostream> #include <ctime> using namespace std; int randBetween() { unsigned seed = time(0); srand(seed); const int MIN_VALUE = -100; const int MAX_VALUE = 100; return (rand() % (MAX_VALUE - MIN_VALUE + 1 )) + MIN_VALUE; } int main() { const int SIZE = 10; int myArray[SIZE]; // ^^ how do I use function above to give myArray random values? return 0; } I wanna use that rand function to give my array random values from -100 to 100 but I dont know how to put that rand function in the array so that my array can generate random number inside it hopefully that makes sense how do I do that?
First we'll take a look at your code and critique it. #include <iostream> #include <ctime> // MISSING <cstdlib> for C random functions using namespace std; // Bad Practice int randBetween() { unsigned seed = time(0); // Wrong placement; should only instantiate ONCE srand(seed); const int MIN_VALUE = -100; const int MAX_VALUE = 100; return (rand() % (MAX_VALUE - MIN_VALUE + 1 )) + MIN_VALUE; // Modulo math tends to make the values in the lower end of the range more prevalent; i.e., // it's not very uniform. } int main() { const int SIZE = 10; // All caps names for constants is not desirable; they can be confused for macros int myArray[SIZE]; // Prefer std::array if the size is known, else std::vector for most cases // ^^ how do I use function above to give myArray random values? return 0; } The biggest issue is the use of C-style conventions when C++ provides better methods. In fact, you won't even need a function for this. The secret sauce of getting the random numbers into your array is a loop. Make your loop visit every element and assign a new random number. Either directly, as in my first example, or by using a function as in my second example. #include <array> #include <iostream> #include <random> int main() { const int minValue = -100; const int maxValue = 100; const int size = 10; std::array<int, size> myArray; // std::mt19937 is the goto PRNG in <random> // This declaration also seeds the PRNG using std::random_device // A std::uniform_int_distribution is exactly what it sounds like // Every number in the range is equally likely to occur. std::mt19937 prng(std::random_device{}()); std::uniform_int_distribution<int> dist(minValue, maxValue); for (auto& i : myArray) { i = dist(prng); } for (auto i : myArray) { std::cout << i << ' '; } std::cout << '\n'; } Now, if you want or need the function, there's a little bit of extra work that needs to be done. #include <array> #include <iostream> #include <random> int randBetween() { const int minValue = -100; const int maxValue = 100; // The keyword static is required now so that the PRNG and distribution // are not re-instantiated every time the function is called. This is // important for them both to work as intended. Re-instantiating resets // their state, and they constantly start from scratch. They must be allowed // to persist their state for better results. static std::mt19937 prng(std::random_device{}()); // Note the static static std::uniform_int_distribution<int> dist(minValue, maxValue); return dist(prng); } int main() { const int size = 10; std::array<int, size> myArray; for (auto& i : myArray) { i = randBetween(); } for (auto i : myArray) { std::cout << i << ' '; } std::cout << '\n'; } Separating the PRNG from the distribution is good practice, especially when programs get larger. Then your single PRNG can feed multiple distributions if needed. One output that I got: -2 -37 81 85 -38 -62 31 -15 -12 -31
70,263,658
70,403,129
Lambda in return statement cannot be implicitly converted to functor
I have the following code struct Functor { Functor(std::function<void()> task) : _task {task} {} void operator() () {_task();} std::function<void()> _task{}; }; Functor run1() //OK { return Functor([](){std::cout << "From function" << std::endl;}); } Functor run2() //Bad. Compile time error { return [](){std::cout << "From function" << std::endl;}; } My questions are: Why run1() is okay but run2() is not allowed? Is there a constructor in the struct Functor that I can define in order to make run2() valid as it is? I am asking this because currently the return type of run2() in my project is std::function<void()> and all is good, but I now need to change it into a functor to store some additional properties, but return statement like run2() are used in many places, and I am reluctant to modify every occurrences of it into run1().
As it is already mentioned in the comments, run2 requires two implicit user conversions, which is prohibited. You can create a template constructor in Functor to make your code valid: #include <functional> #include <iostream> struct Functor { Functor(auto && task) : _task { task } {} void operator() () {_task();} std::function<void()> _task{}; }; Functor run1() //OK { return Functor([](){std::cout << "From function" << std::endl;}); } Functor run2() //Ok { return [](){std::cout << "From function" << std::endl;}; } Demo: https://gcc.godbolt.org/z/bdnYTbKv4
70,263,686
70,263,929
How to load into __m256 from a float* but reading backwards in memory as opposed to forwards?
I've got an array of floats that I'd like to access in reverse order. In my non-vectorized code this is easy. Here is a simplifed version of the data that I have. float A[8] = {a, b, c, d, e, f, g, h}; float B[8] = {s, t, u, v, w, x, y, z}; Here is the operation I would like to do. float C[8] = {a*z, b*y, c*x, d*w, e*v, f*u, g*t, h*s}; I'd like to be able to do some kind of load_ps operation that will give me something like this: __m256 A_Loaded = _mm256_load_ps(&A[0]); = {a, b, c, d, e, f, g, h}; __m256 B_LoadedReversed = _mm256_loadr_ps(&B[7]); = {z, y, x, w, v, u, t, s}; __m256 Output = _mm256_mul_ps(A_Loaded, B_LoadedReversed); = {a*z, b*y, c*x, d*w, e*v, f*u, g*t, h*s}; One of the data sources I have is a lookup table, so could be reversed if push comes to shove, but would much prefer to avoid that as that would compilcate other areas of the program. I've currently got a botch workaround using _mm256_set_ps() and manually pointing to the data I need, but that is not as performative as I would like. I know there is a 'reversed' _mm256_set_ps() (_mm256_setr_ps()), but there doesn't seem to be the _mm256_loadr_ps() that I need. Any ideas and thoughts about this problem would be greatly appreciated! Thanks in advance.
You can reverse the order inside a __m256 in two steps, using _mm256_permute_ps and _mm_256_permute2f128_ps. _mm256_permute_ps allows you to permute within each "lane", the high and low 128-bit chunks. _mm_256_permute2f128_ps allows you to permute 128-bit chunks across lanes. It's something like this: __m256 b = _mm256_loadr_ps(&B[0]); b = _mm256_permute_ps(b, _MM_SHUFFLE(3, 2, 1, 0)); b = _mm256_permute2f128_ps(b, b, 1); These instructions are documented in the Intel intrinsics guide: https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html How does setr_ps work? How does setr_ps() reverse things? It just reverses the arguments. Here's the version I pulled from my GCC installation: extern __inline __m256 __attribute__((__gnu_inline__, __always_inline__, __artificial__)) _mm256_setr_ps (float __A, float __B, float __C, float __D, float __E, float __F, float __G, float __H) { return _mm256_set_ps (__H, __G, __F, __E, __D, __C, __B, __A); } You can see, setr_ps() does not correspond to any underlying processor capability, it just reorders the arguments.
70,263,892
70,285,486
How to compile C++ app for Windows XP in MSVS?
As I read this article, it is enough to download most recent MSVS 2022 and then install toolset C++ Windows XP Support for VS 2017 (v141) tools [Deprecated]. After that in Visual Studio inside project properties I set this toolset. According to linked article it is enough to compile C++ app with XP support. But after my .exe file is created if I run it on XP 64-bit SP2 then it shows error that CompareStringEx function is not found in KERNEL32.DLL. Hence it appears that it is not enough to use this toolset. Something else is needed. In some other places I see that one needs also to add define /D_USING_V110_SDK71_ when compiling and option /SUBSYSTEM:CONSOLE,5.01 when linking. In my project properties I also tried to add this two options, but still CompareStringEx is inside import table of final application. As suggested by @BenVoigt, I did defines /DWINVER=0x0502 /D_WIN32_WINNT=0x0502. Also set C++ standard to /std:c++14 (I would set C++11 but this MSVS version allows to set only C++14 at minimum). Still some non-XP symbols remain in final EXE like InitializeSRWLock that is possibly used by C++11's std::mutex in my code. Does anyone know everything what is needed in order to compile fully XP-compatible application? Update. I managed to build working XP application by doing things above plus setting C++ CRT runtime to Multi Threaded DLL, i.e. using dynamic DLL linkage of CRT. Also as suggested by @ChuckWalbourn (down x86 or x64 redists), I downloaded older version of msvcp140.dll. But it is very important for my project to have statically linked runtime (C++ CRT), i.e. use Multi Threaded value for Runtime field in project properties. Only if it is REALLY not possible only then I will use DLL CRT. Until then solution about how to link CRT statically are welcome, of course to produce XP-compatible EXE.
TL;DR For Window XP VC++ REDIST support, install https://aka.ms/vs/15/release/VC_redist.x86.exe on your Windows XP system -or- if you are doing "side-by-side application local deployment", then use the DLLs from C:\Program Files\Microsoft Visual Studio\2022\<edition>\VC\Redist\MSVC\14.16.27012\x86\Microsoft.VC141.CRT. If you want the latest bug fixes to the CRT, you can also download the REDIST for VS 2019 (16.7) per the link on Microsoft Docs. For Windows XP targeting, you use the v141_xp Platform Toolset installed by Visual Studio (VS 2017, VS 2019, or VS 2022) which is the latest VS 2017 (v141) C++ compiler using an included Windows 7.1A SDK. Make sure you have installed (for VS 2022) the following individual components since you are using MFC: Microsoft.VisualStudio.Component.WinXP: C++ Windows XP Support for VS 2017 (v141) tools [Deprecated] Microsoft.VisualStudio.Component.VC.v141.x86.x64: MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16) Microsoft.VisualStudio.Component.VC.v141.MFC: C++ MFC for v141 build tools (x86 & x64) If you are doing DirectX development, be sure to read this blog post as well for various implications of using the Windows 7.1A SDK. For deployment to Windows XP, you can install the latest VS 2017 Visual C++ REDIST or use VS 2019 Visual C++ up to VS 2019 (16.7). After that the REDIST DLLs themselves are not compatible with Windows XP. On your development system with VS 2022 installed, you are going to have a newer set of Visual C++ REDIST files which are binary compatible with your v141_xp Platform Toolset built EXE, but those VC++ REDIST DLLs are not compatible with Windows XP. IOW: If you look at a dumpbin /imports of the 14.30 (v143 version), 14.29 (v142 latest version), and/or 14.16 (v141 latest version ) copies of msvcp140.dll you will see different imports. The msvcp140.dll sitting in your C:\windows\SysWOW64 folder is going to be the 14.30 version.
70,263,965
70,264,043
Can C++ concepts operate on overload sets?
C++ has an obnoxious limitation that it is impossible to pass overloaded functions to templates, for example std::max can not be nicely used with std::transform. I was thinking that it would be nice if concepts could solve this, but in my attempts I hit the same issue. It looks like concepts are not able to constrain the template based on predicate on function type. Example: #include <type_traits> #include <iostream> #include <boost/callable_traits/args.hpp> namespace ct = boost::callable_traits; template <typename Fn> concept Fn1 = std::tuple_size<ct::args_t<Fn>>::value == 1; template <typename Fn> concept Fn2 = std::tuple_size<ct::args_t<Fn>>::value == 2; template<Fn1 Fn> auto make(Fn f){ return 1; } template<Fn2 Fn> auto make(Fn f){ return 2; } auto fn(int a){ } auto fn(int a, float b){ return 2; } int main() { std::cout << make(fn) << std::endl; std::cout << make(fn) << std::endl; } notes: I know about different solutions to this problem, this is just an example problem to ask specifically if this can be done with concepts. I know that just dispatching on arity is primitive, e.g. predicate should also return bool, etc.
In order for the language to consider whether a type fulfills a concept, C++ must first deduce the type of the argument and plug it into the template function. That deduction cannot happen because the argument is a name representing a function with multiple overloads. So concepts don't even get a chance to work. So long as an expression consisting of the name of an overloaded function cannot undergo template argument deduction, what you're trying to do cannot work. And even if it did work, it still wouldn't work. In this hypothetical, fn fulfills both concepts. And while overloading based on concepts is a thing, it's a thing based on comparing the atomic constraints to look for similarities to see which is more constrained. But their atomic constraints are unrelated (as far as C++ is concerned). Thus, both would be considered equally as valid, and therefore concept overloading would fail. You're just going to have to do what everyone else does: create a lambda.
70,263,985
70,264,048
Strange error in C++ without stoping the program
When I change the value that I pass to my array I receive strange error which doesn't stop the program but it always appears so I'm curious why. I give you my code below: My error is something like: In function 'int numOfDifferentElements(BSTree*, int)': control reaches end of non-void function [-Wreturn-type] ( main.cpp:97:1 ) and there is an arrow pointing to: } #include <iostream> using namespace std; struct BSTree { int val; BSTree* up; BSTree* right; BSTree* left; }; void AddBstNode(BSTree* &root, int valToAdd) { { BSTree* pom; BSTree* nodeToAdd = new BSTree; nodeToAdd->val = valToAdd; nodeToAdd->left = NULL; nodeToAdd->right = NULL; nodeToAdd->up = NULL; if (root == NULL) { root = nodeToAdd; } else { pom = root; while (1) { if (nodeToAdd->val < pom->val) if (pom->left == NULL) { pom->left = nodeToAdd; break; } else pom = pom->left; else if(nodeToAdd->val > pom->val) { if (pom->right == NULL) { pom->right = nodeToAdd; break; } else pom = pom->right; } else // gdy wartosc jest rowna to jej nie dodajemy do drzewka aby potem mozna bylo zliczyc el drzewa // a kazdy z nich bedzie inny { break; } } nodeToAdd->up = pom; } } } int numOfDifferentElements(BSTree* root, int counter) { if (root) { counter++; numOfDifferentElements(root->left, counter); numOfDifferentElements(root->right, counter); } else { return counter; } } void judgeArray(int array[], int x) { BSTree* pom = NULL; int lengthOfArray = *(&array +1 ) - array; // rozmiar naszej tablicy for(int i = 0; i < lengthOfArray; i++) { AddBstNode(pom, array[i]); // tworzymy drzewo z elementow naszej tablicy } int counter = 0; int judge = numOfDifferentElements(pom, counter); // zliczamy liczbe el drzewa, bez zadnych zalozen, bo //wszystkie jego elementy sa rozne co zostalo zapewnione w funkcji AddBstNode ( kom. w linii 76 i 77) if(judge == x) { cout<<"Array is good"<<endl; } else if(judge < x) { cout<<"Array is wrong"<<endl; } else if(judge > x) { cout<<"Array is mediocre"<<endl; } // powyzej nasze zalozenia, jesli liczba roznych el jest mniejsza/wieksza/rowna od naszego zalozonego x ( liczby //roznych elementow) to tak oceniamy nasza tablice } int main() { int N[16] = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8}; // przykladowa tablica int x = 12; // przykladowa wart x judgeArray(N, x); // wywolanie naszej funkcji z przykladowa wartoscia return 0; }
The problem is that in your numOfDifferentElements function, if the if condition is satisified then there is no return statement. The problem is because the return type of the function is non-void and so you must return something. You can solve this by adding a return statement inside the if block or outside(after) the else block as shown below: int numOfDifferentElements(BSTree* root, int counter) { if (root) { counter++; numOfDifferentElements(root->left, counter); numOfDifferentElements(root->right, counter); //can also add a return statement here } else { return counter; } //or add return -1; or some other value indicating ERROR CODE }
70,264,034
70,264,528
How to create array of classes containing a constructor with reference argument?
I have the piece of code hereunder which gives me the following errors: test.cpp:15:38: error: could not convert ‘std::ref<boost::asio::io_context>(((container*)this)->container::ioCtxt)’ from ‘std::reference_wrapper<boost::asio::io_context>’ to ‘A’ 15 | std::array<A,2> bObjs = {std::ref(this->ioCtxt), nullptr}; | ~~~~~~~~^~~~~~~~~~~~~~ | | | std::reference_wrapper<boost::asio::io_context> test.cpp:15:61: error: could not convert ‘nullptr’ from ‘std::nullptr_t’ to ‘A’ 15 | std::array<A,2> bObjs = {std::ref(this->ioCtxt), nullptr}; | ^ | | | This is the minimal piece of code which creates the error in question. This minimal piece of code is a simplistic representation of a more complex situation. #include <boost/asio.hpp> struct A { boost::asio::ip::tcp::socket sock; A(boost::asio::io_context& ioCtxtFromContainer): sock(ioCtxtFromContainer){} }; struct container { boost::asio::io_service ioCtxt; std::array<A,2> bObjs = {std::ref(this->ioCtxt), nullptr}; }; int main(void) { container containerObj; return 0; } What is the correct way of passing a reference to A's constructor? Using vectors or an other form of dynamic memory allocation is not allowed/possible here.
Conmpiler can't do implicit conversion via initializer list: #include <functional> #include <array> struct from{}; struct a { a(from&){} }; int main() { from arg{}; // std::array<a, 1> ar{std::ref(arg)}; // can't deduce from initializer list std::array<a, 1> ar{ arg }; // alright std::array<a, 1> ar2{ a(arg) }; // also alright } How do you expect to initialize from a Pointer something, that takes a reference? A(boost::asio::io_context& ioCtxtFromContainer): You store an array of objects, not an array of pointers. So, either provide a constructor for A which takes a pointer (which is not what you pbviously want), or have an array of pointers: std::array<A*, 2> (using smart pointers preferrably). Or you can use std::optional, like alanger has suggested. You can wrapp your initializer list for your array with a variadic template: template <typename ... Args> std::array<a, sizeof...(Args)> init_array(Args &&... args) { return {a(std::forward<Args>(args))...}; } from arg{}; auto ar3 = init_array(arg, std::ref(arg)); // works
70,264,324
70,278,417
Image Magick++ close .display() Popup window by command
in documentation of Magick++ I found the command to display an image Image temp_image(my_image);temp_image.display(); // display 'my_image' in a pop-up window this works quite well, but I can find a command to close this window by code. My goal is to open a window with the image, give image new name by commandline input, then automatically close the window, and show next image to rename. Although the new popup-window sets the "active window" to it's self. For entering some input to command line (e.g. new_name), I have to click again at the terminal window. My (pseudo)code at the moment: for(all_images){temp_image.display(); renaming_method();} just now I have to close the upcoming window manualy by hand, better would be something like for(all_images){temp_image.display(); renaming_method(); temp_image.display_close();} do you have any ideas how to do this?
Magick++, and ImageMagick, doesn't have any methods to manage active display windows. You can roll your own XWindow method, but most projects I've seen just do the following routine... Write temporary image Ask OS to open temporary file by forking a process & calling xdg-open, open, or start commands (depending on OS). Send SIGINT to pid when user wishes to close child process. Clean-up any resources Not ideal, but will get you roughly there.
70,264,455
70,266,823
How do I make child processes in Win32 so that they show up as nested in Task Manager?
I have a Win32 C++ application. I'm trying to launch one or several child processes with CreateProcess. I want the children to close when the parent does. I achieved this by creating a job and enabling JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: HANDLE hJob = CreateJobObject(NULL, NULL); JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo; ZeroMemory(&extendedInfo, sizeof(extendedInfo)); extendedInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; SetInformationJobObject( hJob, JOBOBJECTINFOCLASS::JobObjectExtendedLimitInformation, &extendedInfo, sizeof(extendedInfo)); Then adding the current (parent) and created (child) process to this job: // assign parent to job AssignProcessToJobObject(hJob, GetCurrentProcess()); // launch child with no inherited handles PROCESS_INFORMATION procInfo; ZeroMemory(&procInfo, sizeof(procInfo)); STARTUPINFOA startInfo; ZeroMemory(&startInfo, sizeof(startInfo)); startInfo.cb = sizeof(startInfo); startInfo.dwFlags |= STARTF_USESTDHANDLES; bool success = CreateProcessA(NULL, "test.exe", // command line NULL, // process security attributes NULL, // primary thread security attributes FALSE, // handles are inherited 0, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &startInfo, // STARTUPINFO pointer &procInfo); // receives PROCESS_INFORMATION // assign child to job AssignProcessToJobObject(hJob, procInfo.hProcess); This works, but the parent app and the child app (main.exe and test.exe) show up as two unrelated processes in the task manager: (Even though closing main.exe will close test.exe). What am I doing differently than, say, Microsoft Teams or Chrome, which both have nested processes?
Exactly what Task manager is doing is not documented. In Windows 8 it does not group child processes, it only organizes based on a process having a window or by being "special". How does Task Manager categorize processes as App, Background Process, or Windows Process?: These are terms that Task Manager simply made up. The system itself doesn’t really care what kind of processes they are. If the process has a visible window, then Task Manager calls it an “App”. If the process is marked as critical, then Task Manager calls it a “Windows Process”. Otherwise, Task Manager calls it a “Background Process”. (I don't believe this is 100% accurate, it clearly knows about services and I suspect it might hard-code some names) In Windows 10 it tries harder to group things together but I don't exactly know what it is doing. It is often (but not always) able to tie the conhost.exe child to its parent console application. The new fancy store/packaged versions of Notepad and Paint have all their processes in a single group. The same does not happen with Notepad2 even though it has a Application Model ID set. Neither does it apply to Wordpad (even when one is a child of the other). I also tried setting an AMUI in a little test application and neither process wide AMUI nor per-HWND AMUI seems to trigger the grouping. A job object does not seem to enable grouping. Depending on your version, Edge might use a special API to tell Task manager about its processes. In conclusion, I don't know what exactly what it is looking for but Packaged applications and App Containers seem to often trigger it.
70,264,522
70,264,662
uninitialized local variable used c++
Why can't I initialize the integer variable num with the value of the number field of the Strct structure? #include <iostream> struct Strct { float number = 16.0f; }; int main() { Strct* strct; int num = strct->number; return 0; } Error List: C4700 uninitialized local variable 'strct' used
Why can't I initialize the integer variable num with the value of the number field of the Strct structure? Because the pointer is uninitialised, and thus it doesn't point to any object. Indirecting through the pointer, or even reading the value of the pointer result in undefined behaviour. I thought my strct points to the Strct structure, that is, to its type No. Pointers don't point to types. Object pointers point to objects. Types are not objects in C++. 16.0f is not the value of number. 16.0f is the default member initialiser of that member. If you create an object of type Strct, and you don't provide an initialiser for that member, then the default member initialiser will be used to initialise the member of the object in question. then can I define a member function that returns the address of this structure? A structure is a type. A type isn't stored in an address. There is no such thing as "address of a type". Here is an example of how to create a variable that names an instance of the class Strct: Strct strct; You can access the member of this variable using the member access operator: int num = strct.number; Here is an example of how to create an instance that doesn't use the default member initialiser: Strct strct = { .number = 4.2f, };
70,264,696
70,272,004
Why is the data parsed by pugixml lost in another function?
I have 2 functions: void XMLParser::ParseScene(const char* path) { // Load the XML file pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(path); scene = doc.child("scene"); } and void XMLParser::CreateModelLights(pugi::xml_node node) { GLuint i = 0; for (pugi::xml_node entity : node.children()) { [...] } } I am calling parser.ParseScene("src/xml/scene.xml"); to generate parser.scene and then call parser.CreateModelLights(parser.scene);, but it gives me rubbish data in node parameter / parser.scene. If I put scene = doc.child("scene"); on CreateModelLight() first line it will parse my data ok in parser.scene, but I don't want to force the node like that because I am calling the function recursively. Ideally I want to parse my XML in ParseScene() and then store it a pugi::xml_node variable declared in the header that I can use in functions like CreateModelLights(). XML looks like this: <?xml version="1.0" encoding="UTF-8"?> <scene> [...] </scene> Rubbish data I get: Data I should get:
This is not terribly clear in the documentation, but PugiXML uses a fairly common memory management pattern: The pugi::xml_document owns the entire XML DOM tree, and pugi::xml_node objects are just shallow pointers into this tree. This means that you need to keep the pugi::xml_document object alive for as long as there are pugi::xml_node objects pointing into it. Probably the quickest way is to promote doc to a member variable.
70,264,739
70,264,809
C++ printf("%s" , string) is giving me very strange output
I am trying to use printf to give my strings color with something like printf("\x1B[92m%d\033[0m", value1); which works for me with integers no problem, but when I try to do something like printf("\x1B[92m%s\033[0m", wantedString); I get random things like, (°√, any help pls? Here is the whole function void searchFileFor(path const& files, string wantedString) { ifstream inFile; string currentString; int lineNumber = 0; bool foundNothing = true; for (auto file : recursive_directory_iterator(files)) { lineNumber = 0; // Reset after each new file inFile.open(file); while (inFile >> currentString) { lineNumber++; if (currentString.find(wantedString) != string::npos) { cout << file << " " << wantedString << " " << lineNumber << '\n'; foundNothing = false; } //cout << file << " " << currentString << endl; } inFile.close(); } if (foundNothing == true) { cout << "We were not able to find: " << wantedString << ""; printf("\x1B[92m%s\033[0m", wantedString); } //cout << "Wanted String: " << wantedString; }
For printf you need a c-style string. Use wantedString.c_str().
70,264,942
70,265,295
_itoa_s doesn't accept dynamic array
I am new to C++ and dynamic memory allocation. I have this code to convert a number from decimal to hexadecimal, that uses a dynamic array: int hexLen = value.length(); char* arrayPtr = new char[hexLen]; _itoa_s(stoi(dec), arrayPtr, 16); string hexVal = static_cast<string>(arrayPtr); delete[] charArrayptr; When I used an array with a fixed size, _itoa_s() worked with it. However, when using a dynamic array, the compiler says that a method with the arguments given doesn't exist. Is this something that I did wrong, or will _itoa_s() simply not work with a dynamic array? Version with non-dynamic array (that works): const int LENGTH = 20; char hexCharArray[LENGTH]; _itoa_s(stoi(dec), hexCharArray, 16);
If you read the documentation carefully, you would see that you are trying to call the template overload of _itoa_s() that takes in a reference to a fixed-sized array: template <size_t size> errno_t _itoa_s( int value, char (&buffer)[size], int radix ); You would need to instead call the non-template overload that takes in a pointer and a size: errno_t _itoa_s( int value, char * buffer, size_t size, int radix ); Try this: int decValue = stoi(dec); int hexLen = value.length(); int arraySize = hexLen + 1; // +1 for null terminator! char* arrayPtr = new char[arraySize]; errno_t errCode = _itoa_s(decValue, arrayPtr, arraySize, 16); if (errCode != 0) { // error handling... } else { string hexVal = arrayPtr; // use hexVal as needed... } delete[] charArrayptr; Since you are trying to get the hex into a string, you can do away with the char* altogether: int decValue = stoi(dec); string hexVal; hexVal.resize(value.length()); errno_t errCode = _itoa_s(decValue, &hexVal[0], hexVal.size()+1, 16); if (errCode != 0) { // error handling... } else { hexVal.resize(strlen(hexVal.c_str())); // truncate any unused portion // use hexVal as needed... }
70,265,092
70,272,131
Template argument deduction/substitution failed with Boost Hana type_c
I do not understand why the following simple example fails: #include <boost/hana.hpp> template <typename _T> static constexpr void Foo(boost::hana::type<_T>) { } int main() { Foo(boost::hana::type_c<int>); return 0; } I get the following error message: [build] error: no matching function for call to ‘Foo(boost::hana::type<int>&)’ [build] 74 | Foo(hana::type_c<int>); [build] | ~~~^~~~~~~~~~~~~~~~~~~ [build] note: candidate: ‘template<class _T> constexpr void Morphy::Foo(boost::hana::type<T>)’ [build] 61 | static constexpr void Foo(hana::type<_T>) { [build] | ^~~ [build] note: template argument deduction/substitution failed: [build] note: couldn’t deduce template parameter ‘_T’ [build] 74 | Foo(hana::type_c<int>); [build] | ~~~^~~~~~~~~~~~~~~~~~~ The only way to make the above work is by making explicit the template argument of Foo by writing Foo<int>(boost::hana::type_c<int>). Why is the compiler unable to automatically deduce the template argument? Notice that the above code works if I use boost::hana::basic_type in place of boost::hana::type in the declaration of Foo. Is this alternative approach correct?
type_c<int> is a variable template that creates a value of type type<int>. It indeed seems like Foo should easily deduce parameter _T from type<_T> when passing type<int>. However it is not possible because type is an alias template that refers to member of some auxiliary class and its parameter is always in non-deduced context. template< typename x_Type > struct FooImpl { using Type = x_Type; }; template< typename x_Type > using Foo = typename FooImpl<x_Type>::Type; template< typename x_Type > // x_Type can not be deduced void Bar(Foo<x_Type>) {} int main() { Bar(Foo<int>{}); return 0; } online compiler basic_type works because it is an actual type of type_c.