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
73,242,648
73,243,333
Optimize the printing of the results of a recursive function
I have the following function, used to print shortest path from source to j void printPath(int parent[], int j) { // base case, i.e. if j is the source if (parent[j] == -1) return; printPath(parent, parent[j]); cout << j+1 << "-"; } It prints results like 1-3-5-6-. How can I change the code to not print the last -? The goal is to get the result 1-3-5-6.
Here is one way: void printPath(int parent[], int j) { // base case, i.e. if j is the source if (parent[j] == -1) return; printPath(parent, parent[j]); if (parent[parent[j]] != -1) cout << "-"; cout << j+1; }
73,242,728
73,242,808
Why is this "expression" not modifiable?
I have a class called CircuitProfiler that has a public member function switchState. Below is the code for it: void CircuitProfiler::switchState(int index) { if (profilingNode) { switch (index) { case 0: node->getVoltage().isKnown = !node->getVoltage().isKnown; break; } } } The code I am having trouble with is the line: node->getVoltage().isKnown = !node->getVoltage().isKnown; I am getting error that says "expression must be a modifiable lvalue". There is a red line under node. node is a pointer to an instance of a Node class that I created. node a private data member of CircuitProfiler. It is declared in CircuitProfiler as Node* node; Node has a private data member called voltage, and getVoltage is a public member function of Node that simply returns voltage. voltage is declared in Node as VariableValue<float> voltage; and the code for getVoltage is: VariableValue<float> Node::getVoltage() { return voltage; } voltage is an instance of a simple struct called VariableValue, the code for which is below. template <class T> struct VariableValue { T value; bool isKnown; }; So why am I getting the error "expression must be a modifiable value"? Let me know if I need to provide any more information.
You are essentially saying (MCVE): struct S { int i; }; // S as VariableValue<float> S f() { return S{}; } // f as getVoltage f().i = 1; // i as isKnown You return a temporary in getVoltage(), which does not bind to an lvalue argument of operator=(). Likely you wanted to return voltage by reference in getVoltage(), if you wanted to use it this way, i.e., VariableValue<float>& Node::getVoltage() { return voltage; } You might also define a const version of it.
73,242,815
73,243,290
Can someone explain this While loop in a linked list to me?
I'm confused with this while loop statement while creating a linked list: while(curr->next != NULL) But curr->next will always be NULL since we never initialized curr->next to point to anything, so that while loop should never run! Can someone explain this, please?? The code snippet is as follows: if (head != NULL) { curr = head; while(curr->next != NULL) { curr = curr->next; } curr->next = n; } The complete code is shown below: void AddNode(int addData) { nodePtr n = new node; n->next = NULL; n->data = addData; if (head != NULL) { curr = head; while(curr->next != NULL) { curr = curr->next; } curr->next = n; } else { head = n; } }
curr->next is null only on the second call to AddNode. The first call to AddNode we go to the head = n; branch. On the second call, curr->next will be null and the while loop doesn't execute at all. But notice what happens after that, at the end of that second call. The curr->next = n; makes curr->next no longer null, appending n to this linked list. By the third call, curr->next is not null. The while loop iterates through the nodes with curr = curr->next until curr->next is null again (last node), then appends to that last node via curr->next = n;.
73,243,399
73,243,598
VMA how to tell the library to use the bigger of 2 heaps?
In my current system vulkan info returns these device specs: memoryHeaps[0]: size = 8589934592 (0x200000000) (8.00 GiB) budget = 7826571264 (0x1d2800000) (7.29 GiB) usage = 0 (0x00000000) (0.00 B) flags: count = 1 MEMORY_HEAP_DEVICE_LOCAL_BIT memoryHeaps[1]: size = 12453414912 (0x2e6480800) (11.60 GiB) budget = 12453414912 (0x2e6480800) (11.60 GiB) usage = 0 (0x00000000) (0.00 B) flags: None memoryHeaps[2]: size = 257949696 (0x0f600000) (246.00 MiB) budget = 251068416 (0x0ef70000) (239.44 MiB) usage = 6881280 (0x00690000) (6.56 MiB) flags: count = 1 MEMORY_HEAP_DEVICE_LOCAL_BIT In summary, heap 0 good, heap 2 bad. I am getting a message that massive texture I am allocating runs out of memory: Message: Validation Error: [ VUID-vkAllocateMemory-pAllocateInfo-01713 ] Object 0: handle = 0x5562fe1c6760, name = Logical device: NVIDIA GeForce GTX 1070, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0xe9a2b96f | vkAllocateMemory: attempting to allocate 268435456 bytes from heap 2,but size of that heap is only 257949696 bytes. The Vulkan spec states: pAllocateInfo->allocationSize must be less than or equal to VkPhysicalDeviceMemoryProperties::memoryHeaps[memindex].size where memindex = VkPhysicalDeviceMemoryProperties::memoryTypes[pAllocateInfo->memoryTypeIndex].heapIndex as returned by vkGetPhysicalDeviceMemoryProperties for the VkPhysicalDevice that device was created from (https://vulkan.lunarg.com/doc/view/1.3.211.0/linux/1.3-extensions/vkspec.html#VUID-vkAllocateMemory-pAllocateInfo-01713) Severity: VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT So I want to tell VMA to use heap 0, which does have enough capacity to hold my giga texture. I am trying to allocate like this: vk::Device& device = h_interface->GetDevice(); const bool is_3D_image = depth > 0; // Set image creation information. vk::ImageCreateInfo image_info = {}; image_info.imageType = is_3D_image ? vk::ImageType::e3D : vk::ImageType::e2D; image_info.format = format; image_info.extent = vk::Extent3D(width, height, max(uint32_t(1), depth)); image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = vk::SampleCountFlagBits::e1; image_info.tiling = tiling; image_info.usage = usage; image_info.sharingMode = vk::SharingMode::eExclusive; image_info.initialLayout = initial_layout; VmaAllocationCreateInfo allocation_info = {}; allocation_info.usage = VMA_MEMORY_USAGE_AUTO; uint32_t memoryTypeIndex = 0; allocation_info.memoryTypeBits = 0u << memoryTypeIndex; VmaAllocation allocation; vk::Image image; VkResult result = vmaCreateImage( vma_allocator, (VkImageCreateInfo*)&image_info, &allocation_info, (VkImage*)&image, &allocation, nullptr); I tried changing allocation_info.usage, I tried changing allocation_info.memoryTypeBits. I tried setting the device limits to 0 for all but the first heap when creating the VMA structure. I read this like 3 times: https://gpuopen-librariesandsdks.github.io/VulkanMemoryAllocator/html/choosing_memory_type.html I don;t understand how to tell VMA to please allocate from heap 0.
VMA's VmaAllocationCreateInfo structure has a member called memoryTypeBits. This allows you to supply a set of memory types from which VMA must select an allocation. So you can get the set of memory types from Vulkan and only specify those which use heap 0. That being said, the fact that this problem happened at all should make you reconsider VMA. Heap 2 is specifically for doing efficient streaming of data to the GPU from the CPU. This is easy enough to determine, as all of the memory types using it are host-visible. However, unless the image uses linear tiling, you cannot write to the bytes of an image directly. Therefore, VMA has no business whatsoever using a host-visible memory type when other memory types that aren't host-visible are available (unless one of your other flags requires it). If the image was not linearly tiled, and you didn't tell VMA to make sure the memory was host-visible, its algorithm has a flaw that should make you reconsider using it going forward.
73,243,736
73,245,219
If I write a function pointer to use in BST template, can they take more than 1 object as argument?
I wrote a template for a binary search tree. I wish to overload the in-order traversal function. I can get it to work when the function pointer only takes in 1 object of class T. I would like it to use a function pointer that uses 2 integer values as well, so that I can pull the integers from outside the statement in main, then my function pointer will use those values to find an object in my BST. Is that possible? I'll show my code below. For example, here is a typical implementation using just the T object: template<class T> void BSTTemplate<T>::inOrder(Node<T>* p) const { if (p != nullptr) { inOrder(p->leftLink); cout << p->info << " "; inOrder(p->rightLink); } } template<class T> void BSTTemplate<T>::inOrderTraversal() const { inOrder(root); } When I activate this, my program spits out all the nodes in the BST in-order. Here is the same code, but with a function pointer: template<class T> void BSTTemplate<T>::inOrder(Node<T>* p, void (*visit) (T&)) const { if (p != nullptr) { inOrder(p->leftLink, *visit); (*visit) (p->info); inOrder(p->rightLink, *visit); } } template<class T> void BSTTemplate<T>::inOrderTraversal(void (*visit) (T&)) const { inOrder(root, *visit); } And now, in my main() I can run a statement such as: //assume tree exists Tree.inOrderTraversal(MyFunction); where MyFunction is a void function such that void MyFunction(MyObject& myObj) { //does something } The goal for me is that I want to use a function with my Tree such that it takes in 2 integers from 'outside'. (basically user input) I've tried something like this: //overloading inOrder template<class T> void BSTTemplate<T>::inOrder(Node<T>* p, void (*visit) (T&,int&,int&)) const { if (p != nullptr) { inOrder(p->leftLink, *visit); (*visit) (p->info); inOrder(p->rightLink, *visit); } } template<class T> void BSTTemplate<T>::inOrderWithInputs(void (*visit) (T&,int&,int&)) const { inOrder(root, *visit); } But when I try to call the traversal function in main() like this: Tree.inOrderWithInputs(MyFunction(*arguments*)); The parser expects the arguments of an object of type T, an int, and another int. Previously when the function was only void MyFunction(MyObject& myObj), I need only use the function name as an argument. With multiple arguments to MyFunction itself, I don't have an object to fill it in with. Ideally I want to do something like Tree.inOrderTraversal(MyFunction(input1,input2)); where inputs are integers acquired from the user. Then the function manipulates those values to create a key, then the key is used to search the tree in-order. Help me connect the dots please?
In C++ it is better to use std::function than old style function pointers. std::function is a template you instantiate by specifying the return value and arguments (as many as you need). It support passing a global function like you used in your code, as well as lambdas (you can also use a class method with std::bind). When you call inOrderTraversal you should supply the arguments for the function as additional parameters (instead of using something like MyFunction(input1,input2) which actually invokes the function and passes it's return value). See complete example: #include <functional> #include <iostream> template <typename T> class BSTTemplate { public: //---------------------vvvvvvvvvvvvv---------------------------- void inOrderWithInputs(std::function<void(T&, int&, int&)> visit, T& arg1, int& arg2, int& arg3) const // <--- the arguments for invoking the function { // Invoke the function with the arguments: visit(arg1, arg2, arg3); } }; void GlobalFunc(float& arg1, int& arg2, int& arg3) { std::cout << "exceuting GlobalFunc with args: " << arg1 << ", " << arg2 << ", " << arg3 << std::endl; } int main() { BSTTemplate<float> bst; float f{ 0 }; int i1{ 1 }; int i2{ 2 }; // Call with a global function: bst.inOrderWithInputs(GlobalFunc, f, i1, i2); // <--- the arguments for invoking the function // Call with a lambda: bst.inOrderWithInputs([](float& arg1, int& arg2, int& arg3) { std::cout << "exceuting lambda with args: " << arg1 << ", " << arg2 << ", " << arg3 << std::endl; }, f, i1, i2); // <--- the arguments for invoking the function return 0; } Output: exceuting GlobalFunc with args: 0, 1, 2 exceuting lambda with args: 0, 1, 2
73,244,049
73,249,650
How to move a unique_ptr without custom deleter to another unique_ptr with custom deleter?
#include <memory> #include <functional> #include <iostream> struct TestStruct { int a = 100; }; struct StructDeleter { void operator()(TestStruct *ptr) const { delete ptr; } }; std::unique_ptr<TestStruct, StructDeleter> MakeNewStruct() { std::unique_ptr<TestStruct> st(new TestStruct()); std::unique_ptr<TestStruct, StructDeleter> customDeleterSt(std::move(st)); std::cout << customDeleterSt->a << std::endl; return customDeleterSt; } int main() { auto a = MakeNewStruct(); std::cout << a->a << std::endl; return 0; } The above code can not be compiled, how to move st to customDeleterSt? I get a st unique_ptr from the st creation interface, and I use the custom deleter to hide the implementation of st from my users, so how to move a unique_ptr without custom deleter to a unique_tr with custom deleter? Thanks for any help!
As noted in the comments, the brute-force way is to have the source .release() to the constructor of the destination. However there is a much more elegant solution (imho): Add an implicit conversion from std::default_delete<TestStruct> to StructDeleter: struct StructDeleter { StructDeleter(std::default_delete<TestStruct>) {} // Add this void operator()(TestStruct *ptr) const { delete ptr; } }; Now the code works with the existing move construction syntax. Whether this is done via the converting constructor, or .release(), if StructDeleter can't (for whatever reasons) properly delete a pointer that std::default_delete handles, this will result in undefined behavior. It is only because StructDeleter calls delete ptr that either of these techniques works. As written, TestStruct does not need to be a complete type at the point of delete. However should TestStruct acquire a non-trivial destructor, you will also need to ensure that for any code that calls StructDeleter::operator()(TestStruct*), that TestStruct is a complete type, otherwise you're back into UB territory again. This assurance is one of the things that std::default_delete<TestStruct> does for you and that StructDeleter (as written) does not. If it is intended to keep ~TestStruct() trivial, it would be a good idea to add: static_assert(std::is_trivially_destructible<TestStruct>::value);
73,245,070
73,246,613
how to match this line "04.08.2022 22:09" with regular expression in cpp
I want to match "04.08.2022 22:09" with regex in c++. The code below doesn't work (doesn't match). //04.08.2022 22:09 if (std::regex_match(line, std::regex("^/d{2}./d{2}./d{4}.*/d/d:/d/d.*"))) { cout << line << "\n"; cin.get(); }
You need to use \d not /d to match digits. You can also use \s+ to match one or more whitespaces instead of .* which matches zero or more of any character. You should also escape the . characters that you want to match to not make it match any character. I also recommend using raw string literals when creating string literals with a lot of backslashes. Example: #include <iostream> #include <regex> #include <string> int main() { std::string line = "04.08.2022 22:09"; std::regex re(R"aw(^\d{2}\.\d{2}\.\d{4}\s+\d{2}:\d{2})aw"); if (std::regex_match(line, re)) { std::cout << line << '\n'; } } If the one-digit hours are not prepended with 0, you need to match the hour with \d{1,2} instead of \d{2}.
73,245,182
73,245,463
Why am I getting different results on my PC and an online compiler?
I compiled the following C++ program for array sorting on my PC using dev C++ 6.30 with TDM-GCC 9.2.0 compiler. I get the following (undesirable) output: 2 4 5 9 23 69 Now, by using an online compiler of programizer, I get the following (desired/expected) output: 2 4 5 9 23 88 This is the code: #include <iostream> using namespace std; int main() { int i, cnt, x; //int Arr[6]; int Arr[6] = {2, 9, 23, 88, 5, 4, }; for (cnt = 1; cnt < 6; cnt++) { for(i=0; i<6; i++) { if ( Arr[i] > Arr[i+1]) { x = Arr[i]; Arr[i] = Arr[i+1]; Arr[i+1] = x; } } } // Printing the sorted array for (int j=0; j<6; j++) cout << Arr[j] << "\t"; }
In fact, this sorting algorithm does not work, and also you have some mistakes in your array initialization. You did this when you tried to initialize your array: int Arr[6] = {2, 9, 23, 88, 5, 4, }; That , in the end of your array is not necessary. This is how it should be: int Arr[6] = {2, 9, 23, 88, 5, 4 }; You should also use this to sort your array: for (cnt = size - 1; cnt >= 0; cnt--) { for(i = 0; i < cnt; i++) { if ( Arr[i] > Arr[i+1]) { x = Arr[i]; Arr[i] = Arr[i+1]; Arr[i+1] = x; } } }
73,245,215
73,245,690
How to initialize recurring `std::unordered_map` via curly braces
I need to initialize a type implementing tree-like structure. Tree t1 = 1; Tree t2 = {{"a",t1},{"b",{{"x",2},{"y",4}}},{"c",5}}; So i defined structure which inherits from std::unordered_map. I had to wrap recurring Tree in smart pointer. //tree.h using std; struct Tree : unordered_map<string, unique_ptr<Tree>>{ int simple; Tree() = default; Tree(unsigned s): simple{s}{}; Tree(const initializer_list<pair<string, unique_ptr<Tree>>> & il): simple{s} { // does not compile, would not work anyway 'coz the pointer } }; I can't figure out how to specify the initializer list. there is something that might help: struct TreeV : vector<pair<string, TreeV>>{ ... TreeV(const vector<pair<string, TreeV>> & v) : vector<pair<string, TreeV>>(v){}; } vector<pair<string, TreeV>> t3 = {{"a",t1},{"b",{{"x",2},{"y",4}}},{"c",5}}; How can I catch recurrent curly braces structure in the 'initializer_list'? or How can I initialize recurring pattern of std::unordered_map from curly braces structure?
Remove the reference from the initializer list. You cannot pass rvalues while using non const references. Also remove the simple{s} from the member initializer list if s isn't even defined anywhere. Tree(std::initializer_list<std::pair<std::string, std::unique_ptr<Tree>>> il) {}; Then something like this would compile. Tree t = { { "one", std::make_unique<Tree>() }, { "two", std::unique_ptr<Tree>(new Tree({ // unique_ptr is used here because make_unique does not support initializer lists. { "three", std::make_unique<Tree>() }})) } }; But I would question the use of unique_ptr altogether, is there a particular reason for using them here? I assume the memory would be managed by the unordered_map anyways? Here's how it would look without the use of unique_ptr: // This would allow to use syntax that resembles your goal Tree(std::initializer_list<std::pair<std::string, Tree>> il) {}; ... Tree t = { { "one", {} }, { "two", { { "three", {} } } } };
73,245,406
73,245,580
Precision rounding problem with boost multiprecision
I want to multiply number 123456789.123456789 by 1000000000.0 and as a result of this operation I expect 123456789123456789 as int or float 123456789123456789.0, but I got: res: 123456789123456791.04328155517578125 int_res: 123456789123456791 Should I do it in other way ? #include <iostream> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> namespace bmp = boost::multiprecision; int main() { bmp::cpp_dec_float_100 scalar{1000000000.0}; bmp::cpp_dec_float_100 a{123456789.123456789}; bmp::cpp_dec_float_100 res = a * scalar; bmp::cpp_int int_res = res.convert_to<bmp::cpp_int>(); std::cout << " res: " << res.str() << std::endl; std::cout << "int_res: " << int_res.str() << std::endl; return 0; } Code: https://wandbox.org/permlink/xB8yBWuzzGvQugg7
See https://www.boost.org/doc/libs/1_79_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html. You are initialising a with a double literal. 123456789.123456789 can't be represented by a double so you get the closest approximation which is 123456789.12345679104328155517578125. If you want to initialise precisely use a string literal instead: bmp::cpp_dec_float_100 a{"123456789.123456789"};
73,245,575
73,304,280
add user include dir after standard include dir
when using -Idir1 flag to add include path, gcc search dir1 BEFORE system standard include dir, e.g: $ cpp -v /dev/null -I$HOME/glibc/include -o /dev/null gcc will search $HOME/glibc/include first,then the standard include dirs: /usr/lib/gcc/x86_64-linux-gnu/9/include /usr/local/include /usr/include/x86_64-linux-gnu /usr/include How to adjust include dir order, e.g: search standard include dir first, then the -Idir ? Thanks!
There might some solutions for this, but the comment that Dmytro Ovdiienko posted provided the answer: Did you try to use -idirafter key? See: gcc.gnu.org/onlinedocs/gcc/…
73,246,502
73,247,414
c++ unorderd_map insert fails for value_type with atomic<bool> member
class strategy { int id; std::atomic<bool> strategyStarted; int startTime; int endTime; void getStartTime() { return startTime; } void setStartTime(int sTime) { startTime = sTime; } }; class strategyImpl{ std::unordered_map<int, strategy> allStrategies; strategyImpl() { strategy newParams; newParams.id = 1; newParams.strategyStarted.store(false); newParams.startTime = 104500; newParams.endTime = 150500; allStrategies.insert(std::make_pair(newParams.id, newParams)); <--ERROR } }; The problem arises when I try to insert/insert_or_assign/emplace to the unordered map allStrategies. Below are all the tried methods and their specific compiler errors. allStrategies.insert(std::make_pair(newParams.id, newParams)); error: no matching function for call to ‘std::unordered_map<int, strategy>::insert(std::pair<int, strategy>)’ allStrategies.insert(std::pair<int, strategy>(newParams.id, newParams)); error: no matching function for call to ‘std::pair<int, strategy>::pair(int&, strategy&)’ allStrategies.insert(std::unordered_map<int, strategy>::value_type(newParams.id, newParams)); error: no matching function for call to ‘std::pair<const int, strategy>::pair(int&, strategy&)’ allStrategies.insert_or_assign(newParams.id, newParams); error: use of deleted function ‘strategy& strategy::operator=(const strategy&)’ allStrategies.emplace(newParams.id, newParams); error: no matching function for call to ‘std::pair<const int, strategy>::pair(int&, strategy&)’ I have tried all possible ways, but just am not able to insert into this unorderd_map. As far as I have read about these ways to add entries to a map, the value type is not required to have default constructor or copy constructor. Please help me insert key value pairs to this map. How to do it? Edit: Added the problem causing member to class definition (it was omitted for conciseness) The root cause seems to be the member atomic<bool> strategyStarted After removal of the member, insert(make_pair..) compiles fine. Do I really have to do it without the atomic type?
So the basic problem is that the compiler isn't able to generate the default copy constructor because of the std::atomic. So you must write one for yourself. E.g. class strategy { public: strategy() = default; strategy(const strategy& rhs) : id(rhs.id) , strategyStarted(rhs.strategyStarted.load()) , startTime(rhs.startTime) , endTime(rhs.endTime) { } strategy& operator=(const strategy& rhs); // to do int id; std::atomic<bool> strategyStarted; int startTime; int endTime; int getStartTime() { return startTime; } void setStartTime(int sTime) { startTime = sTime; } }; With that addition, all (or most) of your previous attempts should work. On the other hand you could write a move constructor, in which case try_emplace and similar will work. Whichever you choose you should also also add the corresponding assignment operator.
73,246,665
73,246,753
How Comparator Works Internally?
#include <iostream> #include<bits/stdc++.h> using namespace std; bool compare (int a, int b) { return a>b; } int main() { int arr[5]= {1,2,5,9,6}; sort (arr,arr+5, compare); for (auto i: arr) cout << i << " "; return 0; } The above code is sorted in descending order. I am completely blank on how it is working. I read articles but did not get a good explanation. Why compare is not followed by () while calling as we do with functions? How does the compare function get the value as we do not have passed any parameters? How do return true and false results in descending order sorting?
Because you are not calling it. You are passing the compare function to std::sort without calling it, so that std::sort can call it for you. It is called by std::sort (many times), and std::sort supplies the parameters from your array Again std::sort looks at the return value (true or false) and sorts the two numbers accordingly.
73,246,902
73,247,303
vs code intellisense broken with c++17 explicit template deduction
I have an issue with vs code intellisense for c++17. The following code runs perfectly fine, but vs code tells me it is wrong. It doesn't understand the explicit template deduction. The installed extensions can be seen on the left hand side of the image. I'm using vs Code in combination with wsl2. The same thing happenes when using vs code on an ubuntu server. Am i maybe missing an extension for c++17?
Thanks for the comments. I didn't know that i had to set the cppstandard in vs code to c++17 manually. Simply go to: File -> Preferences -> Settings, search for: cppstandard, set Cpp Standart to c++17
73,247,565
73,258,067
Undefined symbols for architecture arm64: "_glClear", referenced from: _main in main.cpp.o arm64 GLFW3
So i was build a GLFW program with cmake Everthing went fine Until i build it and make give me this error Undefined symbols for architecture arm64: "_glClear", referenced from: _main in main.cpp.o ld: symbol(s) not found for architecture arm64 I try with this command CMAKE_LINK_LIBRARY_SUFFIX And this link_directories Still not working i have no idea what's going on here. Edit: Here are my CMakeLists cmake_minimum_required(VERSION 3.20.0) project(TESTING) add_executable(${PROJECT_NAME} "main.cpp") set(CMAKE_LIBRARY_PATH "~/DEV/vcpkg/installed/arm64-osx") set(CMAKE_TOOLCHAIN_FILE "~/DEV/vcpkg/scripts/buildsystems/vcpkg.cmake") link_directories(~/DEV/vcpkg/installed/arm64-osx/lib) find_package(glfw3 CONFIG REQUIRED) target_link_libraries(${PROJECT_NAME} PRIVATE glfw)
ANSWER: So you need to add this line: "-framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo" in the CMAKELISTS on target_link_libraries Or you can use "-framework OpenGL" but if you use all the solution up there it will give you some warning. I don't know but if you don't see any warning I think I'm using vcpkg incorrectly And this Question is SOLVED
73,247,656
73,248,117
How to declare a compile-time constant list of different size lists in a constant header file?
Introduction Good day, I want to optimize my application and especially a constant header file. In order to do so, I define inline constexpr constants in order to avoid multiple copies of those variable in files they are included. And also to have compile-time constants. I want now to add a new inline constexpr variable/arrays and this complexifies the constant header files. I want a list/array of a certain fixed size containing lists/arrays, each of them of different sizes. Finally, I would like an easy way of using it and easy accessibility. Planned work In the following, I note CONST to denot that the CONST values are compile-time constants. I wanted to implement my constant lists/arrays, that are later needed to be contained in a parent list/array (all defined in the constant header file), as: inline constexpr std::array<CONST int, size1> first = { some CONST values }; inline constexpr std::array<CONST int, size2> second= { some other CONST values }; inline constexpr std::array<CONST int, size3> third = { some other CONST values }; Now, the idea is to access each array via a parent list for simplicity, if possible: CONTAINER parent = { first, second, third }; Problems Now I see problem arrising when I want to manipulate the arrays. Ideally, I would like the children (first, second and third) to behave as std::vector<int> and the parent as std::vector<std::vector<CONST int>*>. Because I could access first via a std::vector<CONST int>* pointer and I could change the pointed vector like the following: // Initialization std::vector<CONST int>* current_vec = nullptr; ... // First assignation current_vec = parent[0]; ... // Reassignation current_vec = parent[1]; ... But this implementation uses vector. With std::array, I think my pointer could not do the thing because it needs to know the size of each child arrays. Also, maybe I could do something with iterators but same problem (auto keyword might be a solution?). So, what I did for now is to use std::vector and define the child arrays as: inline const std::vector<int> first = { some CONST values }; inline const std::vector<int> second = { some other CONST values }; inline const std::vector<int> third = { some other CONST values }; And afterwards, I define the parent as: inline constexpr std::array<const std::vector<CONST int>*, 3> parent = {&first, &second, &third}; I can access the children like expected above: const std::vector<CONST int>* to_access = parent[0]; It seems to work and I think the vectors are compiled-const (I guess so, if not, I wouldn't be able to compile the inline constexpr parent?). Question First, do you find the approach meaningful and is there something I don't see know that actually make my solution wrong? Secondly, would you use another container or another solution with constexpr rather than a const vector, an alternative that I am maybe not aware of (maybe constexpr functions or working with iterators)? I hope everything is clear. I thank you in advance for your advises and help. Note I know that we can define constexpr vector since c++20 but I think it works only with the msvc c++20 compiler so I want to avoid that solution.
The following may give you ideas: #include <array> const int size1 = 1; const int size2 = 2; const int size3 = 3; constexpr std::array<int, size1> first = { 1 }; constexpr std::array<int, size2> second= { 2 }; constexpr std::array<int, size3> third = { 3 }; #include <variant> // The safest, I guess, annoying to use. constexpr std::array< std::variant<decltype(first), decltype(second), decltype(third)>, 3> parent1 = { first, second, third }; // The simplest - no bounds information. constexpr std::array<const int *, 3> parent2 = { first.data(), second.data(), third.data() }; // Tie bounds together with pointers. constexpr std::array<std::pair<const int *, std::size_t>, 3> parent3 = {{ { first.data(), first.size(), }, { second.data(), second.size(), }, { third.data(), third.size(), }, }}; // In C++20 we now have span #include <span> constexpr std::array<std::span<const int>, 3> parent4 = {{ first, second, third }}; // Compile-time template access. template<int index> constexpr auto parent5() { if constexpr (index == 0) { return first; } else if constexpr (index == 1) { return second; } else if constexpr (index == 2) { return third; } } I think accessing uniformly 3 arrays with different sizes is asking for out-of-bounds trouble. Remember to check bounds to avoid undefined behavior.
73,247,711
73,250,506
Why is my Arduino MKR NB 1500 stuck after sending or receiving a couple of MQTT messages?
Good morning everyone, newcomer writing his first question here (and new to C++/OOP). So, i'm currently working on a project in which i have to send 2 types of JSON payloads to a MQTT broker after regular intervals (which can be set by sending a message to the Arduino MKR NB 1500). I'm currently using these libraries: ArduinoJson, StreamUtils to generate and serialize/deserialize the JSONs, PubSubClient to publish/receive, and MKRNB in my VS code workplace. What I noticed is that my program runs fine for a couple of publishes/receives and then stays stuck in the serialization function: I tried to trace with the serial monitor to see exactly where, but eventually arrived at a point in which my knowledge in C++ is too weak to recognize where to even put the traces in the code... Let me show a small piece of the code: DynamicJsonDocument coffeeDoc(12288); //i need a big JSON document (it's generated right before //the transmission and destroyed right after) coffeeDoc["device"]["id"] = boardID JsonObject transaction = coffeeDoc.createNestedObject("transaction"); transaction["id"] = j; //j was defined as int, it's the number of the message sent JsonArray transaction_data = transaction.createNestedArray("data"); for(int i = 0; i < total; i++){ //this loop generates the objects in the JSON transaction_data[i] = coffeeDoc.createNestedObject(); transaction_data[i]["id"] = i; transaction_data[i]["ts"] = coffeeInfo[i].ts; transaction_data[i]["pwr"] = String(coffeeInfo[i].pwr,1); transaction_data[i]["t1"] = String(coffeeInfo[i].t1,1); transaction_data[i]["t2"] = String(coffeeInfo[i].t2,1); transaction_data[i]["extruder"] = coffeeInfo[i].extruder; transaction_data[i]["time"] = coffeeInfo[i].time; } client.beginPublish("device/coffee", measureJson(coffeeDoc), false); BufferingPrint bufferedClient{client, 32}; serializeJson(coffeeDoc, bufferedClient); //THE PROGRAM STOPS IN THIS AND NEVER COMES OUT bufferedClient.flush(); client.endPublish(); j++; coffeeDoc.clear(); //destroy the JSON document so it can be reused The same code works as it should if i use an Arduino MKR WiFi 1010, I think i know too little about how the GSM works. What am I doing wrong? (Again, it works about twice before getting stuck). Thanks to everybody who will find the time to help, have a nice one!!
Well, here's a little update: turns out i ran out of memory, so 12288 bytes were too many for the poor microcontroller. By doing some "stupid" tries, i figured 10235 bytes are good and close to the maximum available (the program won't use more than 85% of the RAM); yeah, that's pretty close to the maximum, but the requirements of the project give no other option. Thanks even for having read this question, have a nice one!
73,247,946
73,254,401
How change image in wxStaticBitmap in C++
The compiler tells me that the program class doesn't contain an element named SetBitmap when I want to change the image in it Solvo: wxImage bildo("./bildo.png", wxBITMAP_TYPE_PNG); objekto->SetBitmap(wxBitmap(bildo)); objekto is object with class wxStaticBitmap
As said by Igor, it is better to speak english if you want a response. Compiler says that program class does not contain an element with name "SetBitmap" when I want to change an image in it. You should post the part of your code, because wxStaticBitmap has a member named SetBitmap()
73,248,616
73,253,255
Which encoding works best for Windows API calls?
I use a function from the Windows API called GetFileAttributesW to retrieve attributes from a file. The function signature is defined as: DWORD GetFileAttributesW([in] LPCWSTR lpFileName); LPCWSTR is defined as const wchar_t*. I want to call the function: fs::path inputPath = ... GetFileAttributesW(inputPath.whichMethodHere()?); The given input path is of type std::filesystem::path that has several convenience converters like: std::filesystem::path::string() std::filesystem::path::wstring() std::filesystem::path::u8string() std::filesystem::path::u16string() std::filesystem::path::u32string() The two functions wstring() and u16string() stand out here for me. Both are defined with a character type of wchar_t and char16_t respectively. Question 1: What is the main difference between wstring() and u16string(). Does wstring() return something different than u16string in real life scenarios? Question 2: Which encoding does the Windows API generally expect?
TL;DR: char16_t doesn't provide any substantial advantage over wchar_t on Windows, and it's less convenient to use. Choose wchar_t, always. Microsoft's implementation of path::native() returns a std::wstring (not a std::u16string) as a matter of a conscious decision. Which encoding does the Windows API generally expect? Windows uses UTF-16LE encoding internally, everywhere, but doesn't enforce well-formedness anywhere. Particularly when dealing with filesystem objects, any sequence of 16-bit values (with a few exceptions) is admissible. What is the main difference between wstring() and u16string(). Does wstring() return something different than u16string in real life scenarios? The answer is more involved than this proposed answer suggests. wstring() and u16string() return a std::wstring and std::u16string, respectively, which are std::basic_string instantiations for wchar_t and char16_t. The question thus boils down to this: What is the difference between wchar_t and char16_t? The answer is disturbingly unspecific. The section on character types lists them as following: wchar_t - type for wide character representation (see wide strings). Required to be large enough to represent any supported character code point. It has the same size, signedness, and alignment as one of the integer types, but is a distinct type. char16_t - type for UTF-16 character representation, required to be large enough to represent any UTF-16 code unit (16 bits). It has the same size, signedness, and alignment as std::uint_least16_t, but is a distinct type. If you read carefully, neither type has a fixed size, and neither type is required to use any particular character encoding. It is specifically true that C++ makes no guarantees that char16_t must store UTF-16 encoded text (only that the type must be able to). What does this mean in practice? Since Windows uses UTF-16LE everywhere, wchar_t has historically always been a 16-bit type on Windows. The introduction of char16_t on Windows hasn't changed much: It's just another type capable of representing UTF-16 encoded text. Since it is a distinct type, you're going to have to cast when passing a char16_t* into a function (which has always accepted a wchar_t*, or, rather, one of its C approximations). On Windows, you can pretty much assume that wchar_t and char16_t will be the same width, and hold UTF-16 encoded characters. You can thus also assume, that wstring() and u16string() will return the same binary data. wchar_t is generally more useful as that's the native type used in interfaces, and doesn't require casts.
73,248,673
73,248,819
Cannot convert unique_ptr<derived> to unique_ptr<base>
There are 3 classes: decoder_mqtt - Common decoder subdecoder_mqtt_base - Base subdecoder for each concrete version (not an abstract class, but have virtual method). subdecoder_mqtt_v5 : subdecoder_mqtt_base - Derived from subdecoder_mqtt_base subdecoder class. decoder_mqtt creates a subdecoder: // file: mqtt.cc #include "mqtt_v5.h" ... using subdecoder_ptr = std::unique_ptr<subdecoder_mqtt_base>; ... decoder_base::result_t decoder_mqtt::decode_data(const char* data, size_t length) { return subdecoder_put_data<subdecoder_mqtt_v5>( data, length, SUBDECODERS_STATE::V5_REJECTED, _sd_mqtt_v5 ); } ... template <class SUBDECODER_T> decoder_base::result_t decoder_mqtt::subdecoder_put_data( const char* data, size_t length, SUBDECODERS_STATE sd_state_if_rejected, subdecoder_ptr& subdecoder) { if (!(to_underlying(sd_state_if_rejected) & _subdecoders_state)) { if (!subdecoder) subdecoder = std::make_unique<SUBDECODER_T>(this); // Error here! result_t res = subdecoder->reassemble_and_decode_data(data, length); if (!res) { _subdecoders_state |= to_underlying(sd_state_if_rejected); subdecoder = nullptr; } return res; } return result_t(false, 0); } Definition of a subdecoder_mqtt_v5: class subdecoder_mqtt_v5 : subdecoder_mqtt_base { public: subdecoder_mqtt_v5(decoder_mqtt* d_mqtt); virtual ~subdecoder_mqtt_v5(); virtual result_t reassemble_and_decode_data(const char* data, size_t length) override final; .... }; GCC prints an error: error: no match for ‘operator=’ (operand types are ‘decoder_mqtt::subdecoder_ptr’ {aka ‘std::unique_ptr<subdecoder_mqtt_base>’} and ‘std::_MakeUniq<subdecoder_mqtt_v5>::__single_object’ {aka ‘std::unique_ptr<subdecoder_mqtt_v5, std::default_delete<subdecoder_mqtt_v5> >’}) /usr/include/c++/9/bits/unique_ptr.h:305:7: note: candidate: ‘std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(std::unique_ptr<_Tp, _Dp>&&) [with _Tp = subdecoder_mqtt_base; _Dp = std::default_delete<subdecoder_mqtt_base>]’ 305 | operator=(unique_ptr&& __u) noexcept | ^~~~~~~~ /usr/include/c++/9/bits/unique_ptr.h:305:30: note: no known conversion for argument 1 from ‘std::_MakeUniq<subdecoder_mqtt_v5>::__single_object’ {aka ‘std::unique_ptr<subdecoder_mqtt_v5, std::default_delete<subdecoder_mqtt_v5> >’} to ‘std::unique_ptr<subdecoder_mqtt_base>&&’ 305 | operator=(unique_ptr&& __u) noexcept What am I doing wrong? Elsewhere, similar code compiles.
What am I doing wrong? subdecoder_mqtt_v5 privately derives from subdecoder_mqtt_base, so there is only an implicit conversion of pointers in the members and friends of subdecoder_mqtt_v5. The unique_ptr constructor is not one of those places. You probably meant to publicly inherit: class subdecoder_mqtt_v5 : public subdecoder_mqtt_base
73,248,689
73,258,541
Is there any reason I should include a header in the associated cpp file if the former only provides declarations the latter defines?
Consider a foo.cpp file with the following content #include "foo.hpp" int foo() { return 7; } and its associated header #pragma once int foo(); The latter is obviously needed to make aware the following main function of the existence of foo: #include <iostream> #include "foo.hpp" // to make the name `foo` available int main() { std::cout << foo() << std::endl; } However, the #include "foo.hpp" seems to be redundant. Is there any reason I should keep it? I've seen this practice in the codebase where I work on, but I guess there's many examples available in open source. For instance, as an example picked at random, look at src/builtin_builtin.h and src/builtin_bultin.cpp from the fish-shell code base: the former, beside the include guard, has just one #include, two class declarations, and a function declaration. One could put 2 in a fwd header, include it in the cpp file together with 1, and then the cpp file wouldn't need anymore to include its own header.
Some reasons to include the header (fpp.hpp) from its implementation file (fpp.cpp): If you include foo.hpp first in foo.cpp, then compilation of foo.cpp acts as a test that foo.hpp is self-contained, meaning it can be successfully compiled without including anything else first. The Google C++ coding guidelines specifically recommend including the associated header first. It is good practice for foo.hpp to declare everything that foo.cpp exports, and for everything else in foo.cpp to have internal linkage in order to not pollute the global namespace. The GCC option -Wmissing-declarations will report deviations from that practice, but it only works if foo.cpp includes foo.hpp. Sometimes (often, in fact), including foo.hpp is needed so foo.cpp will compile. Most commonly, foo.hpp defines a type that foo.cpp needs, but it can also happen that function declarations are needed due to use before definition. I recommend to just do so consistently rather than trying to deduce whether it's necessary in each case. Occasionally, the compiler can diagnose mismatches between declarations and definitions. A nasty case I've seen is a header declaring a global int x but the implementation file defining long x. Waste a day debugging that mistake, and I predict you'll resolve to include the associated header every time thereafter! Finally, there are no good reasons not to include the associated header. In particular, omitting that include will almost never make a measurable difference to compile time. There are ways of dramatically improving compile times by restructuring header dependencies (for example, use of forward headers), but this isn't one of them. Acknowledgments: Point 1 was noted by BoP in a comment. MSalters' answer notes points 3 and 4.
73,249,006
73,263,365
Qt - Replacing 1 character with multiple characters in a QString
I'm building a text converter that converts things to an exagerrated Scottish accent. Naturally, I need to turn all "u"s into "oo"s. And drop the g in any words that end with g. I'd like to know whether there's a method of replacing one character with more that one character in a QString. Code I have so far, which converts one character to another character. void MainWindow::on_replaceU_clicked() QString example = "summarize"; QString inputTextScottish = example.replace(QChar('u'), QChar('o'), Qt::CaseInsensitive); qDebug() << inputTextScottish; //Output: somarize What I'm looking for, would probably do something like this. example.replace(QChar('u'), QChar('oo'), Qt::CaseInsensitive); //Output: soomarize Please let me know if more information is needed to solve this issue. This is based on the QString documentation.
Short: void MainWindow::on_replaceU_clicked() QString example = "summarize"; // Better: use QStringLiteral("summarize") QString inputTextScottish = example.replace(QChar('u'), QLatin1String("oo"), Qt::CaseInsensitive); qDebug() << inputTextScottish; // Output: soomarize Longer Why use QStringLiteral()? Because it initializes the string at compile time, which is much faster than generating it at runtime Why use QLatin1String()? In short: it is much faster than QString or QStringLiteral (if there is an overload for QLatin1String()). You can accept @perivesta's answer, because he was faster than me
73,249,538
73,249,869
Copy and Move Assignment with additional argument
I have a RAII class which manages a resource. The problem is, copying the resource requires an additional parameter which is in no way related to the resource, rather is an argument to the resource copy operation. Thus I have a class copy constructor which requires an additional argument. This is allowed provided the additional argument has a default value. I want to write copy assignment and move assignment operators (preferably using the copy-swap idiom), but those do not allow an additional argument. I could make that troublesome argument a class member, but then users are likely to use it incorrectly, as it would need to be set before every copy or move assignment call. Any ideas how to approach this? struct Foo{ void* ptr; Foo(size_t){/*allocate*/} ~Foo(){/*deallocate*/} Foo(const Foo& that, int x = 0 /*required additional parameter for copying*/){CopyMethod(*this,that,x);} Foo& operator=(Foo);// cannot implement without int x parameter };
There is no absolute requirement in C++ that a copy or a move must be done by operator= or by a constructor. All that does is allow a copy or a move to result from a natural use of the = operator, or natural object construction. But there is no universal rule in C++ as to what copy or move must do, or what it means. It means, in practical terms, whatever the class want it to mean. Unsurprisingly, a copy or a move can also be implemented by some random class method, perhaps named copy_from or move_from. I could make that troublesome argument a class member, but then users are likely to use it incorrectly, Delete the copy/move constructor/operator. Implement class methods that effect a copy or a move from another instance of this object. Those methods can have hundreds of parameters, if needed. That would be quite cumbersome, of course. In your case just one parameter won't be much of a bother. So, in the end, a copy or a move gets effected by cheaply default-constructing a new object, and then invoking the appropriate class method, forcing your users to spell out what all the required parameters are, and logically eliminating the possibility of misusing the class's copy/move semantics. It's also possible not to delete the default constructors or operators, but perhaps implement them in some meaningful way, to effect a copy or a move with the default parameter values, and allowing usage of = in most common use cases, but requiring a named class method when things must happen out of the ordinary. When it comes to C++, the only thing that's etched in stone is its grammar. There is no way to stick some additional values in the vicinity of any natural = operator, and have it sucked into a copy or a move constructor. Hence it's not possible to make the default copy/move assignment work this way. But nothing prevents a copy or a move to be implemented by something other than an old-fashioned=. Sure, more typing is required to explicitly invoke a named class method, but it is what it is, C++'s grammar is immutable. Also, keep in mind that the C++ library containers have absolutely no knowledge, whatsoever, about any extra parameters your object requires to be copied or moved. They don't care. Shoving this object in a vector requires, at least, default copy semantics. There is no way to use your object with std::vector if it requires some explicit value, of some kind, to be copied or moved. It's a default copy constructor/assignment, or no dice.
73,249,853
73,250,036
C++ How to Auto Increment static integer variable on object creation?
C++ How to Auto Increment static integer variable on object creation? When I run the program I want the account number to increment, and I am required to use a static member of the class to automatically assign numbers. I am currently getting a make error for undefined reference to `bankAccount::accountNumber' bankAccount.h #include <string> using std::string; class bankAccount { string accountName; int accountNumber; string accountType; //Checking or Savings. double accountBalance; double interestRate; public: static int nextAccNum; bankAccount(); bankAccount(string accName, string accType, double accBalance, double intRate); void deposit(); void withdraw(); void display(); }; bankAccountImp.cpp #include <iostream> #include "bankAccount.h" using std::cout; using std::cin; using std::endl; bankAccount::bankAccount() { accountName = ""; accountNumber = nextAccNum++; accountType = ""; accountBalance = 0.00; interestRate = 0.00; accountNumber++; } bankAccount::bankAccount(string accName, string accType, double accBalance, double intRate) { accountName = accName; accountNumber = nextAccNum++; accountType = accType; accountBalance = accBalance; interestRate = intRate; } void bankAccount::deposit() { int depAmt; cout << "Please enter an amount to deposit: "; cin >> depAmt; accountBalance += depAmt; } void bankAccount::withdraw() { int delAmt; cout << "Please enter an amount to deposit: "; cin >> delAmt; accountBalance -= delAmt; } void bankAccount::display() { cout << "Account Number: " << accountNumber << endl; cout << "Holder's Name: " << accountName << endl; cout << "Account Type: " << accountType << endl; cout << "Interest Rate: " << interestRate << endl; } The program #include <iostream> #include <iomanip> #include "bankAccount.h" using std::cout; using std::endl; int main() { bankAccount acct1; bankAccount acct2; acct1.display(); cout << endl; acct2.display(); return 0; }
Like this, I've renamed the static variable nextAccNum. Having one variable called accNum and another called accountNumber is obviously a recipe for confusion. bankAccount::bankAccount() { accountName = ""; accountNumber = nextAccNum++; accountType = ""; accountBalance = 0.00; interestRate = 0.00; } bankAccount::bankAccount(string accName, string accType, double accBalance, double intRate) { accountName = accName; accountNumber = nextAccNum++; accountType = accType; accountBalance = accBalance; interestRate = intRate; }
73,250,047
73,251,046
Why can't I create process in vs2022
I am new to programming. I want simply create a process , but it always fail. This is the code. #include <Windows.h> #include <atlconv.h> #include <iostream> wchar_t* atw(const char* oc) { USES_CONVERSION; return A2W(oc); } int main() { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); if (CreateProcess( NULL, atw("E:\\AFolder\\AProgram.exe"), NULL, NULL, false, NULL, NULL, atw("E:\\AFolder"), &si, &pi )) { //do something } else { //do something } ... } "AProgram.exe" and "AFolder" are just symbols , I am sure they exist and can run. Also, my native language is not English, plesae ignore some possible language mistakes and cultural conflict
I'm afraid than atw() return a dangling pointer. check A2W implementation details and warnings from the compiler. your usage of A2W is wrong. possible solutions : std::wstring atw(const char* oc) { USES_CONVERSION; return A2W(oc); } or use A2W directly in main
73,250,277
73,250,460
force generic type of template function to inherit some class
in Rust programing language you can declare a function with argument of generic type that must implement a trait. (for those who doesn't know, you can think implement is inheritance and trait is class). so the object you pass to that function must have that trait implemented. for example: // Define a function `printer` that takes a generic type `T` which // must implement trait `Display`. fn printer<T: Display>(t: T) { println!("{}", t); } now my question is, how can I define such template function in c++ that force a type to inherit some base classes?
The C++20 way: template <std::derived_from<Display> T> void printer(const T &value) { // ... } Or the abbreviated template syntax: void printer(const std::derived_from<Display> auto &value) { // ... } Do note that there's some difference between std::derived_from and std::is_base_of_v (other than one of them being a concept): the latter checks for any base, while the former checks for an unambiguous public base. If that's what you want, but you don't have C++20, you can additionally check std::is_convertible_v<A *, B *> for this.
73,250,430
73,250,535
C++ thrown exception message not shown when running app from Windows CMD
If I run a simple app #include <stdexcept> int main() { throw std::runtime_error("Hello World!"); } with Windows CMD, the error message is not shown. How can I fix it?
Let's take a look at what throw does in C++ from the official Microsoft Docs. In the C++ exception mechanism, control moves from the throw statement to the first catch statement that can handle the thrown type. Note that this means throw does not actually output anything on its own — you'd have to catch it first, then output something. Also note that this means the throw will have to be surrounded by try if you want to do anything with the exception other than terminate the program (which throwing the exception will do on its own). See below for an example of how to use throw properly. #include <stdexcept> #include <cstdio> int main() { try { throw std::runtime_error("Hello World!"); } catch (const std::exception& e) { puts(e.what()); } }
73,250,728
73,250,826
How to Initialize a Map of Unique pointer Objects sorted by a Object Variable
Hello I am new to the c++ and have a problem with a Unique Pointer of a Object as a Key of a Map. What does the template need to look like on std::map<std::unique_ptr<Person>,string,?> phonebookMap2; so the Person gets Sorted/Inserted initial by first name? Or how do i sort the map, i tired it with sort(phonebookMap2.begin(),phonebookMap2.end(),sortfunction2); but then ther is this issue: no match for 'operator-' (operand types are 'std::_Rb_tree_iterator<std::pair<const std::unique_ptr, std::__cxx11::basic_string > >' and 'std::_Rb_tree_iterator<std::pair<const std::unique_ptr, std::__cxx11::basic_string > >') i have class looking like this: #ifndef PERSON_H #define PERSON_H #include .. class Person { private: string m_firstName; string m_lastName; string m_address; public: Person(); Person(const string& firstName, const string& lastName, const string& address); string getFirstName() const; string getLastName() const; string getAddress() const; }; bool operator<(const Person& left, const Person& right){ return left.getFirstName() < right.getFirstName(); }; #endif // PERSON_H Main: #include... bool sortfunction2(const std::unique_ptr<Person> &x, const std::unique_ptr<Person> &y) { return x->getFirstName() < y->getFirstName(); } int main() { //Template missing std::map<std::unique_ptr<Person>,string,?> phonebookMap2; phonebookMap2.insert(make_pair(std::make_unique<Person>("Max", "Mustermann", "Bahnstr. 17"),"06151 123456")); phonebookMap2.insert(make_pair(std::make_unique<Person>("Hubert", "Kah", "Minnesängergasse 23"),"06151 654321")); //Not working sort(phonebookMap2.begin(),phonebookMap2.end(),sortfunction2);<br />
You cannot std::sort a std::map. Elements in a std::map are sorted and you cannot change order, that would break invariants of the map. You can provide the comparison as functor. Then you only need to specify the functors type as argument of std::map: struct PersonCompare { bool operator()(const std::unique_ptr<Person>& left, const std::unique_ptr<Person>& right) const { return left->getFirstName() < right->getFirstName(); } }; int main() { //Template missing std::map<std::unique_ptr<Person>,string,PersonCompare> phonebookMap2; phonebookMap2.insert(make_pair(std::make_unique<Person>("Max", "Mustermann", "Bahnstr. 17"),"06151 123456")); phonebookMap2.insert(make_pair(std::make_unique<Person>("Hubert", "Kah", "Minnesängergasse 23"),"06151 654321")); } Complete Example
73,250,847
73,250,914
How does the compiler deduce which version of std::vector::begin() to call when passing it to std::vector::insert?
I am trying to make my own mini-vector class and I am attempting to replicate some of the functions, but I can not get them to behave the same way when passing calls such as begin() and end() as parameters - the compiler doesn't deduce the right version. Here is an example: template<typename T> class Iterator { public: Iterator() {} }; template<typename T> class ConstIterator { public: ConstIterator() {} }; template <typename T> class MyList { public: MyList() {} Iterator<T> Begin() { return Iterator<T>(); } ConstIterator<T> Begin() const { return Iterator<T>(); } void Insert(ConstIterator<T> it) { } }; int main() { MyList<int> myList; myList.Insert(myList.Begin()); } At myList.Insert(myList.Begin()); it does not try to use the correct version of Begin(), the const one. From what I can tell in the std::vector implementation, there are two versions of begin() - one returns an iterator and one returns a const_iterator. The only other difference between them is that one is a const method (the one returning a const_iterator). _NODISCARD _CONSTEXPR20 iterator begin() noexcept { auto& _My_data = _Mypair._Myval2; return iterator(_My_data._Myfirst, _STD addressof(_My_data)); } _NODISCARD _CONSTEXPR20 const_iterator begin() const noexcept { auto& _My_data = _Mypair._Myval2; return const_iterator(_My_data._Myfirst, _STD addressof(_My_data)); } Many methods, like std::vector::insert take a const_iterator parameter: _CONSTEXPR20 iterator insert(const_iterator _Where, const _Ty& _Val) { // insert _Val at _Where return emplace(_Where, _Val); } _CONSTEXPR20 iterator insert(const_iterator _Where, _Ty&& _Val) { // insert by moving _Val at _Where return emplace(_Where, _STD move(_Val)); } However, there is nothing in the insert method that would make the compiler use the const version of begin(). Which means it has to deduce by the return type alone, but as far as I know that's not possible? How is it achieving it then?
There is no deduction. If myList is not const-qualified, then the non-const version of Begin() is called for myList.Begin(). Otherwise the const version is called. How you use the result of myList.Begin() is not relevant. The standard library avoids your issue by providing a conversion from the non-const iterator to the const iterator. For example you could give ConstIterator a constructor which accepts a Iterator, which you must have anyway to make the return Iterator<T>(); statement in your const version of Begin() work (assuming that is not a typo).
73,250,949
73,260,345
Custom formatting of the elements of std::vectors using the fmt library
While I can use <fmt/ranges.h> to readily output the contents of a std::vector<T>, I'm at a loss to format the display of its elements according to my preferences. #include <fmt/core.h> #include <fmt/ranges.h> int main() { double x1 = 1.324353; double x2 = 4.432345; std::vector<double> v = {x1, x2}; fmt::print("{}\n", v); // OK [1.324353, 4.432345] fmt::print("{:+5.2}\n", x1); // OK +1.3 // fmt::print("{:+5.2}\n", v); // Does not compile! return EXIT_SUCCESS; } The program outputs: [1.324353, 4.432345] +1.3 but is missing the desired output from the commented out line in my code above [ +1.3, +4.4] I then tried implementing a custom formatter for vectors of ordinary type but my attempt comes up short: // custom formatter for displaying vectors template <typename T> struct fmt::formatter<std::vector<T>> : fmt::formatter<T> { constexpr auto parse(format_parse_context &ctx) { return ctx.begin(); } template <typename FormatContext> auto format(std::vector<T> v, FormatContext &ctx) { std::vector<std::string> v_str; v_str.reserve(v.size()); const auto fmt_str = [&]() { if constexpr (std::is_integral<T>::value) { return "{:+5}"; } else if constexpr (std::is_floating_point<T>::value) { return "{:+5.2}"; } else { return "{}"; } }(); for (auto &e : v) { v_str.push_back(fmt::format(fmt_str, e)); } return format_to(ctx.out(), "{}", v); } }; The compiler complains type_traits:3174:38: error: ambiguous partial specializations of 'formatter<std::vector<double>>' : public integral_constant<bool, __is_constructible(_Tp, _Args...)> How do I get the fmt library to display the contents of a vector with custom formatting? The version I'm currently using is 8.1.1.
You can do it as follows: std::vector<double> v = {1.324353, 4.432345}; fmt::print("{::+5.2}\n", v); This prints: [ +1.3, +4.4] godbolt Note the extra :. Format specifiers after the first colon (empty in this case) apply to the vector itself. Specifiers after the second colon (+5.2) apply to elements.
73,251,137
73,251,461
OpenMP integer copied after tasks finish
I do not know if this is documented anywhere, if so I would love a reference to it, however I have found some unexpected behaviour when using OpenMP. I have a simple program below to illustrate the issue. Here in point form I will tell what I expect the program to do: I want to have 2 threads They both share an integer The first thread increments the integer The second thread reads the integer Ater incrementing once, an external process must tell the first thread to continue incrementing (via a mutex lock) The second thread is in charge of unlocking this mutex As you will see, the counter which is shared between the threads is not altered properly for the second thread. However, if I turn the counter into an integer refernce instead, I get the expected result. Here is a simple code example: #include <mutex> #include <thread> #include <chrono> #include <iostream> #include <omp.h> using namespace std; using std::this_thread::sleep_for; using std::chrono::milliseconds; const int sleep_amount = 2000; int main() { int counter = 0; // if I comment this and uncomment the 2 lines below, I get the expected results /* int c = 0; */ /* int &counter = c; */ omp_lock_t mut; omp_init_lock(&mut); int counter_1, counter_2; #pragma omp parallel #pragma omp single { #pragma omp task default(shared) // The first task just increments the counter 3 times { while (counter < 3) { omp_set_lock(&mut); counter += 1; cout << "increasing: " << counter << endl; } } #pragma omp task default(shared) { sleep_for(milliseconds(sleep_amount)); // While sleeping, counter is increased to 1 in the first task counter_1 = counter; cout << "counter_1: " << counter << endl; omp_unset_lock(&mut); sleep_for(milliseconds(sleep_amount)); // While sleeping, counter is increased to 2 in the first task counter_2 = counter; cout << "counter_2: " << counter << endl; omp_unset_lock(&mut); // Release one last time to increment the counter to 3 } } omp_destroy_lock(&mut); cout << "expected: 1, actual: " << counter_1 << endl; cout << "expected: 2, actual: " << counter_2 << endl; cout << "expected: 3, actual: " << counter << endl; } Here is my output: increasing: 1 counter_1: 0 increasing: 2 counter_2: 0 increasing: 3 expected: 1, actual: 0 expected: 2, actual: 0 expected: 3, actual: 3 gcc version: 9.4.0 Additional discoveries: If I use OpenMP 'sections' instead of 'tasks', I get the expected result as well. The problem seems to be with 'tasks' specifically If I use posix semaphores, this problem also persists.
This is not permitted to unlock a mutex from another thread. Doing it causes an undefined behavior. The general solution is to use semaphores in this case. Wait conditions can also help (regarding the real-world use cases). To quote the OpenMP documentation (note that this constraint is shared by nearly all mutex implementation including pthreads): A program that accesses a lock that is not in the locked state or that is not owned by the task that contains the call through either routine is non-conforming. A program that accesses a lock that is not in the uninitialized state through either routine is non-conforming. Moreover, the two tasks can be executed on the same thread or different threads. You should not assume anything about their scheduling unless you tell OpenMP to do so with dependencies. Here, it is completely compliant for a runtime to execute the tasks serially. You need to use OpenMP sections so multiple threads execute different sections. Besides, it is generally considered as a bad practice to use locks in tasks as the runtime scheduler is not aware of them. Finally, you do not need a lock in this case: an atomic operation is sufficient. Fortunately, OpenMP supports atomic operations (as well as C++). Additional notes Note that locks guarantee the consistency of memory accesses in multiple threads thanks to memory barriers. Indeed, an unlock operation on a mutex cause a release memory barrier that make writes visible from others threads. A lock from another thread do an acquire memory barrier that force reads to be done after the lock. When lock/unlocks are not used correctly, the way memory accesses are done is not safe anymore and this cause some variable not to be updated from other threads for example. More generally, this also tends to create race conditions. Thus, put it shortly, don't do that.
73,251,357
73,251,947
string into const uint8_t*
I'm writing a program in C++/C for raspberry pi pico. Pico has a 2MB of flash memory and it's SDK provides a function which allows to write data to that memory: void flash_range_program(uint32_t flash_offs, const uint8_t *data, size_t count) Second parameter of that function is the data which we want to write in the memory. I want to save strings and floats in that memory, but I don't know what is the best (performance wise) way to convert std::string and float to __const uint8_t*__.
Assuming that std::uint8_t is unsigned char (as is usually the case), you are allowed to simply access the object representation of a float variable called f via reinterpret_cast<const unsigned char*>(&f) and the contents of a std::string variable called s via reinterpret_cast<const unsigned char*>(s.c_str()) The corresponding sizes are sizeof(f) and s.size() (or s.size()+1 if you want to store the null terminator of the string as well). This is assuming of course that you want to store the object representation of the float variable. If you want to store a serialized representation instead, then first convert to a std::string in an appropriate format. In the unlikely scenario that uint8_t is not an alias for unsigned char you are not allowed to substitute unsigned char with uint8_t in the shown casts. They would then cause aliasing violations and therefore undefined behavior when the values are accessed through the resulting pointers.
73,252,000
73,279,528
QWebEngineView causes window to move slow
m trying to move my QMainWindow by using another widget inside QMainWindow. Im moving my window by overriding : void mousePressEvent(QMouseEvent *event) void mouseMoveEvent(QMouseEvent *event) in a QTabWidget. The window moves well and everything works fine if there is no QWebEngineView widget, but if add the QWebEngineView widget to a layout the movement of the window is laggy, any idea? here is a minimal reproducible example: mainwindow.h: #include <QMainWindow> #include <QMouseEvent> #include <QtWidgets/QtWidgets> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; }; class MyTabWidget : public QTabWidget { Q_OBJECT public: MyTabWidget(QWidget *parent = 0) : QTabWidget(parent){} protected: void mousePressEvent(QMouseEvent *event) override { QWidget::mousePressEvent(event); pressPoint = event->pos(); } void mouseMoveEvent(QMouseEvent *event) override { QWidget::mouseMoveEvent(event); this->window()->move(this->window()->pos() + (event->pos() - pressPoint) ); } private: QPoint pressPoint; }; #endif // MAINWINDOW_H mainwindow.cpp: #include "mainwindow.h" #include "ui_mainwindow.h" #include <QWebEngineView> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); MyTabWidget *tabWidget = new MyTabWidget(this); ui->verticalLayout->addWidget(tabWidget); QWidget *widget = new QWidget(this); QHBoxLayout *hlayout = new QHBoxLayout(this); QWebEngineView *view = new QWebEngineView(this); widget->setLayout(hlayout); hlayout->addWidget(view); tabWidget->addTab(widget, "asd"); view->load(QUrl("https://www.google.com/")); } MainWindow::~MainWindow() { delete ui; } In this code if you delete everything related to QWebEngineView the window will move without lag. Edit: this example does the job but , is there a better way to do this? setUpdatesEnabled(false); //This in mousePressEvent bigVisualChanges(); setUpdatesEnabled(true); //This in mouseReleaseEvent i dont like this way because for example if im watching a youtube video the image will freeze.
Try to reimplement your mousePressEvent and mouseMoveEvent this way, with globalPosition() instead of pos(). Worked for me. Window started to move smoothly. void mousePressEvent(QMouseEvent *event) override { pressPoint = event->globalPosition().toPoint(); QWidget::mousePressEvent(event); } void mouseMoveEvent(QMouseEvent *event) override { QPoint delta = event->globalPosition().toPoint() - pressPoint; this->window()->move(this->window()->pos() + delta ); pressPoint = event->globalPosition().toPoint(); QWidget::mouseMoveEvent(event); } Update: For better web engine performance (page loading, video playing and webpage animations), build in release configuration. Update2: test show https://youtu.be/QM3UXjipr8Q.
73,252,011
73,252,097
Does private inheritance actually create a base-class object in the derived class?
In C++ Primer Plus p.797, Containment adds an object to a class as a named member object, whereas private inheritance adds an object to a class as an unnamed inherited object. I wonder if "private inheritance actually create a base-class object in the derived class" as this book said, Or is it just a conceptual explanation??
The statement is basically correct, but requires some corrections in the C++ terminology if it is taken strictly. (However, especially when the point is to explain OOP concepts, this terminology is often not used strictly or even conflicts with OOP terminology.) It is not the class which contains a member object or an inherited object. It is each object of the class type which contains a member subobject or a base class subobject. On the other hand the class itself has members and base classes corresponding to these subobjects. It is also not clear to me why private is of any relevance here. It doesn't affect the statement at all. As mentioned under this answer it might just be meant to contrast the "containment" concept which I guess in the C++ language would translate to private non-static data members. The quote probably is missing context though as well.
73,252,481
73,304,426
How to solve Assertion Fail in GCC Compiler, C++
Hello dudes and dudettes! When I compile my C++ program on Ubuntu (a VirtualMachine in VirtualBox), which previously ran without errors under Windows, I get a segmentation fault. /usr/bin/ld: BFD (GNU Binutils for Ubuntu) 2.38 assertion fail ../../bfd/reloc.c:8580 /home/rafael/projects/Send06/lib/x86-64//libstar-api.a(dwzh.o):fake:(.idata$2+0x0): dangerous relocation: collect2: fatal error: ld terminated with signal 11 [Segmentation fault], core dumped compilation terminated. make: *** [Makefile:382: Send06] Error 1 I understand what a segmentation fault is, but I do not comprehend how this could happen in an external library. The source code of the library is not available. Steps I took: Compiled a "Hello World!" program. --> no errors. Enlarged the virtual RAM. --> no changes. Can you help me? Thanks in advance. System: Windows 10 VM: Ubuntu 22.04.01 LTS IDE: Qt Creator 8 Compiler: gcc 11.2.0
I confused a Linux with a Windows library! The answer is quite simple. I had a folder with libraries with the ending xyz.lib and xyz.a. So I thought, .lib for Windows and .a for Linux. However, there was seperate distribution of libraries for Linux. Now everything works. Thank you for your input!
73,253,042
73,254,410
End thread from parent main vs. another thread
I'm new to C++ and am trying to have two threads run: i) Thread that keeps looping until an atomic bool is flipped. ii) A thread that polls for input from keyboard and flips the atomic bool. I seem to be unable to get std::cin.get() to react to an input unless it is assigned its' own thread (like below). Why? Would it not then be set from the parent main thread? #include <iostream> #include <iomanip> // To set decimal places. #include <thread> //std::thread #include <atomic> //for atomic boolean shared between threads. #include <math.h> #define USE_MATH_DEFINES //For PI std::atomic<bool> keepRunning(false); //set to false to avoid compiler optimising away. void loop(){ int t = 1; while(!keepRunning.load(std::memory_order_acquire)) //lower cost than directly polling atomic bool? { //Write sine wave output to console. std::cout << std::setprecision(3) << sin(M_PI * 2 * t/100) << std::endl; (t<101)? t++ : t = 1; } } //This works, as opposed to stopping in main. void countSafe(){ int j = 1; while (j<1E7) { j++; } keepRunning.store(true, std::memory_order_release); //ends the loop thread. } int main(){ std::thread first (loop); //start the loop thread std::thread second (countSafe); //start the countSafe thread. Without this it doesn't work. //Why does polling for std::cin.get() here not work? //std::cin.get(); //wait for key press. puts in buffer..? //keepRunning.store(true, std::memory_order_release); //Set stop to true. second.join(); //pause to join. first.join(); //pause to join return 0; }
I'm not quite sure what your problem is, but use of cin.get() might be part of it. Let's simplify with this code: #include <iostream> using namespace std; int main(int, char **) { cout << "Type something: "; cin.get(); cout << "Done.\n"; } Try that code and run it. Then type a single character. Chances are that the code won't recognize it. And you can type all you want until you hit return. This is complicated, but your program doesn't actually receive the characters until you hit return unless you play other games. Like I said, it's complicated. It's possible behavior is different on Windows, but this is the behavior on Mac and Linux. So is it "not working" because you tried typing a space but you really need to use Return?
73,253,049
73,253,817
Is it possible for CMake to show error when linking to two incompatible libraries?
Please see the below minimal example cmake_minimum_required(VERSION 3.20) project(sample) add_library(libA A.cpp A.h) add_library(libB B.cpp B.h) add_executable(${PROJECT_NAME} main.cpp) # Given it is known that libA and libB is incompatible, # is it possible to write some extra cmake code to show error while doing cmake config, # instead of having to compile to discover the error? target_link_libraries(${PROJECT_NAME} libA libB) --> need to show error # target_link_libraries(${PROJECT_NAME} libA) --> ok # target_link_libraries(${PROJECT_NAME} libB) --> ok Given that I can't alter the source of libA and libB to make them compatible, how can I discover the error earlier in the CMake configuration stage instead of having to compile the huge codebase to find out the error?
Yes! This is actually possible using a little-known feature called Compatible Interface Properties. You'll define a custom property with an arbitrary name. Here I'll call it ABI_GROUP and use two different GUIDs for the values. Then you'll add that property to COMPATIBLE_INTERFACE_STRING. See the code below: cmake_minimum_required(VERSION 3.23) project(example) add_library(libA A.cpp A.h) set_property(TARGET libA PROPERTY INTERFACE_ABI_GROUP "5c6142b9-9b60-4327-bd71-122bd29a9646") set_property(TARGET libA APPEND PROPERTY COMPATIBLE_INTERFACE_STRING ABI_GROUP) add_library(libB B.cpp B.h) set_property(TARGET libB PROPERTY INTERFACE_ABI_GROUP "e291a3cd-50e4-44dc-a90c-66899d34bde5") set_property(TARGET libB APPEND PROPERTY COMPATIBLE_INTERFACE_STRING ABI_GROUP) add_executable(example main.cpp) target_link_libraries(example PRIVATE libA libB) This results in the following error: CMake Error: The INTERFACE_ABI_GROUP property of "libB" does not agree with the value of ABI_GROUP already determined for "example". The values of all properties in the COMPATIBLE_INTERFACE_STRING list must either be empty or match among the transitive set of targets that are linked together. There are also a few other modes: COMPATIBLE_INTERFACE_BOOL - same as string, but tolerant to "truthy" values, i.e. ON and 1 are considered compatible COMPATIBLE_INTERFACE_NUMBER_MAX - the property evaluates to the largest number among the transitive target set. COMPATIBLE_INTERFACE_NUMBER_MIN - same as above, but smallest
73,253,091
73,253,531
Can someone please explain this bit manipulation code to me?
I am new to competitive programming. I recently gave the Div 3 contest codeforces. Eventhough I solved the problem C, I really found this code from one of the top programmers really interesting. I have been trying to really understand his code, but it seems like I am too much of a beginner to understand it without someone else explaining it to me. Here is the code. void main(){ int S; cin >> S; int ans = 1e9; for (int mask = 0; mask < 1 << 9; mask++) { int sum = 0; string num; for (int i = 0; i < 9; i++) if (mask >> i & 1) { sum += i + 1; num += char('0' + (i + 1)); } if (sum != S) continue; ans = min(ans, stoi(num)); } cout << ans << '\n'; } The problem is to find the minimum number whose sum of digits is equal to given number S, such that every digit in the result is unique. Eq. S = 20, Ans = 389 (3+8+9 = 20)
Mask is 9-bits long, each bit represents a digit from 1-9. Thus it counts from 0 and stops at 512. Each value in that number corresponds to possible solution. Find every solution that sums to the proper value, and remember the smallest one of them. For example, if mask is 235, in binary it is 011101011 // bit representation of 235 987654321 // corresponding digit ==> 124678 // number for this example: "digits" with a 1-bit above // and with lowest digits to the left There are a few observations: you want the smallest digits in the most significant places in the result, so a 1 will always come before any larger digit. there is no need for a zero in the answer; it doesn't affect the sum and only makes the result larger This loop converts the bits into the corresponding digit, and applies that digit to the sum and to the "num" which is what it'll print for output. for (int i = 0; i < 9; i++) if (mask >> i & 1) { // check bit i in the mask sum += i + 1; // numeric sum num += char('0' + (i + 1)); // output as a string } (mask >> i) ensures the ith bit is now shifted to the first place, and then & 1 removes every bit except the first one. The result is either 0 or 1, and it's the value of the ith bit. The num could have been accumulated in an int instead of a string (initialized to 0, then for each digit: multiply by 10, then add the digit), which is more efficient, but they didn't.
73,253,775
73,274,712
'identifier undefined' in C++11 for-loop with USTRUCT
I am implementing logging functionality in Unreal Engine 4.27 (in C++). A key part of my code is a function that is called once per game-tick. This function is responsible for iterating over an array of actors that I would like to log data for, checking whether a new log entry should be written at this point in time and calling the necessary functions to do that. I am iterating over elements of a TArray of UStructs: LogObject->LoggingInfo = TArray<FActorLoggingInformation>. This array is defined as a UProperty of LogObject. In the loop I have to change the values of the elements so I want to work with the original items and "label" the current item as "ActorLoggingInfo". I have seen this done generally in cpp and also with TArrays. And yet my code does not work, there is no error message, but ActorLoggingInfo is undefined, thus the if-condition is never met. This is the for-loop: for (FActorLoggingInformation& ActorLoggingInfo : LogObject->LoggingInfo) { if (ActorLoggingInfo.LogNextTick == true) { ActorLoggingInfo.LogNextTick = false; ... } ... } This is the definition of FActorLoggingInformation: USTRUCT(BlueprintType) struct FActorLoggingInformation { GENERATED_BODY() public: FActorLoggingInformation() { } FActorLoggingInformation(int32 LogTimer, AActor* Actor, FString LogName) { this->LogTimer = LogTimer; this->LogNextTick = false; ... } // Specifies Logging Frequency in ms UPROPERTY(BlueprintReadOnly, VisibleAnywhere) int32 LogTimer; bool LogNextTick; ... }; This is the debugger at run-time: Additional Notes: 1. Something that consistently works for me is omitting the &, using: for (FActorLoggingInformation ActorLoggingInfo : LogObject->LoggingInfo) However, this is creating useless duplicates on a per-tick basis and complicates applying changes to the original objects from within in the for-loop, so it is not a viable option. 2. I have also tried auto& instead of FActorLoggingInformation& as used in the examples above, but I encountered the same issue, so I thought it would be best to be as explicit as possible. I would be very thankful if you had any ideas how I can fix this :) Thanks in advance!
Thanks to Avi Berger for helping me find my problem! In fact, ActorLoggingInfo was actually never undefined and the code within the body of the if-clause was also executed (it just didn't do what it was intended to do). When stepping through the code in the debugger it never showed the steps within the if-body and ActorLoggingInfo was shown as undefined so when no logs were written, I assumed it was something to do with that instead of my output function not working properly. So lesson learnt, do not blindly trust the debugger :)
73,253,926
73,254,089
Is it possible to use a static template variable in a template function?
For example, in this instance (the code is pretty self-explanatory): enum types : bool { READ, WRITE }; template<typename T> auto function(types i, T data) { static T datas; if (i == WRITE) { datas = data; } else if (i == READ) { return datas; } } int main() { function(WRITE, "hello"); std::cout << function(READ, NULL); } The expected output is: hello but it ends up in an exception. Is there any way to fix this or is it not possible?
You should be able to use this kind of logic, but the issue here is that the type parameters for both calls are different. (There's also another issue of a function with return type T not returning anything, but I'll ignore this for now.) The first call uses char const* as template parameter and the second one either int or std::nullptr_t depending on how the NULL macro is defined. Your code results in an uninitialized value being returned by the second call which is undefined behaviour. You need to make sure the same template parameter is used in both cases: int main() { function(WRITE, "hello"); std::cout << function(READ,static_cast<char const*>(nullptr)); } or int main() { function(WRITE, "hello"); std::cout << function<char const*>(READ, nullptr); }
73,254,797
73,254,844
Template does not work when it is not in the main class
I have tried using a template in a class but it works in the main class. Here is my main class: #include "AddSubtract.cpp" #include <iostream> #include <string> using namespace std; int main() { templEx(); } And here is the class where the template is located: #include <iostream> #include <string> using namespace std; template<typename T> void Print(T value) { std::cout << value << std::endl; } void templEx() { Print("Venezuela"); } And here are the errors which I get: Severity Code Description Project File Line Source Suppression State Error LNK2005 "void __cdecl templEx(void)" (?templEx@@YAXXZ) already defined in AddSubtract.obj ConsoleApplication1 C:\Users\bahge\source\repos\ConsoleApplication1\ConsoleApplication1\Source1.obj 1 Build Severity Code Description Project File Line Source Suppression State Error LNK1169 one or more multiply defined symbols found ConsoleApplication1 C:\Users\bahge\source\repos\ConsoleApplication1\x64\Debug\ConsoleApplication1.exe 1 Build
You're compiling that code that defines tmplEx once in the main.cpp and additionally in the secondary source file, which leads to the conflict. Define the template in a separate header file that both can #include as necessary.
73,255,024
73,270,885
Zero Subsequences problem - What's wrong with my C++ solution?
Problem Statement: Given an array arr of n integers, count the number of non-empty subsequences of the given array such that their product of maximum element and minimum element is zero. Since this number can be huge, compute it modulo 10 ^ 9 + 7 A subsequence of an array is defined as the sequence obtained by deleting several elements from the array (possible none) without changing the order of the remaining elements. Example Given n = 3, arr = [1, 0, – 2]. There are 7 subsequences of arr that are- [1], minimum = 1, maximum =1 , min * max = 1 . [1,0] minimum = 0, maximum=1, min * max=0 [ 1,0, – 2], minimum = – 2, maximum =1, min* max = -2. [0], minimum = 0, maximum =0, min * max=0 [0,-2],minimum=-2,maximum=0, min* max=0, [1, -2] minimum=-2, maximum=1,min* max=-2 [- 2] minimum =-2 maximum = – 2 , min* max = 4. There are 3 subsequences whose minimum * maximum = 0 that are [1, 0], [0], [0, – 2] . Hence the answer is 3. I tried to come up with a solution, by counting the number of zeroes, positive numbers and negative numbers and then adding possible subsequences(2^n, per count) to an empty variable. My answer is way off though, it's 10 when the expected answer is 3. Can someone please point out my mistake? #include<bits/stdc++.h> using namespace std; #define int long long int zeroSubs(vector<int> arr){ int x = 0, y = 0, z = 0, ans = 0; for(int i = 0; i < arr.size(); i++){ if(arr[i] == 0) z++; else if(arr[i] < 0) x++; else y++; } ans += ((int)pow(2, z))*((int)pow(2, x)); ans += ((int)pow(2, y))*((int)pow(2, z)); ans += ((int)pow(2, z)); return ans; } int32_t main() { //directly passed the sample test case as an array cout<<zeroSubs({1, 0, -2}); return 0; }
ans += ((1<<z)-1)*((1<<x)-1); ans += ((1<<y)-1)*((1<<z)-1); ans += ((1<<z)-1); Made this slight change in the logic, thanks a lot to everyone for the valuable feedback. It works now.
73,255,661
73,336,950
wxWidgets wxGetKeyState() and Wayland issue
I have run into a wxGetKeyState() issue with Wayland. Let me explain: In some of my apps, I add a test for the Shift key being pressed in the ctor of my app’s top wxFrame window. If the Shift key is down during launch, I run diagnostic code relevant to my app. This has always worked just fine until I switched to Ubuntu 22.04 with the Wayland display server. If I run my app in Ubuntu 22.04 with the X.org display sever, everything runs as expected. By the way, I’m using wxWidgets 3.2.0. To test this possible bug just add these few lines of code to the end of the top wxFrame ctor. MyFrame::MyFrame() { ... if (wxGetKeyState(WXK_SHIFT)) { wxMessageBox("Hello there"); } } Does anyone have run into this issue? Is there a known work-around? Regards, Bob EDIT: When I run the minimal app (shown below) I see these results for X and Wayland. Output when launching the app while holding the shift key down in X. 18:40:25: Debug: from CTOR: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 18:40:25: Debug: from idle: 1 Under X, wxGetKeyState() behaves as expected. It goes thru 16 idle cycles before stopping while showing the correct value all along. Now, this is the output when launching the app while holding the shift key down in Waylan. 18:32:43: Debug: from CTOR: 0 18:32:43: Debug: from idle: 0 18:32:43: Debug: from idle: 0 18:32:43: Debug: from idle: 0 18:32:43: Debug: from idle: 1 Under Wayland, the test at the ctor fails and it takes 3 idle cycles before reporting the correct value. I hope this test helps to identify and solve this issue. Minimal test program: #include <wx/wx.h> class MyApp: public wxApp { public: virtual bool OnInit(); }; class MyFrame: public wxFrame { public: MyFrame(); void on_idle(wxIdleEvent& event); }; wxIMPLEMENT_APP(MyApp); bool MyApp::OnInit() { MyFrame* wnd = new MyFrame(); wnd->Show(); return true; } MyFrame::MyFrame() : wxFrame(NULL, wxID_ANY, "minimal") { Bind(wxEVT_IDLE, &MyFrame::on_idle, this); wxLogDebug("from CTOR: %d", wxGetKeyState(WXK_SHIFT)); } void MyFrame::on_idle(wxIdleEvent& event) { wxLogDebug("from idle: %d", wxGetKeyState(WXK_SHIFT)); }
I implemented a temporary solution to my problem with the Wayland/wxGetKeyState() issue. The function get_key_state_hack(), below, offers the same functionally of wxGetKeyState() with the following caveats: The use of this function only makes sense when targeting Linux/Wayland. It does not provide any advantage in any other context. The day that wxGetKeyState() starts working correctly with Wayland, you won’t need this function anymore. As suggested by VZ, the problem seems to be with GDK. This function is only useful during the start-up of the program since after a few idle event cycles wxGetKeyState() works correctly. This function will block for a few idle event cycles. This is not a problem in my case since I use it as a one-time test to detect if the Shift key was held down during program launch and as soon as the user moves the mouse or touches the keyboard there will be an avalanche of idle events. #include <wx/evtloop.h> bool get_key_state_hack(wxKeyCode key) { int count = 5; bool pressed = false; wxEventLoop loop; auto on_idle = [&](wxIdleEvent& event) { pressed = wxGetKeyState(key); if (pressed || (--count < 1)) { loop.Exit(); } }; wxTheApp->Bind(wxEVT_IDLE, on_idle); loop.Run(); wxTheApp->Unbind(wxEVT_IDLE, on_idle); return pressed; } By the way, I decided to use a lambda function as event handler to keep all the code nicely packed in a single C++ function. I hope this function can be useful to anyone who faces this problem.
73,255,930
73,258,034
Add namespace pcl functions and PointT in header file
I have a header file preprocess.h in the include folder that simply does noise removal from a point cloud. The point type of point cloud does not exist in the pcl library so I have to create a custom point type RadarPoint for pcl::PointCloud<PointT>. Also, it's a good practice to create a namespace for functions inside the header file. The following is my code. #ifndef PREPROCESS_H #define PREPROCESS_H #define PCL_NO_PRECOMPILE #include <ros/ros.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/pcl_macros.h> #include <pcl/filters/statistical_outlier_removal.h> namespace filtration { struct RadarPoint { PCL_ADD_POINT4D; // preferred way of adding a XYZ+padding uint8_t beam_side; EIGEN_MAKE_ALIGNED_OPERATOR_NEW // make sure our new allocators are aligned } EIGEN_ALIGN16; // enforce SSE padding for correct memory alignment POINT_CLOUD_REGISTER_POINT_STRUCT (RadarPoint, // here we add XYZ and beam_side (float, x, x) (float, y, y) (float, z, z) (uint8_t, beam_side, beam_side) ) //remove outliers from point cloud pcl::PointCloud<RadarPoint>::Ptr filter(const pcl::PointCloud<RadarPoint>::Ptr& cloud_input); } #endif However, there are some bugs. For the function, I got the error "namespace filtration::pcl" has no member PointCloud. For the custom PointT, I got the two errors. The first error is namespace "filtration::pcl" has no member "Vector3fMap" for the code PCL_ADD_POINT4D;. The second error is improperly terminated macro invocation for the code POINT_CLOUD_REGISTER_POINT_STRUCT. Any help on why and how to solve them?
POINT_CLOUD_REGISTER_POINT_STRUCT must be used in the global namespace: https://github.com/PointCloudLibrary/pcl/blob/master/common/include/pcl/register_point_struct.h#L63 See also how the macro is used in PCL: https://github.com/PointCloudLibrary/pcl/blob/master/common/include/pcl/impl/point_types.hpp#L1781
73,256,565
73,258,767
My program for calculating pi using Chudnovsky in C++ precision problem
My code: #include <iostream> #include <iomanip> #include <cmath> long double fac(long double num) { long double result = 1.0; for (long double i=2.0; i<num; i++) result *= i; return result; } int main() { using namespace std; long double pi=0.0; for (long double k = 0.0; k < 10.0; k++) { pi += (pow(-1.0,k) * fac(6.0 * k) * (13591409.0 + (545140134.0 * k))) / (fac(3.0 * k) * pow(fac(k), 3.0) * pow(640320.0, 3.0 * k + 3.0/2.0)); } pi *= 12.0; cout << setprecision(100) << 1.0 / pi << endl; return 0; } My output: 3.1415926535897637228433865175247774459421634674072265625 The problem with this output is that it outputed 56 digits instead of 100; How do I fix that?
First of all your factorial is wrong the loop should be for (long double i=2.0; i<=num; i++) instead of i<num !!! As mentioned in the comments double can hold only up to ~16 digits so your 100 digits is not doable by this method. To remedy this there are 2 ways: use high precision datatype there are libs for this, or you can implement it on your own you need just few basic operations. Note that to represent 100 digits you need at least ceil(100 digits/log10(2)) = 333 bits of mantisa or fixed point integer while double has only 53 53*log10(2) = 15.954589770191003346328161420398 digits use different method of computation of PI For arbitrary precision I recommend to use BPP However if you want just 100 digits you can use simple taylor seriesbased like this on strings (no need for any high precision datatype nor FPU): //The following 160 character C program, written by Dik T. Winter at CWI, computes pi to 800 decimal digits. int a=10000,b=0,c=2800,d=0,e=0,f[2801],g=0;main(){for(;b-c;)f[b++]=a/5; for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);} Aside the obvious precision limits Your implementation is really bad from both performance and precision aspects that is why you lost precision way sooner as you hitting double precision limits in very low iterations of k. If you rewrite the iterations so the subresults are as small as can be (in terms of bits of mantisa) and not use too much unnecessary computations here few hints: why are you computing the same factorials again and again You have k! in loop where k is incrementing why not just multiply the k to some variable holding actual factorial instead? for example: //for ( k=0;k<10;k++){ ... fac(k) ... } for (f=1,k=0;k<10;k++){ if (k) f*=k; ... f ... } why are you divide by factorials again and again if you think a bit about it then if (a>b) you can compute this instead: a! / b! = (1*2*3*4*...*b*...*a) / (1*2*3*4*...*b) a! / b! = (b+1)*(b+2)*...*(a) I would not use pow at all for this pow is "very complex" function causing further precision and performance losses for example pow(-1.0,k) can be done like this: //for ( k=0;k<10;k++){ ... pow(-1.0,k) ... } for (s=+1,k=0;k<10;k++){ s=-s; ... s ... } Also pow(640320.0, 3.0 * k + 3.0/2.0)) can be computed in the same way as factorial, pow(fac(k), 3.0) you can 3 times multipply the variable holding fac(k) instead ... the therm pow(640320.0, 3.0 * k + 3.0/2.0) outgrows even (6k)! so you can divide it by it to keep subresults smaller... These few simple tweaks will enhance the precision a lot as you will overflow the double precision much much latter as the subresults will be much smaller then the naive ones as factorials tend to grow really fast Putting all together leads to this: double pi_Chudnovsky() // no pow,fac lower subresult { // https://en.wikipedia.org/wiki/Chudnovsky_algorithm double pi,s,f,f3,k,k3,k6,p,dp,q,r; for (pi=0.0,s=1.0,f=f3=1,k=k3=k6=0.0,p=640320.0,dp=p*p*p,p*=sqrt(p),r=13591409.0;k<27.0;k++,s=-s) { if (k) // f=k!, f3=(3k)!, p=pow(640320.0,3k+1.5)*(3k)!/(6k)!, r=13591409.0+(545140134.0*k) { p*=dp; r+=545140134.0; f*=k; k3++; f3*=k3; k6++; p/=k6; p*=k3; k3++; f3*=k3; k6++; p/=k6; p*=k3; k3++; f3*=k3; k6++; p/=k6; p*=k3; k6++; p/=k6; k6++; p/=k6; k6++; p/=k6; } q=s*r; q/=f; q/=f; q/=f; q/=p; pi+=q; } return 1.0/(pi*12.0); } as you can see k goes up to 27, while your naive method can go only up to 18 on 64 bit doubles before overflow. However the result is the same as the double mantissa is saturated after 2 iterations ...
73,256,881
73,585,556
Why do we traverse backwards when using counting sort
I have been using counting sort for a few days now. I have noticed that we travers backwards when using it. I was wondering why? If anyone could answer it. It would be great.
We do this to maintain stability because if we traverse 1 4 1 2 7 2 as the frequency of 1 is 2 if we traverse from front it will move first one to 2nd position then again again move 3 one to first position disturbing their order this doesn't affect much if we consider these two ones same but this will affect if we are using 2D array and there is some data attached to it, then this will change the order more if traverse from front ,try this by yourself on paper you will understand keeping the order point in mind.
73,256,915
73,270,939
Traversing byte string through uint16_t pointer
I have a list of uint16_t's that has been packed into a protobuf message that looks like: bytes values = 1; The generated stubs for this message in C allows me to set the field with some code like: protobufMessage.set_values(uint16ptr, sizeof(uint16_t) * amount); In the above example, uint16ptr is a uint16_t* to the start of the value list and amount is the number of elements in that list. Now, since I know the message is in the field and I want to be as efficient as possible, I don't want to memcpy as that I want to somehow directly access that memory and I don't want to iterate through the values one by one as cases with a large amount value would be slow. So I tried something like: uint16_t *ptr = (uint16_t*) some_string.c_str(); This works "fine", however I don't get the same values I originally packed in. I think it might be because I am not traversing the data correctly. How should I do this properly?
Protobuf encodes your message so you can't simply read the values back from a string. But a "repeated" uint16_t should be a big blob somewhere in the message. If you knew the offset you could access the data there. But that is still UB since the uint16_t in the protobuf message are not aligned. So on some CPUs this will be just slow, on others it will trap. The only safe way is to memcpy the data. Use the function provided by protobuf to extract the uint16_t's. Note: Strictly speaking it's even worse since there are no objects of type uint16_t living in the message so any access would be UB. But it being a fundemantal type makes it ok-ish, if it weren't for the alignment.
73,257,086
73,257,311
how to pack a std::string as a std::tuple<Ts...>
I have a parameter pack like <int, long, string, double> and a string like "100 1000 hello 1.0001" how can I resolve these data and pack them into a std::tuple<int, long, string, double>
One way is to use std::apply to expand the elements of the tuple and use istringstream to extract the formatted data and assign it to the element #include <string> #include <tuple> #include <sstream> int main() { std::string s = "100 1000 hello 1.0001"; std::tuple<int, long, std::string, double> t; auto os = std::istringstream{s}; std::apply([&os](auto&... x) { (os >> ... >> x); }, t); } Demo
73,257,227
73,257,250
C++: wchar_t cannot be stored in a std::map as a key or value
I am trying to make a variable with the data type std::map<char, wchar_t> in C++. When I try this, Visual Studio gives this build error: C2440 'initializing': cannot convert from 'initializer list' to 'std::map<char,wchar_t,std::less<char>,std::allocator<std::pair<const char,wchar_t>>>' The same error also occurs when wchar_t is the key data type and char is the value data type. You can replicate this error by running the following code: const std::map<char, wchar_t> UNICODE_MAP = { { 'X', L"█" }, { 'G', L"▓" }, { 'O', L"ᗣ" }, { 'P', L"ᗤ" } }; How would I make a map with the key as a char and the value as a wchar_t data type?
It's a map from narrow char to wide char, not char to wide string: Instead of this: const std::map<char, wchar_t> UNICODE_MAP = { { 'X', L"█" }, { 'G', L"▓" }, { 'O', L"ᗣ" }, { 'P', L"ᗤ" } }; Use this: const std::map<char, wchar_t> UNICODE_MAP = { { 'X', L'█' }, { 'G', L'▓' }, { 'O', L'ᗣ' }, { 'P', L'ᗤ' } }; If you actually need the value to be a string, then declare it as: const std::map<char, std::wstring> UNICODE_MAP = { { 'X', L"█" }, ... Also, while I'm here, I advocate for escaping all Unicode chars in source files that are not in the ASCII range. Between IDEs with varying behaviors, revision control systems, and the guy down the hall who didn't read your memo about "save as Unicode", this can get easily corrupted. So... my final recommendation is this: const std::map<char, wchar_t> UNICODE_MAP = { { 'X', L'\u2588' }, { 'G', L'\u2593' }, { 'O', L'\u15e3' }, { 'P', L'\u15e4' } };
73,257,382
73,257,557
Trying to enable conservative rasterization fails
I am trying to follow Sacha Willems' example on conservative rasterization. To that effect I added tried requesting the extensions when making my device: const std::vector<const char*> DEVICE_EXTENSIONS = { VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME }; vk::DeviceCreateInfo create_info = {}; create_info.queueCreateInfoCount = queue_create_infos.size(); create_info.pQueueCreateInfos = queue_create_infos.data(); create_info.enabledLayerCount = 0; create_info.ppEnabledLayerNames = nullptr; create_info.enabledExtensionCount = DEVICE_EXTENSIONS.size(); create_info.ppEnabledExtensionNames = DEVICE_EXTENSIONS.data(); create_info.pEnabledFeatures = &device_features; /* ... */ However when I try to load some of the extension functions, it fails: vkGetPhysicalDeviceProperties2KHR_NE = (PFN_vkGetPhysicalDeviceProperties2KHR) vkGetInstanceProcAddr( instance, "vkGetPhysicalDeviceProperties2KHR"); Assert(vkGetPhysicalDeviceProperties2KHR_NE, "Failed to find extension function: vkGetPhysicalDeviceProperties2KHR"); Failed check: vkGetPhysicalDeviceProperties2KHR_NE Failed to find extension function: vkGetPhysicalDeviceProperties2KHR I know that the extension is available in my card: vulkaninfo | grep extensi | grep conservative MESA-INTEL: warning: Haswell Vulkan support is incomplete WARNING: lavapipe is not a conformant vulkan implementation, testing use only. WARNING: lavapipe is not a conformant vulkan implementation, testing use only. VK_EXT_conservative_rasterization : extension revision 1 What am I missing?
VK_KHR_get_physical_device_properties2 is an instance level extension (see the name chapter of the extension spec), but you are enabling it at the device level. That's why loading it's function pointer via vkGetInstanceProcAddr fails. You need to enable that extension at instance creation time.
73,257,461
73,257,520
Why is this function returning an empty vector?
In the code below I am trying to return an array containing the longest strings of the inputArray. However, when I use it the array outputted is empty. vector<string> solution(vector<string> inputArray) { int highestSize, add; vector<string> newArray{}; for (int i = 0; i < inputArray.size(); ++i) { highestSize = max(int(inputArray[i].length()), highestSize); } for (int i = 0; i < inputArray.size(); ++i) { if (inputArray[i].length() == highestSize) { newArray[add] = inputArray[i]; ++add; } } return newArray; }
There are several issues in your code: highestSize and add are not initialized. In C++ variables are not default initialized to 0 as you might have expected. newArray is default constructed to have 0 elements. In this case you cannot use operator[] the way you did. operator[] can access only elements that were allocated. You can use push_back to add to the vector. If your code was changed so that you knew in advance how many entries you will need in newArray, you could also resize the vector and then use operator[] to access the elements. There are some more options like resereving capacity and using push_back, you can see more info here. It's better to pass inputArray by const& to avoid an unneeded copy. A fixed version: #include <string> #include <vector> std::vector<std::string> solution(std::vector<std::string> const & inputArray) { int highestSize{ 0 }; std::vector<std::string> newArray{}; for (int i = 0; i < inputArray.size(); ++i) { highestSize = std::max(int(inputArray[i].length()), highestSize); } for (int i = 0; i < inputArray.size(); ++i) { if (inputArray[i].length() == highestSize) { newArray.push_back(inputArray[i]); } } return newArray; } A side note: it's better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
73,257,667
73,257,785
Learning c++ atm and this seems like a dumb question but can someone please tell me why the guessing game i made isnt working?
while(guess!=ans1){ cout << "Enter your first guess: "; cin >> guess; } This is the loop I am using but its not working can someone please tell me how I fix this?? (I am not using an ide btw.) EDIT Full code #include <iostream> using namespace std; int main() { int ans1 = 3; int ans2 = 7; int ans3 = 12; int guess; while (guess != ans1) { cout << "Enter your first guess: "; cin >> guess; } cout << "\nYou guessed correctly!"; while (guess != ans2) { cout << "Enter your second guess: "; cin >> guess; } cout << "\nYou guessed correctly!"; while (guess != ans3) { cout << "Enter your final guess: "; cin >> guess; } cout << "\nYou win!!!"; return 0; }
I offer you some alternatives: #include <iostream> int main() { using std::cout; // this allows you to only use cout instead of std::cout using std::cin; // and not import the entire namespace. Also, only within // the main function. So no global pollution. int const ans1 = 3; // these do not change, so they should be const int const ans2 = 7; int const ans3 = 12; int guess = 0; while (guess != ans1) { cout << "Enter your first guess: "; cin >> guess; } cout << "\nYou guessed correctly!\n"; while (guess != ans2) { cout << "Enter your second guess: "; cin >> guess; } cout << "\nYou guessed correctly!"; while (guess != ans3) { cout << "Enter your final guess: "; cin >> guess; } cout << "\nYou win!!!"; } But surely you notice we copied a lot of code. This is where we can make use of arrays. A lot of free tutorials will teach you C-style arrays, but this is the C++ way to do it: #include <array> #include <iostream> int main() { using std::array; using std::cout; using std::cin; // alternatively array<int, 3> const answers = {3, 7, 12}; int guess = 0; for( std::size_t i = 0; i < answers.size(); i++ ){ // (iterating loop, the "standard" for loop while( guess != answers[i] ){ cout << "Enter your first guess: "; cin >> guess; } cout << "\nYou guessed correctly!\n"; } // alternatively for( auto const& answer : answers ){ // range based loop (more complicated to understand) while( guess != answers ){ cout << "Enter your first guess: "; cin >> guess; } cout << "\nYou guessed correctly!\n"; } return 0; }
73,257,728
73,257,950
Vulkan extensions is listed by vulkaninfo but not by enumerateInstanceExtensions
I am trying to enable conservative rasterization. To that effect I am calling vk::enumerateExtensionProperties() to see the extensions supported on my system. That gives me this list: VK_KHR_device_group_creation VK_KHR_display VK_KHR_external_fence_capabilities VK_KHR_external_memory_capabilities VK_KHR_external_semaphore_capabilities VK_KHR_get_display_properties2 VK_KHR_get_physical_device_properties2 VK_KHR_get_surface_capabilities2 VK_KHR_surface VK_KHR_surface_protected_capabilities VK_KHR_wayland_surface VK_KHR_xcb_surface VK_KHR_xlib_surface VK_EXT_acquire_drm_display VK_EXT_acquire_xlib_display VK_EXT_debug_report VK_EXT_direct_mode_display VK_EXT_display_surface_counter VK_EXT_debug_utils VK_KHR_portability_enumeration Printed by: auto [result, extensions] = vk::enumerateInstanceExtensionProperties(); Assert( result == vk::Result::eSuccess, "Error: Failed to request available extensions"); for(const auto& extension: extensions) { std::cout << extension.extensionName << std::endl; } Conservative rasterization is not enabled. But when I use vulkaninfo it does show: Device Extensions: count = 138 VK_EXT_4444_formats : extension revision 1 VK_EXT_blend_operation_advanced : extension revision 2 VK_EXT_border_color_swizzle : extension revision 1 VK_EXT_buffer_device_address : extension revision 2 VK_EXT_calibrated_timestamps : extension revision 2 VK_EXT_color_write_enable : extension revision 1 VK_EXT_conditional_rendering : extension revision 2 VK_EXT_conservative_rasterization : extension revision 1 ... How come it is found by vulkan ino and not by enumerateExtenions?
You are comparing instance extensions (on your side) with device extensions in vulkaninfo. To get a list of device extensions, you need to call vkEnumerateDeviceExtensionPropertiesinstead of vkEnumerateInstanceExtensionProperties. That should give you the same list as vulkaninfo does.
73,258,713
73,266,409
LLVM IR C++ API create anonymous global variable
How can I create an anonymous global variable in LLVM IR C++ API? I can create a named global variable as follows: GlobalVariable *createGlobalVariable( Module *module, Type *type, std::string name ) { module->getOrInsertGlobal(name, type); return module->getNamedGlobal(name); } For example: auto context = new LLVMContext(); auto module = new Module("Module", *context); auto type = IntegerType::getInt32Ty(*context); auto globalVariable = createGlobalVariable( module, type, "globalVariableName" ); auto constantInt = ConstantInt::getIntegerValue( type, APInt(32, 42) ); globalVariable->setInitializer(constantInt); module->dump(); It will generate: ; ModuleID = 'Module' source_filename = "Module" @globalVariableName = global i32 42 How can I create an anonymous global variable? I would like to generate somethings like: ; ModuleID = 'Module' source_filename = "Module" @0 = global i32 42 @0 is a unique identifiers
In comment, @IlCapitano said that Pass "" as name I try auto context = new LLVMContext(); auto module = new Module("Module", *context); auto type = IntegerType::getInt32Ty(*context); auto constant = module->getOrInsertGlobal("", type); module->dump(); It generates: ; ModuleID = 'Module' source_filename = "Module" @0 = external global i32 But if I set initializer, will be Segmentation fault auto constant = module->getOrInsertGlobal("", type); auto anonymousGlobalVariable = module->getNamedGlobal(constant->getName()); anonymousGlobalVariable->setInitializer(constantInt); // -> Segmentation fault The correct way is creating GlobalVariable by using constructor: auto context = new LLVMContext(); auto module = new Module("Module", *context); auto type = IntegerType::getInt32Ty(*context); auto constantInt = ConstantInt::getIntegerValue(type, APInt(32, 42)); auto anonymousGlobalVariable = new GlobalVariable( *module, type, false, GlobalValue::CommonLinkage, constantInt, "" ); module->dump(); Nice ; ModuleID = 'Module' source_filename = "Module" @0 = common global i32 42
73,259,231
73,259,797
`std::stable_sort` gives wrong results when `std::execution::par`
I wrote simple algorithm for sorting rows in Eigen matrix. This should do the same as Matlab's sortrows function: template <typename D> void _sort( const D &M, Eigen::VectorX<ptrdiff_t>& idx, std::function<bool(ptrdiff_t, ptrdiff_t)> cmp_fun) { // initialize original index locations idx = Eigen::ArrayX<ptrdiff_t>::LinSpaced( M.rows(), 0, M.rows()-1); std::stable_sort(std::execution::par, idx.begin(), idx.end(), cmp_fun); } /// \brief sort_rows sorts the rows of a matrix in ascending order /// based on the elements in the first column. When the first column /// contains repeated elements, sortrows sorts according to the values /// in the next column and repeats this behavior for succeeding equal values. /// M_sorted = M(ind, Eigen::all) /// \param M /// \return ind template <typename D> Eigen::VectorX<ptrdiff_t> sort_rows(const Eigen::DenseBase<D> &M){ // initialize original index locations Eigen::VectorX<ptrdiff_t> idx; ptrdiff_t col = 0; std::function<bool(ptrdiff_t, ptrdiff_t)> cmp_fun; cmp_fun = [&M, &col, &cmp_fun]( const ptrdiff_t& row1, const ptrdiff_t& row2)->bool { if (M(row1, col) < M(row2, col)){ col = 0; return true; } if (M(row1, col) > M(row2, col)){ col = 0; return false; } // only 'M(row1, col) == M(row2, col)' option is left // it will return 'true' only if this is the last column // i.e. all other columns at these rows are also equal if (col == M.cols()-1){ if (M(row1, col) == M(row2, col)){ col = 0; return true; } col = 0; return false; } col++; return cmp_fun(row1, row2); }; _sort(M.derived(), idx, cmp_fun); return idx; } If I set std::execution::par i get wrong result like in the picture: With std::execution::seq and the same data the graph non-decreasingly grows in steps (correct result). What should I know about execution policy to avoid such situations? EDIT: my implementation for sort_rows that now works with std::execution::par and doesn't use recursion anymore: template <typename D> void _sort( const D &M, Eigen::VectorX<ptrdiff_t>& idx, std::function<bool(ptrdiff_t, ptrdiff_t)> cmp_fun) { // initialize original index locations idx = Eigen::ArrayX<ptrdiff_t>::LinSpaced( M.rows(), 0, M.rows()-1); std::stable_sort(std::execution::par, idx.begin(), idx.end(), cmp_fun); } /// \brief sort_rows sorts the rows of a matrix in ascending order /// based on the elements in the first column. When the first column /// contains repeated elements, sortrows sorts according to the values /// in the next column and repeats this behavior for succeeding equal values. /// M_sorted = M(ind, Eigen::all) /// \param M /// \return ind template <typename D> Eigen::VectorX<ptrdiff_t> sort_rows(const Eigen::DenseBase<D> &M){ // initialize original index locations Eigen::VectorX<ptrdiff_t> idx; std::function<bool(ptrdiff_t, ptrdiff_t)> cmp_fun; cmp_fun = [&M]( const ptrdiff_t& row1, const ptrdiff_t& row2)->bool { ptrdiff_t N = M.cols()-1; for (ptrdiff_t col = 0; col < N; col++){ if (M(row1, col) < M(row2, col)) return true; if (M(row1, col) > M(row2, col)) return false; } // notice the operator is '<=' as it is the last column check // i.e. when all other columns are equal at these rows if (M(row1, Eigen::last) <= M(row2, Eigen::last)) return true; return false; }; _sort(M.derived(), idx, cmp_fun); return idx; }
Here is my implementation of rowsort. I find the documentation of rowsort somewhat confusing. I work under the assumption that it is just a lexicographical sort. Note that your code can probably be fixed just by making a col variable local to your lambda instead of having it as a shared reference. template<class Derived> void rowsort(Eigen::MatrixBase<Derived>& mat) { using PermutationMatrix = Eigen::PermutationMatrix<Derived::RowsAtCompileTime>; PermutationMatrix permut; permut.setIdentity(mat.rows()); auto& indices = permut.indices(); std::stable_sort(std::execution::par, indices.begin(), indices.end(), [&mat](Eigen::Index left, Eigen::Index right) noexcept -> bool { const auto& leftrow = mat.row(left); const auto& rightrow = mat.row(right); for(Eigen::Index col = 0, cols = mat.cols(); col < cols; ++col) { const auto& leftval = leftrow[col]; const auto& rightval = rightrow[col]; if(leftval < rightval) return true; if(leftval > rightval) break; } return false; }); mat = permut.inverse() * mat; } Notes: There might be a clever way to avoid inverting the permutation. It's a bit annoying that applying the permutation is only defined for MatrixBase, not DenseBase stable sort isn't necessary for this. I assume you have an external reason for using it The function should probably take the matrix as a const reference so that it can be called seamlessly with block() expressions and then cast away the const. I didn't put it in to avoid making the code ugly and confusing. Refer to the relevant chapter in the documentation on passing Eigen types to functions
73,259,322
73,259,464
Is there any way to check, from a .hpp file, if C stdio functions are used in the corresponding .cpp file?
I have the following question. Supposing I have an header file header.hpp which is include in a test.cpp file. Is it possible to add instructions to the header.hpp file in order to check (maybe at compile time) if some C stdio functions are used in the test.cpp file and in positive case do something specific? For example something like: header.hpp: #ifndef HEAD #define HEAD #include <iostream> if ( C stdio functions are used in test.cpp ){ std::cout << "Hey" << "\n"; } #endif test.cpp #include "header.hpp" #include <cstdio> int main(){ printf( "Hello\n" ); // C stdio function has been used. } Output: Hello Hey
No, this is not possible. Neither C++, nor C, work like this, on a fundamental level. An #include is logically equivalent to physically inserting the contents of the included file into the including file. Doing a cut and paste of your header.hpp into the beginning of your test.cpp replacing the #include accomplishes exactly the same thing. The resulting code gets compiled from beginning to the end, in order. When reading the header file, the C++ compiler has no knowledge, whatsoever, of something it hasn't read yet. An #include stops reading the file that it's in, and the included file gets read and compiled, before proceeding.
73,259,369
73,262,136
Why my clangd in vscode will change my header file's order to alphabetical order when I was fomating doc?
I found my clangd plugin in VSCode will modify *.h file's order to alphabetical order. For example: before: -#include "c.h" -#include "b.h" -#include "a.h" after: +#include "a.h" +#include "b.h" +#include "c.h" And here is my clangd's settins,How do I fix this bug. "clangd.onConfigChanged": "restart", "clangd.arguments": [ "--clang-tidy", "--clang-tidy-checks=performance-*,bugprone-*", "--compile-commands-dir=${workspaceFolder}/.vscode/", "--background-index", "--completion-style=detailed", "--enable-config", "--fallback-style=Mozilla", "--function-arg-placeholders=false", "--all-scopes-completion", "--header-insertion-decorators", "--header-insertion=iwyu", "--log=verbose", "--pch-storage=memory", "--pretty", "--ranking-model=decision_forest", "--cross-file-rename", "-j=16" ], "clangd.checkUpdates": false,
Clangd formats your code using clang-format (or more precisely, the LibFormat library that's also used by clang-format), and respects the configuration found in the .clang-format file in the project's root directory (or a subdirectory). See https://clang.llvm.org/docs/ClangFormatStyleOptions.html for the various formatting options supported by clang-format. The one relevant to your question is SortIncludes.
73,259,764
73,283,608
Downcasting to furthest subclass when calling templated function
I use LuaBridge to import a large framework of classes into a Lua-accessible framework. LuaBridge uses complex template functions that maintain a list of linkages back to methods and properties of each class. The Lua language itself is loosely typed, and it does not check to see if a method or property exists until you call it. My framework implements a ClassName method at every level that allows the Lua programs to know which class it is dealing with. That's just background for my program. This is a C++ question. I would like to call a function that, in its broadest abstraction, looks something like this: template <typename T> do_something_in_lua(T * object); // LuaBridge will create a pointer to a T instance in Lua and call it like this: class foobase { public: void notify_lua() { do_something_in_lua(this); } }; class foo : public foobase { public: int some_method(); }; foo x; x.notify_lua(); My question is, is there a simple way for do_something_in_lua to use the maximally downcasted version of T? Either when I call it or in the templated function? Using dynamic_cast is difficult because I would have to maintain an explicit list of every possible subclass to find the right one. Even if it is adding a templated virtual function in foobase that returns the desired type of this, I would be interested in suggestions for an elegant solution. I guess a broader version of my question would be, does modern C++ provide any tools for downcasting in template programming (e.g., in type_traits or the like) that I should be investigating?
Thanks to several helpful comments, the solution turns out to be a hybrid of CRTP and Double Dispatch. Here is a version of it based on my example above. I like the fact that it requires no pure virtual functions does not require templatizing the base class (for reasons specific to my code base) If I ever need to add a new subclass, I just need to add it to the list in the std::variant, and better yet, the compiler will complain until I do so. template <typename T> void do_something_in_lua(T * object); // every subclass of foobase must be listed here. class foosub1; class foosub2; using foobase_typed_ptr = std::variant<foosub1*, foosub2*>; class foobase { foobase_typed_ptr _typedptr; public: foobase(const foobase_typed_ptr &ptr) : _typedptr(ptr) {} void notify_lua() { std::visit([](auto const &ptr) { do_something_in_lua(ptr); }, _typedptr); } }; class foosub1 : public foobase { public: foosub1() : foobase(this) {} int some_method1(); }; class foosub2 : public foobase { public: foosub2() : foobase(this) {} int some_method2(); }; // and to call it in code: foosub2 x; x.notify_lua(); // now Lua gets called with a foosub2* instead of a foobase*.
73,260,357
73,260,475
Multiple Recursion Calls
#include <iostream> using namespace std; int y(int i){ cout<<i<<endl; i++; if(i==10){ return 10000000; } int left=y(i); int right=y(i)+1; return right; } int main() { cout<<y(1); return 0; } In this code after left(9) has executed shouldn't "i" come out of the stack and execute right(1) ?But while debugging I have noticed that right(9) gets executed.Could someone please explain this to me.Thank you in advance.
Execution doesn't come out of the stack. Each return removes one call. so when i==9 the call in int left=y(9) will be followed by the call in int right=y(9)+1 because i==9 still. Only then will the call to y(8) return and so on through y(7),y(6) and so on down to the original call in main() of y(1). Like any stack structure it is unloaded in the reverse order it's built. Personally I think of those clever plate dispensers where the weight of the plates is balanced by a spring. When you call a function you create a new local environment (put a new plate on the stack) and a function returns the top plate is discarded. When you discard the bottom plate you're returning from main() and the program finishes. Imagine y(9) printed on the top plate and y(8) on the one underneath. At the end is a instrumented version of the code showing the stack size and number of calls made. #include <iostream> int y(int i,char from,int &calls,int &stack){ ++calls; ++stack; std::cout<<"entering y("<< i<<','<<from<<") "<<calls<<' '<<stack<<'\n'; i++; if(i==10){ std::cout<<"returning "<<10000000<<" from y(" << i<<','<<from<<") [1]\n"; --stack; return 10000000; } int left=y(i,'l',calls,stack); int right=y(i,'r',calls,stack)+1; std::cout<<"returning "<<right<<" from y(" << i<<','<<from<<") [2]\n"; --stack; return right; } int main() { int calls{0}; int stack{1};//We're in main(). std::cout<<y(1,'m',calls,stack); return 0; }
73,260,538
73,260,833
Passing C++ lambda as argument to non templated function
As I googled std::function works slower than simple lambda function. Consider the following use case will there be std::function penalty when using stl sorting algorithms (v vector may be big enough and occupy about N*GB of data): #include <iostream> #include <functional> #include <algorithm> #include <vector> using namespace std; void sorter(std::vector<int>& v, std::function<bool(int a, int b)> f){ std::sort(v.begin(), v.end(), f); } int main() { std::vector<int> v = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; for (auto val : v) cout << val << " "; cout << endl; int c = 4; auto f = [&c](int a, int b){ return a+b < c; }; sorter(v, f); for (auto val : v) cout << val << " "; cout << endl; return 0; } As you can see I create the lambda function f and pass it to a sorter function. My task is to keep sorter function non-templated that is why I tried to pass lamda function as std::function. Or are there better ways of doing that?
Lambdas that do not capture anything can be converted to a function pointer with the + operator: void sorter(std::vector<int>& v, bool (*cmp)(int,int)); int main() { auto const cmp = +[](int a, int b) { return a < b; }; vector<int> v{3, 2, 1}; sorter(v, cmp); } But if it does capture something, you should either make it a template, or use std::function. No way around that.
73,260,680
73,260,803
How can I set value of a variable to an amount that is more than unsigned long long maximum value in C++?
I know that The maximum value for a variable of type unsigned long long in C++ is: 18,446,744,073,709,551,615 but I don't know that how can I set value of a variable to an amount that is more than 18,446,744,073,709,551,615?
maybe you can use __int128,the only problem is that you can't use cin,cout or printf but you can write a function like that: //output inline void write(__int128 x) { if(x<0) putchar('-'),x=-x; if(x>9) write(x/10); putchar(x%10+'0'); } //input inline __int128 read() { __int128 X=0,w=0; char ch=0; while(!isdigit(ch)) {w|=ch=='-';ch=getchar();} while(isdigit(ch)) X=x*10+(ch-'0'),ch=getchar(); return w?-X:X; }
73,261,703
73,276,722
Use NVIDIA GPUDirect RDMA with nvJPEG
Is that possible to use NVIDIA GPIDirect RDMA with NVIDIA nvJPEG? From the description of RDMA technology that should be possible but seems nvJPEG interfaces expect only host memory input.
Nvidia nvJPEG uses a hybrid approach for JPEG decoding. Some of the code is executed on the CPU, some of it on the GPU. See especially the decoupled functions https://docs.nvidia.com/cuda/nvjpeg/index.html#nvjpeg-decoupled-decode-api So, no, it is not possible.
73,261,993
73,262,033
A linear-time algorithm that rearrange negative and positive integers with zeroes in between
Problem: Array has positive, negative, and 0 integers, and values are not necessarily unique. The positive values are to the right of zeroes, and the negative values are to the left of zeroes. The positive and the negative values do not have to be sorted. However, the zeros must be in between the positive and negative integers. The algorithm must run in linear time. Some acceptable answers I can think of are the following: [-3, -1, -9, 0, 5, 2, 9] [-5, -2, 0, 0, 5, 2, 9] [-3, 0, 0, 0, 4, 1] My thought process and attempts: The process is very similar to the quicksort algorithm where we can choose 0 to be our pivot point. Ideally, this shouldn't be an issue because we can simply search for the index of 0 and set that index as our pivot point to replace at the end. However, from what I understand the search process itself requires at least O(nLog(n)) run time (such as binary search), and therefore cannot be used in this case. One extreme solution to this that I can think of that runs in a linear time is using the linear select algorithm where we split the array into subgroups of 5 and find the median of the medians of the subgroups. However, I doubt this will work since the median isn't always going to be 0, therefore the pivot point isn't always guaranteed to be 0. What's really throwing me off in the problem is that the negative and positive integers do not have to be sorted but simultaneously must be partitioned by zeroes. What I have so far: I was able to modify the partitioning process of the quick sort algorithm. The following runs in a linear time, but the problem is that it is not able to place the zeroes in the appropriate positions. This is the output that I am able to get with the current progress I have: void partition(T a[], int lo, int n) { size_t i = lo, j; for (j = i; j < n; j++){ if (a[j] < 0){ std::swap(a[i], a[j]); i++; } } } Using array of [9, -3, -6, 1, 3,4,-22,0] Output of the code is [ -3 -6 -22 1 3 4 9 0 ] Thank you very much in advance for any feedback that you may have.
A simple linear algorithm in two iterations can be to first push all negative numbers to the left, and in a second iteration push all positives numbers to the right. void rearrange(T a[], int n) { int next_to_place= 0; for (int i = 0; i < n; i++) { if (a[i] < 0) { std::swap(a[i], a[next_to_place++]); } } for (int i = next_to_place; i < n; i++) { if (a[i] == 0) { std::swap(a[i], a[next_to_place++]); } } } This is suboptimal, as you can probably solve it with a single iteration (which will be more cache friendly), but it is linear and simple to understand.
73,262,060
73,265,079
Why is my regex C++ expression not working?
I have the following regex expression: \\(([^)]+)\\) (don't take into account the double brackets it's because of C++) and the following code: if (in_str.find("(") != string::npos) { print(to_string(countMatchInRegex(in_str, "\\([^ ]*\\.[^ ]*\\)"))); for (int i = 0; i < countMatchInRegex(in_str, "\\(([^)]+)\\)"); ++i) { regex r("\\(([^)]+)\\)"); smatch m; regex_search(in_str, m, r); string obj = m.str(); obj = obj.substr(1, obj.length() - 2); string property = obj.substr(obj.find(".") + 1); obj = obj.substr(0, obj.find(".")); in_str = replace(in_str, m.str(), process_property(obj, property)); } } This code is supposed to find, in a string, substrings like the following: (something.somethingelse). It works fine, except it only works two times...but i don't know how. I do know the problem is not the countMatchInRegex function, because I've printed what it results the correct number of substrings that match the regex expression in the string. If anyone has any idea, please share them, I've been stuck on this for weeks..
I actually found the error, I don’t know why but C++ was returning different values for the two countMatchInRegex so all I did was assign it to a variable and use the variable instead every thing the function was called in the code.
73,262,668
73,262,708
Range Based Loop C++
How would you implement a class in C++ using constant time and constant space such that the following would work? for (auto &x : Range{0, 10}) { cout << x << " "; } My initial idea was to create a vector but wasn't constant space. Curious how this would be done.
For a range-based for loop to work, you need: begin() returning an iterator end() returning an iterator On the iterator, you need: operator!=() to compare at least against end() operator++() to increment the loop iterator operator*() for dereference of the iterator So you'll need to implement two classes: Range and the corresponding iterator. Loop starts at it = begin() and goes while it != end() (technically, end() is evaluated only once per loop, stored and we compare against the stored value); in each loop, it's dereferenced as *it and after the body, incremented as ++it;.
73,263,172
73,272,414
fatal error LNK1104: cannot open file 'kernel32.lib' in Visual Studio 2019
I'm using Visual Studio 2019 and I got an error even my PATH has kernel32.lib path. C:\Users\googi\Desktop\CMakeProject2\out\build\x64-debug\CMakeProject2\LINK : fatal error LNK1104: cannot open file 'kernel32.lib' ninja: build stopped: subcommand failed. PATH... c:\Program Files (x86)\Windows Kits\10\Lib\10.0.19041.0\um\x86 And if I try to run on Command Prompt, it says... This file does not have an app associated with it for performing this action. Please install an app or, if one already installed, create an association in the Defalt Apps Setting page. I tried other these 3 paths but it gave me exact same errors. C:\Program Files (x86)\Windows Kits\10\Lib\10.0.19041.0\um\arm C:\Program Files (x86)\Windows Kits\10\Lib\10.0.19041.0\um\arm64 C:\Program Files (x86)\Windows Kits\10\Lib\10.0.19041.0\um\x64
About your case, I suggest you check these things below: Check if you have installed the Windows SDK for your version. Check if $(WindowsSdkDir)\lib is included in the directories list, if not, manually add it. Check if the value of WindowsSdkDir is correct.
73,263,255
73,364,675
Qt Android blank window
Problem I have a problem with Qt on Android in all my applications: after I close the QFileDialog (code below), I have a blank black window. I can't do anything in the application except close it. Here is the code I use: QFileDialog dialog(this, tr("Open Markdown File")); dialog.setMimeTypeFilters({"text/markdown"}); dialog.setAcceptMode(QFileDialog::AcceptOpen); if (dialog.exec() == QDialog::Accepted) { const QString file = dialog.selectedFiles().at(0); if (file == path || file.isEmpty()) return; openFile(file); } Informations My Qt version is Qt 6.2.4 Device running on: Samsung Galaxy S10e arm64-v8 build JDK version 17 SDK-Version: 7.0 NDK-Version: 22.1.7171670 C++ version 17 Edit Here a Screenshot what I see: Edit 2 After some more debugging i figured out, that it reaches the end of the code. I also tried to add Q[Core|Gui]Application::processEvents() and QMainWindow::repaint() but i istill have the blank screen as you cas see in the screenshot above. Edit 3 The Code is in a QMainWindow and is executed in the main thread. The APP has a QApplication object. After the end of the code is reached, the main thread aka main event loop runs as usual, but I have a black window. You can find all the code on GitHub, but only the part I showed causes problems.
Works well on my configuration: Samsung Note 20, Android 12, latest update, Qt 6.3.1, clang arm64-v8a, SDK 7.0, NDK 22.1.7171670. Demo: https://youtube.com/shorts/KkyrTYkTNb0?feature=share. Your app open and save file well, FileDialog works well too. So no assumptions about the reasons you see blank screen: may be phone software version, may be some feature of your Qt version. I did several changes in your project however to be able to read and write files on android: Created Android build files Added READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions to manifest. Added setDirectWriteFallback(true) to mainwindow.cpp: 1139: QSaveFile f(path, this); 1140: f.setDirectWriteFallback(true); //!!! 1141: if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) { ... otherwise file created, but I had an error on f.commit():
73,263,346
73,263,397
Can reverse iterators be used in place of forward iterator parameters?
Looking at the function parameters for std::generate() the parameters say that this function only takes forward iterators: I'm having a hard time understanding why this code is compiling: #include <iostream> #include <vector> #include <algorithm> using namespace std; void printer(int i) { cout << i << ", "; } struct Sequence { int start; Sequence(int start) :start(start) { } int operator() () { return start++ % 7; } }; int main() { vector<int> v1(4); generate(v1.rbegin(), v1.rend(), Sequence(10)); // Line I for_each(v1.begin(), v1.end(), printer); } Outputs 6, 5, 4, 3, My understanding is that std::generate takes two parameters that need to both be forward iterators. And looking at the documentation for rbegin() and rend(), they both return reverse iterators. Is there some type of implicit conversion that allows these reverse iterators to act as Forward Iterators? At first, I suspected that the .base() part of these iterators may be at play generate(v1.rbegin().base(), v1.rend().base(), Sequence(10)); //Line II This compiles but throws an error at run time (Which makes complete sense). I also tried generate (v1.rend().base(), v1.rbegin().base(), Sequence(10)); // LINE III Output : 3, 4, 5, 6, This compiles and runs but isn't equivalent to my original output (Line I), so this isn't what is happening. Any help or input would be greatly appreciated.
You know what, reverse-iterators can be forward-iterators too! Specifically, the term reverse-iterator means that they go reverse to the "natural" direction. The term forward-iterator names a concept, which guarantees among others that you can make a copy of an iterator, and copy and original can be independently used to iterate the sequence, and look at the elements, however often you want. Take a good look at it, and you will see that while both are based on the concept iterator, and while they add different additional requirements, those are not contradictory. Actually, whenever you have a reverse-iterator, they are normally automatically derived by decorating a bidirectional iterator (which is a forward-iterator), though that is not quite a requirement.
73,263,604
73,263,682
How to pass in a dynamically allocated array as an argument to a function
So I created a dynamically allocated array of structs pretend that structtype is the name of the struct, and arr is the array. structtype * arr; arr = new structtype[counter+15]; Then I attempted to pass that array of structs into multiple types of functions with prototypes such as: void read_info(structtype (&arr)[15], int integer); and void Append(structtype arr[15]); In turn I got these errors: error: cannot convert ‘structtype’ to ‘structtype (&)[15]’ and error: cannot convert ‘structtype**’ to ‘structtype (&)[15]' Can yall help me figure out how to get rid of these errors, for example dereferencing the pointer part of the array or something.
Your array is somewhere in memory, location which is pointed by the actual variable arr the pointer. The array is therefore represented by the pointer, however the pointer carries no information about where the array ends or its size, unlike std::vector<>. So you need to pass it with the known size as in: #include <cstdio> struct structtype { int a; }; void dosomething( structtype* s, int size ) { for ( int j=0; j<size; ++j ) { printf( "s[%d]=%d\n", j, s[j] ); } } int main() { int counter = 50; structtype * arr; arr = new structtype[counter+15]; dosomething( arr, counter + 15 ); delete arr; } Godbolt: https://godbolt.org/z/95P5d4sfT
73,263,701
73,263,773
Is there a way to have a member parameter type be a pointer to a derived class
I'm writing a module system for my program, where individual modules are initialised and shutdown by a system. how this works is I call an Init() function that will initialise a static pointer of the class. this works and is fine, however: I would like to abstract this into a class so the api is easier to maintain, but I don't know how to change the pointer type of the derived class automatically for example, if I have the base class IModule: class IModule { public: protected: result Init(); result Shutdown(); private: static IModule* s_instance; }; is there a way I can write this class so that the derived class can be written as class Derived : public IModule { protected: result Init(); result Shutdown(); } and have Derived::s_instance evaluate to a Derived*
No, you can't have a variable whose type depends on the type of this. However, you can have a variable whose type depends on a template parameter. template <typename T> class IModule { private: static T* s_instance; }; class Derived : public IModule<Derived> { // The s_instance in this class is of type Derived*. } This is called the curiously recurring template pattern and it's used to do all sorts of tricks in C++. It may not work for your use case (for instance, you can no longer have a list of IModule which all have different derived types), but depending on what exactly you're doing this may be the way to go.
73,263,739
73,263,882
Construct vector of certain size
Trying to construct a class attribute - a vector of certain size class cTest { public: std::vector<double> myTable(1900); }; main() { cTest test; return 0; } compiler says: ./src/main.cpp:43:33: error: expected identifier before numeric constant 43 | std::vector<double> myTable(1900); | ^~~~
This: std::vector<double> myTable(1900); Looks like a member function declaration, and function declarations expect an argument list. 1900 does not satisfy that. There are a couple of ways to solve this: class cTest { public: std::vector<double> myTable = std::vector<double>(1900); }; If you want to make this a little less obnoxiously verbose: class cTest { using dbl_vec = std::vector<double>; public: dbl_vec myTable = dbl_vec(1900); }; Or using the member initializer list in a constructor: class cTest { public: std::vector<double> myTable; cTest() : myTable(1900) { } };
73,263,875
73,263,887
I'm trying to calculate the area of the triangle, but keep getting area = 0
I'm trying to calculate the area of a triangle, but keep getting 0. What am I doing wrong? #include <iostream> using namespace std; int main() { int area, base, height; area = (1/2)*base*height; cout << "Enter the base: "; cin >> base; cout << "Enter the height: "; cin >> height; cout << "The area is: " << area << endl; }
You're trying to calculate the area before you know the base and height. So the answer is going to be undefined, because base and height haven't been set (depending on how your compiler does things, it may set unknown variables to 0, or it may let them be random values. Either way it won't work). Wait until after the user enters the number to do the calculation.
73,264,027
73,264,736
ranges and temporary initializer lists
I am trying to pass what I think is a prvalue into a range adapter closure object. It won't compile unless I bind a name to the initializer list and make it an lvalue. What is happening here? #include <bits/stdc++.h> using namespace std; int main(){ //why does this compile? auto init_list = {1,2,4}; auto v = init_list | views::drop(1); //but not this? // auto v2 = initializer_list<int>{1,2,4} | views::drop(1); //or this? //auto v3 = views::all(initializer_list<int>{1,2,4}) | views::drop(1); }
When you use r | views::drop(1) to create a new view, range adaptors will automatically convert r into a view for you. This requires that the type of r must model viewable_range: template<class T> concept viewable_­range = range<T> && ((view<remove_cvref_t<T>> && constructible_­from<remove_cvref_t<T>, T>) || (!view<remove_cvref_t<T>> && (is_lvalue_reference_v<T> || (movable<remove_reference_t<T>> && !is-initializer-list<T>)))); Note the last requirement: (is_lvalue_reference_v<T> || (movable<remove_reference_t<T>> && !is-initializer-list<T>)))); Since the type of r doesn't model a view, which in your case is initializer_list, it needs to be an lvalue, allowing us to freely take its address to construct a ref_view without worrying about dangling. Or, we need it to be movable, which allows us to transfer its ownership to owning_view, which means the following is well-formed: auto r = std::vector{42} | views::drop(1) But in this case, we also need it not to be a specialization of initializer_list, because we can't transfer ownership of it, initializer_list always copy. That's why your example fails.
73,264,448
73,264,739
Compare goldbolt and MSVC C++ version
I have written some code that compiles on godbolt, but does not compile in Microsoft Visual Studio. I am trying to figure out why. My first step was to compare compiler versions. On goldbolt, I am compiling the code using "x64 msvc v19.latest." I googled "how to check msvc version," and all of the directions I can find lead me to the MSVS version, which is 17.2.6. How can I find my MSVC version that is comparable to the godbolt version?
You can look up version numbers here: Microsoft Visual C++ - Internal version numbering. Godbolt uses _MSC_VER separated by a dot, e.g. 1914 is 19.14 on Godbolt.
73,264,873
73,264,912
error: assigning to 'subhook_t' (aka 'subhook_struct *') from incompatible type 'void *'
I've solved 6 different errors, but no matter how far I look I keep hitting a dead end with this one error in a subhook code written in c. ./subhook_x86.c:470:10: error: assigning to 'subhook_t' (aka 'subhook_struct *') from incompatible type 'void *' hook = calloc(1, sizeof(*hook)); ^~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated. For context, hook is declared as subhook_t hook;
Unlike C, C++ doesn't allow automatic conversions from void * to other types. You need to use an explicit cast. hook = static_cast<subhook_t>(calloc(1, sizeof(*hook)));
73,265,141
73,265,181
Is there any restriction in returning std::function from a function within a class
If I enable line number 4 in below code then I end up in getting compilation error , while I am doing same thing (calling getFp1) outside the class and that works perfectly fine . **Compilation Error** : In member function 'std::function<void(std::__cxx11::basic_string<char>)> testClass::getFp()': Practice.cpp:23:14: error: cannot convert 'testClass::myTestFunction' from type 'void (testClass::)(std::string)' {aka 'void (testClass::)(std::__cxx11::basic_string<char>)'} to type 'std::function<void(std::__cxx11::basic_string<char>)>' 23 | return myTestFunction; | ^~~~~~~~~~~~~~ Code #include <iostream> #include <functional> #include <string> //#define CLASS 1 -------------> Enabling this throws compilation error (?) using namespace std; void printMessage(string str){ cout << str << endl; } void testFunction(std::function<void(std::string)> fp,string s){ fp(s); } #ifdef CLASS class testClass { public : void myTestFunction(std::string s){ cout << s << endl; } public : std::function<void(std::string) > getFp(){ return myTestFunction; } }; #endif std::function<void(std::string) > getFp1(){ return printMessage; } int main(){ std::function<void(string)> fp = printMessage; fp("Whats up !!") ; testFunction(fp,"All is Well"); #ifdef CLASS testClass t ; auto fp1 = t.getFp(); fp1("Calling Private Method ?"); #endif auto fp2 = getFp1(); fp2("Great !!"); return 0; } ============================
This is a variation on the member functions are not regular functions question we get so often. Your code can be made to work like this public : std::function<void(testClass&,std::string) > getFp(){ return &testClass::myTestFunction; } }; and to call this method testClass t ; auto fp1 = t.getFp(); fp1(t, "Calling Private Method ?"); Not sure if this is acceptable to you or not.
73,265,199
73,265,236
Undefined symbols for architecture x86_64: referenced from subhook-9679a6.o
Error: "subhook_unprotect(void*, unsigned long)", referenced from: _subhook_new in subhook-9679a6.o ld: symbol(s) not found for architecture x86_64 Linking command: g++ -dynamiclib -fPIC -v -o finalcalling.dylib finalversion.cpp /Users/~/Desktop/c/subhook-master/subhook.c -std=c++11 After going through my code I found that subhook_unprotect(void*, unsigned long) is not even in my code.
If this is your code https://github.com/Zeex/subhook then it seems you are supposed to also include subhook_unix.c in your build. That file does define subhook_unprotect. So does subhook_windows.c but I'm assuming you are on a unix like platform.
73,265,364
73,265,442
If condition evaluates to false on changing the sequence of conditions. (C++)
I am trying to solve the "Find Number of Islands in a 2D matrix" problem and I am using DFS technique to count the number of adjacent 1's in the matrix. In the dfs() function, the condition - if( (arr[i][j]=='0') || i<0 || j<0 || i==r || j==c) evaluates to false when (arr[i][j] == '0') condition is written first in sequence but when written like this - if(i<0 || j<0 || i==r || j==c || (arr[i][j]=='0')) it evaluates to true. This condition is used to check whether the current values of i and j are not out of bounds and that the element arr[i][j] of the matrix is not equal to '0'. The code: class Solution { public: void dfs(vector<vector<char>>& arr, int i, int j, int& r, int& c){ if( (arr[i][j]=='0') || i<0 || j<0 || i==r || j==c) return; // MARKED VISITED arr[i][j] = '0'; dfs(arr,i,j+1,r,c); dfs(arr,i,j-1,r,c); dfs(arr,i+1,j,r,c); dfs(arr,i-1,j,r,c); } int numIslands(vector<vector<char>>& arr) { int rows=arr.size(); if(rows==0){return 0;} int cols=arr[0].size(); int numOfIslands=0; int i=0; int j=0; int r=arr.size(); int c=arr[0].size(); for( i=0;i<r;i++){ for( j=0;j<c;j++){ if(arr[i][j]=='1'){ dfs(arr, i , j,r,c); numOfIslands++; } } } return numOfIslands; } }; This code works only when the element in the matrix is '1' but terminates when element '0' is encountered. Will someone please explain the reason for the failure of the if condition?
Operator || (and similarly operator &&) are always evaluated left to right, and evaluation stops when the result is known. So if the left hand side of || is true then the right hand side is not evaluated. This is known as short circuit evaluation. So suppose that i equals -1 in this expression (arr[i][j]=='0') || i<0 || j<0 || i==r || j==c then you access arr[-1][j] and that is an out of bounds array access which means your program has undefined behaviour, so the expression could evaluate to anything, or could even crash. But in this expression i<0 || j<0 || i==r || j==c || (arr[i][j]=='0') i<0 evaluates to true, so the whole expression is true, and the remaining clauses of the expression are unevaluated. So you avoid the undefined behaviour of the first version and you get the correct result of true.
73,265,397
73,267,609
How to initialize non-const member variable with const value
struct IntSlice { int* ptr_; int len_; }; std::initializer_list<int> xs = {1, 2, 3}; const IntSlice s = {xs.begin(), (int)xs.size()}; // this does not work :( It is giving me an error, that we cannot assign a const pointer to a non const pointer but I thought the declaration const IntSlice would fix that. I think I know what's going on. const IntSlice is promoting int* ptr_ to int* const ptr_ not const int* const ptr_ which is what I want. But surely, there has to be some way to promote int* ptr_ to const int* without having to create a ReadonlyIntSlice?
IntSlice is too specific. It works only with (mutable) int slices. Why not have something that works with any type of slice? template <typename T> struct Slice { T* ptr_; std::size_t len_; }; Now you can have Slice<int>, Slice<const int>, Slice<const * const double> and whatever else you fancy. std::initializer_list<int> xs = {1, 2, 3}; Slice<const int> s = {xs.begin(), xs.size()}; In C++17, if you add an appropriate constructor or a deduction guide, you can omit the template argument. template <typename T> Slice(T* ptr, std::size_t len) -> Slice<T>; Slice s = {xs.begin(), xs.size()};
73,265,851
73,265,893
Why C++ friendship for function inside a class does not work same as a standalone function?
I want to know why one of the following two codes compiles while the other does not. In the first code, createB is a stand alone function. In the second code the function createB is a member of class A. The first one compiles. #include <iostream> class A; class B { public: B() { std::cout << "B"; } friend B createB(); }; class A { public: A() { std::cout << "A"; } }; B createB() { return B(); } int main() { A a; B b = createB(); } The second one does not. #include <iostream> class A; class B { public: B() { std::cout << "B"; } friend B A::createB(); }; class A { public: A() { std::cout << "A"; } B createB() { return B(); } }; int main() { A a; B b = a.createB(); }
Case 1 In the first snippet, createB is a free(standalone) function and it is not mandatory that the friend declaration names an existing function. So this works and also implicitly declares a function named createB with return type of B in the global namespace, though this createB is not visible through ordinary lookup. Case 2 The problem in the 2nd example is that A is an incomplete at the point of the friend declaration friend B A::createB();. To solve this, we can move the definition of A to before B so that A is complete at the point of the friend declaration. Additionally, we can provide the definition of createB after B has been defined as shown below: //forward declaration so that B can be used in declaration B createB(); class B; class A { public: A() { std::cout << "A"; } //this is declaration B createB(); }; class B { public: B() { std::cout << "B"; } friend B A::createB(); //this works as now at this point A is complete since we moved the definition of A to before B }; //this is definition B A::createB() { return B(); } int main() { A a; B b = a.createB(); } Working demo
73,265,936
73,266,010
Why my header files can't correctly index each other's declaration dependency with clangd in VSCode?
I'm now codeing C/C++ in VSCode with clangd.There are some annoying problems.For example,I defined a variable in "a.h",which also used in "b.h".But it will error in b.h with: "Unknown type name 'xxxxx'clang(unknown_typename)". Actually it doesn't affect the compliling results,But always lots of annoying red waves there. //in "a.h" typedef unsigned long uint64; //in "b.h" uint64 abc; //Error here: (Unknown type name 'uint64'clang(unknown_typename) //in "xxx.c" #include "a.h" #include "b.h" abc=1; // Correct here I have only used "complile_commands.json" to configure clangd.It's run good that I can easily jump to definition or declaration.Is there anything more for clangd I need to configure? (PS: here is my clangd's settins) "clangd.onConfigChanged": "restart", "clangd.arguments": [ "--clang-tidy", "--clang-tidy-checks=performance-*,bugprone-*", "--compile-commands-dir=${workspaceFolder}/.vscode/", "--background-index", "--completion-style=detailed", "--enable-config", "--function-arg-placeholders=false", "--all-scopes-completion", "--header-insertion-decorators", "--header-insertion=never", "--log=verbose", "--pch-storage=memory", "--pretty", "--ranking-model=decision_forest", "--cross-file-rename", "-j=16" ], "clangd.checkUpdates": false,
This has nothing to do with VScode or clangd. Instead, the problem is that in file b.h you have not included a.h and thus uint64 is unknown at the point where you're using it uint64 abc;. To solve this, you need to include a.h before using uint64: a.h #pragma once typedef unsigned long uint64; b.h #pragma once #include "a.h" //added this uint64 abc; //works now
73,266,301
73,267,217
noexcept, third party and STL calls
I'm trying to understand when I should use noexcept and when I should not. In my library, I have many methods. Some are using methods from third party, some are using the STL. Some use throw, some don't. I can put noexcept statements on all my methods, the compiler just do not complain at all. But I do. I can check my own throws to know if I should put a noexcept on a method, but am I supposed to check every signature of the STL methods and third party methods to know if I should put a noexcept ? I could do that but that seems inefficient, am I missing something here ? example code where I should NOT use noexcept if my understanding is correct: foo::foo() noexcept { this->BarPtr = std::make_unique<Bar>(); }
You don't have to chase down anything. If you aren't sure about exceptions being thrown, then your method is "potentially throwing". That's the term used by the standard for operations that are not noexcept. So don't mark your method if you aren't sure, it's only honest (lack of) advertisement. That's not to say you should never be bothered about it. For example, move operations that are noexcept can enable/optimise the use of certain standard containers. So if you are writing a custom one, it's worthwhile to try and determine if you can mark things noexcept1. 1 - As an anecdote, I dealt once with a class that held a member of a type that was written for C++03. The semantics of the type did permit throwing (it had a narrow contract) for invalid inputs or copies thereof, but we only generated valid ones. So I marked the move operations noexcept to facilitate use of a standard container that was appropriate.
73,266,969
73,267,216
Spinning words, but cannot return result in correct order
I'm writing a function that takes a string, and reverses all the space-separated words that are longer than 5 characters. e.g. the expected output for an input string "Hey fellow warriors" should be "Hey wollef sroirraw" Currently with my code I'm getting the result "sroirraw Hey wollef" which spins the words that are longer than 5 characters, however they don't print in the correct order. I assume that this is happening because of how the assignment of the string being split is done and how they are printed. I initialized y to x cause initially I was not using a vector to store the words. I was hoping to run a check if words were longer than 5 then it would reverse it, add a blank space, continue the loop for the string, join the string and return the joint string. std::string spinWords(const std::string &str) { std:: string x = ""; std:: string y = ""; std::vector<std::string> words; for (int i = 0; i < str.length(); i++){ if (str[i] == ' '){ if (x.length() > 5){ std::reverse(x.begin(), x.end()); } words.push_back(x); x= ""; } x = x + str[i]; } if (x.length() > 5){ std::reverse(x.begin(), x.end()); } y = x; for (int j = 0; j < words.size(); j++){ y = y + words[j] + " "; } return y; } int main(){ std::cout << "\n\n" << spinWords("Welcome"); std::cout << "\n\n" << spinWords("Hey fellow warriors"); }
Here is some problems with your approach. You probably don't want to consider spaces as part of words, so you should't add current symbol when it is ' ': if (str[i] == ' ') { //... } else // move it to else block { x = x + str[i]; } Following your logic, you forgot to add the last word to your collection, if it is not empty: // we add probably last word only if it is not empty //empty ~ length() == 0 if(!x.empty()) { if (x.length() > 5) { std::reverse(x.begin(), x.end()); } words.push_back(x); } //Why this assigment? //y = x; for (int j = 0; j < words.size(); j++) { // use += for optimal string allocation y += words[j] + " "; } Some improvements: You can use std::stringstream to split string by spaces returns etc: #include <sstream> std::istringstream iss(str); for (std::string word; iss >> word; ) { if (word.length() > 5) { std::reverse(word.begin(), word.end()); } words.push_back(word); } You may also want to optimise string y internal reallocation. So you can accumulate overall size of all words in existing loop and reserve some memory for your result: y.reserve(totalLength); (actual for large input string)
73,267,101
73,339,980
Why can't I check for a constraints on a type using requires?
I'm trying to understand how to use Concepts to do interface checks on a type (duck typing?), and produce the most readable code. I have the following concept: template <typename T> concept Shape = requires(const T& t) { { t.area() } -> std::convertible_to<float>; }; And then use it as follows template <typename T> struct shape_checker_check_in_ctor { shape_checker_check_in_ctor() {static_assert(Shape<T>);} }; struct Circle : shape_checker_check_in_ctor<Circle> { float r; float area() const {return 22*r*r/7;} }; Which works fine, but I think having the static_assert in the constructor of the constraint checker makes its role a tad less obvious. What I'd like instead is the following, which involves less boilerplate: template <typename T> requires Shape<T> struct shape_checker_with_constraint {}; And then struct Square : shape_checker_with_constraint<Square> { double side; float area() const {return side*side;} }; But it doesn't work. Full code here: https://godbolt.org/z/GzEq54P8Y Can anyone figure out why please?
CRTP is amazing, but doesn't solve every problem. CRTP is not the right tool here. The test you need to do has to happen after the type is fully defined. You have hacked it by putting a static assert in the constructor. Here I simply put the static assert right after the class definition, when it is complete. struct Circle { float r; float area() const {return 22*r*r/7;} }; static_assert( Shape<Circle> ); struct Square { double side; float area() const {return side*side;} }; static_assert( Shape<Square> ); now in a future version of C++, we expect to get reflection and eventually (maybe) metaclasses. With metaclasses, you'd be able to do something like class(Shape) Circle { float r; float area() const {return 22*r*r/7;} }; and the metaclass Shape would perform checks and manipulation of the struct. This proposal is in its early steps and won't show up until after we have reflection (which was delayed from c++23 by the pandemic).
73,268,160
73,561,295
Large global array of vectors causing compilation error
I have a very simple C++ code (it was a large one, but I stripped it to the essentials), but it's failing to compile. I'm providing all the details below. The code #include <vector> const int SIZE = 43691; std::vector<int> v[SIZE]; int main() { return 0; } Compilation command: g++ -std=c++17 code.cpp -o code Compilation error: /var/folders/l5/mcv9tnkx66l65t30ypt260r00000gn/T//ccAtIuZq.s:449:29: error: unexpected token in '.section' directive .section .data.rel.ro.local ^ GCC version: gcc version 12.1.0 (Homebrew GCC 12.1.0_1) Operating system: MacOS Monterey, version 12.3, 64bit architecture (M1) My findings and remarks: The constant SIZE isn't random here. I tried many different values, and SIZE = 43691 is the first one that causes the compilation error. My guess is that it is caused by stack overflow. So I tried to compile using the flag -Wl,-stack_size,0x20000000, and also tried ulimit -s 65520. But neither of them has any effect on the issue, the code still fails to compile once SIZE exceeds 43690. I also calculated the amount of stack memory this code consumes when SIZE = 43690. AFAIK, vectors use 24B stack memory, so the total comes to 24B * 43690 = 1048560B. This number is very close to 220 = 1048576. In fact, SIZE = 43691 is the first time that the consumed stack memory exceeds 220B. Unless this is quite some coincidence, my stack memory is somehow limited to 220B = 2M. If that really is the case, I still cannot find any way to increase it via the compilation command arguments. All the solutions in the internet leads to the stack_size linker argument, but it doesn't seem to work on my machine. I'm wondering now if it's because of the M1 chip somehow. I'm aware that I can change this code to use vector of vectors to consume memory from the heap, but I have to deal with other's codes very often who are used to coding like this. Let me know if I need to provide any more details. I've been stuck with this the whole day. Any help would be extremely appreciated. Thanks in advance!
It does seem to be an M1 / M1 Pro issue. I tested your code on two seperate M1 Pro machine with the same result as yours. One workaround I found is to use the x86_64 version of gcc under rosetta, which doesn't have these allocation problems.
73,268,326
73,268,393
How can I check if the type `T` is `std::pair<?, bool>` in C++?
We can define a function to insert multiple values to a set like this: template <typename T, typename... U> bool insert_all(T& to, const U... arguments) { return (to.insert(arguments).second && ...); } So this code can insert 4, 5 and 6 to the set: std::set set { 1, 2, 3 }; insert_all(set, 4, 5, 6); Obviously, type T maybe a type without a method accepting int, called insert and returns std::pair<?, bool>. It's necessary to check it by SFINAE: template <typename T, typename U, typename = void> struct can_insert : std::false_type { }; template <typename T, typename U> struct can_insert<T, U, std::enable_if_t<std::is_same_v<decltype(std::declval<T>().insert(std::declval<U>())), std::pair<typename T::iterator, bool>>, void> > : std::true_type { }; template <typename T, typename U> inline constexpr auto can_insert_v = can_insert<T, U>::value; Pay attention to the second one, ...std::pair<typename T::iterator, bool>>..., how to express it like java code ? extends Pair<?, Boolean> gracefully?
It's not much different than the technique you already coded: #include <tuple> #include <type_traits> template<typename T> struct is_pair_t_and_bool : std::false_type {}; template<typename T> struct is_pair_t_and_bool<std::pair<T, bool>> : std::true_type {}; static_assert( is_pair_t_and_bool<std::pair<char, bool>>::value ); static_assert( !is_pair_t_and_bool<int>::value ); static_assert( !is_pair_t_and_bool<std::pair<int, int>>::value ); And, in C++20, once you've gone that far you might as well make it a concept: template<typename T> concept pair_t_and_bool=is_pair_t_and_bool<T>::value; template<pair_t_and_bool T> struct something {}; something<std::pair<int, bool>> this_compiles; something<std::pair<int, int >> this_doesnt_compile;
73,269,540
73,269,939
std::move between unique_ptr and another that it owns
Consider some class/struct struct Foo{ int val = 0; std::unique_ptr<Foo> child_a = NULL; std::unique_ptr<Foo> child_b = NULL; Foo(int val_):val(val_){} ~Foo(){std::cout<<"Deleting foo "<<val<<std::endl;} }; as you might construct in a doubly linked list/binary tree or similar. Now, consider that in such a list we have several such Foos which point to each other in a tree like fashion e.g. through std::unique_ptr<Foo> root = std::make_unique<Foo>(Foo(0)); root->child_a = std::make_unique<Foo>(Foo(1)); root->child_b = std::make_unique<Foo>(Foo(2)); root->child_a->child_a = std::make_unique<Foo>(Foo(3)); root->child_a->child_b = std::make_unique<Foo>(Foo(4)); root->child_b->child_a = std::make_unique<Foo>(Foo(5)); root->child_b->child_b = std::make_unique<Foo>(Foo(6)); In this context, if I write root = NULL then all the linked children get deleted and I get output that looks something like Deleting foo 0 Deleting foo 1 Deleting foo 3 Deleting foo 4 Deleting foo 2 Deleting foo 5 Deleting foo 6 My question then, is what exactly is happening when I do something like this root = std::move(root->child_a); The output in such a situation looks like Deleting foo 0 Deleting foo 2 Deleting foo 5 Deleting foo 6 leaving only the child_a branch in place of the original root as one might hope. But looking at this I realise I'm not completely sure how the std::move works under the hood here, and the "expected behavior" really seems to be taking the self-referential move for granted. I had always broadly thought that a move like this a=std::move(b); functioned very roughly as a = NULL; b.release(); a.get() = b.get(); but of course this can't be right here, because the first NULL would destruct b before it could replace the a which has just been removed. Instead I imagine something like this is happening b.release(); c = b.get(); a = NULL; a.get() = c; such that b is moved into some new raw pointer c so that a can be deleted without interfering with the original b. But it took a bit of thought an experimentation to try to figure out what is going on here, and I'm still not sure, which is a bit unnerving when a) reading code with such uses whilst b) the vast majority of tutorials I can find on unique_ptrs just don't mention what to expect when moving nested pointers to each other. Can anyone elaborate what is actually happening here and perhaps point me to a good resource?
from cppreference std::unique_ptr<T,Deleter>::reset void reset( pointer ptr = pointer() ) noexcept; Given current_ptr, the pointer that was managed by *this, performs the following actions, in this order: Saves a copy of the current pointer old_ptr = current_ptr Overwrites the current pointer with the argument current_ptr = ptr If the old pointer was non-empty, deletes the previously managed object if(old_ptr) get_deleter()(old_ptr). std::unique_ptr<T,Deleter>::operator= unique_ptr& operator=( unique_ptr&& r ) noexcept; Move assignment operator. Transfers ownership from r to *this as if by calling reset(r.release()) followed by an assignment of get_deleter() from std::forward<Deleter>(r.get_deleter())
73,269,698
73,270,672
Problems implementing vector as a data container C++
I need to read data from a file and send it to a vector to perform some calculations with them. The data looks like this: 0 524 36 12 8 7 96 0 2 1 11 22 55 77 88 88 96 15 78 45 65 32 78 98 65 54 12 I managed to put the data in a "istringstream", it change with each iteration as it should, but I cannot put the data in the vector, it keeps adding just the first line of the file (e.g 0 524 36 12 8 7 96 0 2). #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> int main() { std::ifstream input; std::string strInput; std::istringstream strData; std::vector<int> vectData; input.open("input.txt"); for (int idx = 0; idx < 3; idx++) { std::getline(input >> std::ws, strInput, '\n'); strData.str(strInput); int idy; //int index = 0; while(strData >> idy) { vectData.push_back(idy); //++index; } std::cout << strData.str() << std::endl; for (auto i:vectData) { std::cout<< i << ' '; } std::cout << '\n' << std::endl; } return 0; } I hope I have improved the question this time, thanks for all the suggestions.
it keeps adding just the first line of the file That's because it is the only one it has. You seem to be of the impression that the str setter of std::istringstream resets the stream state from its prior error/eof condition. It doesn't. Since you're reusing the same strData member on each for-loop iteration, only the first one pushes through and fills the vector. After that the stream is in fail-state (by design, since that is what broke the inner-while-loop). When processing the next line, the stream is still in fail-state, and the while loop is effectively skipped. Your options are numerous. For this trivial example I'd probably just do this, the most minimal change I can muster (which also fixes resetting the vector). #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> int main() { std::ifstream input; std::string strInput; input.open("input.txt"); for (int idx = 0; idx < 3; idx++) { std::getline(input >> std::ws, strInput, '\n'); std::istringstream strData(strInput); // moved here std::vector<int> vectData; // also moved here int idy; while (strData >> idy) { vectData.push_back(idy); } std::cout << strData.str() << std::endl; for (auto i : vectData) { std::cout << i << ' '; } std::cout << '\n' << std::endl; } return 0; } Another considerably more concise and arguably more robust possibility is just this: #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <iterator> int main() { std::ifstream input("input.txt"); if (input.is_open()) { std::string strInput; while (std::getline(input, strInput)) { std::cout << strInput << '\n'; std::istringstream strData(strInput); std::vector<int> vectData { std::istream_iterator<int>(strData), std::istream_iterator<int>() }; for (auto i : vectData) { std::cout << i << ' '; } std::cout << "\n\n"; } } } Output (for the given sample input) 0 524 36 12 8 7 96 0 2 0 524 36 12 8 7 96 0 2 1 11 22 55 77 88 88 96 15 1 11 22 55 77 88 88 96 15 78 45 65 32 78 98 65 54 12 78 45 65 32 78 98 65 54 12
73,269,744
73,273,125
Adding vertices on mouse click in DirectX 12
I'm trying to implement a functionality where a vertex is added whenever the user clicks on the viewport. So far I've managed to draw vertices with the mouse using D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, but the working implementation simply creates a new vertex buffer every click^^ That's how I came to my new implementation after hours of research and trial & error because I totally don't get how a D3D12_HEAP_TYPE_UPLOAD works combined with a D3D12_HEAP_TYPE_DEFAULT I've noticed a strange behavior: Whenever I reach 10 clicks (the defined number of DYNAMIC_VERTEX_BUFFER_MAX_VERTICES), the linestrip is drawn. Before I don't reach the vertex buffer size, nothing is drawn. In addition I ran PIX debugger to see the contents of my vertex buffer. The vertices are initially stored in the buffer with (0, 0, 0, 0) and when I reach the limit (10 clicks), they magically appear with their correct values. Here are 2 screenshots in comparison [Vertices NOT empty after 10 clicks][1] [1]: https://i.stack.imgur.com/oah1Y.png [Vertices empty( < 10 clicks][2] [2]: https://i.stack.imgur.com/PWJgz.png Here is the implementation I came along with -> the call order is CreateDefaultBuffer once and then every time a vertex is added I call UpdateUploadHeap and then BindVertexBufferView void CreateDefaultBuffer(ID3D12Device& device, ComPtr<ID3D12GraphicsCommandList> commandList, const void* rawData, const UINT bufferSize) { // create default vertex buffer const CD3DX12_HEAP_PROPERTIES heapProp(D3D12_HEAP_TYPE_DEFAULT); const auto buf = CD3DX12_RESOURCE_DESC::Buffer(BufferSize * DYNAMIC_VERTEX_BUFFER_MAX_VERTICES); //DYNAMIC_VERTEX_BUFFER_MAX_VERTICES is 10 auto hr = device.CreateCommittedResource( &heapProp, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&D3DBuffer)); VALIDATE((hr == ERROR_SUCCESS), "CreateCommittedResource failed"); D3DBuffer->SetName(L"Dynamic Vertex Buffer"); // set name for debugger const auto transition = CD3DX12_RESOURCE_BARRIER::Transition(D3DBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); commandList->ResourceBarrier(1, &transition); } void UpdateUploaeHeap(ID3D12Device& device, ComPtr<ID3D12GraphicsCommandList> commandList, const void* rawData, const UINT bufferSize) { // create upload buffer to copy vertices into default buffer const CD3DX12_HEAP_PROPERTIES heapPropUpload(D3D12_HEAP_TYPE_UPLOAD); const auto bufUpload = CD3DX12_RESOURCE_DESC::Buffer(bufferSize); const auto hr = device.CreateCommittedResource( &heapPropUpload, D3D12_HEAP_FLAG_NONE, &bufUpload, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(D3DBufferUpload.ReleaseAndGetAddressOf())); VALIDATE((hr == ERROR_SUCCESS), "CreateCommittedResource failed"); D3DBufferUpload->SetName(L"Upload Buffer for copying into Dynamic Vertex Buffer"); // set name for debugger D3D12_SUBRESOURCE_DATA vertexData = {}; vertexData.pData = rawData; vertexData.RowPitch = bufferSize; vertexData.SlicePitch = vertexData.RowPitch; UpdateSubresources(commandList.Get(), D3DBuffer.Get(), D3DBufferUpload.Get(), 0, 0, 1, &vertexData); } D3D12_VERTEX_BUFFER_VIEW vertexBufferView; void BindVertexBufferView() { vertexBufferView.BufferLocation = D3DBuffer->GetGPUVirtualAddress(); vertexBufferView.StrideInBytes = sizeof(meshData.vertices[0]); vertexBufferView.SizeInBytes = static_cast<UINT>(meshData.vertices.size()) * vertexBufferView.StrideInBytes; }```
Resources allocated from the D3D12_HEAP_TYPE_DEFAULT heap are placed in memory where the GPU can access them. There's no guarantee that the CPU can access it at all. In some architectures, there's no difference and all memory can be accessed by both at all times (Unified Memory Architecture such as the Xbox). In other architectures, default memory is dedicated video RAM that is not accessible from the CPU at all. In order to place data into D3D12_HEAP_TYPE_DEFAULT from CPU system memory, you need to copy the data into a resource allocated from the D3D12_HEAP_TYPE_UPLOAD heap. This memory is explicitly designated to be visible to both the CPU and GPU. This can be the "PCIe aperture" or some other mechanism. You can render directly from D3D12_HEAP_TYPE_UPLOAD memory for VBs/IBs and textures. This is equivalent to the DirectX 11 concept of D3D11_USAGE_DYNAMIC. That said, there's usually a performance penalty to rendering directly from this type of memory. You also use D3D12_HEAP_TYPE_UPLOAD heap memory directly for Constant Buffers (CB) as these are modified a lot during render. A key thing to remember is that DirectX 12 does not do "buffer renaming" for you. If you change a resource while it's being used by the GPU, it's going to cause problems with the render. The application is responsible for ensuring the resource is no longer being used for drawing before you change it. For example, after you have called the UpdateSubresources helper nothing is actually on the video card yet. You have to Close the associated command-list and Execute it. Then sometime later the copy is actually performed by the GPU (or DMA engine). The resource barriers take care of the dependencies between resources in the same command-list, but you still have to make sure you don't change the resource data from the CPU until it's actually done. The practical up-shot of this fact is that if you are setting a resource in the UPLOAD heap, then using it in a command-list, you must leave it alone and alive until the task you scheduled is actually completed on the GPU. If you want to render with a different version of the same resource, you need to create a new instance of it for the next draw or next frame. You have to wait 2 or 3 frames worth of rendering to know that the original resource you used is actually done. There are a number of ways to handle the recycling the memory and tracking its usage lifetime, but it looks like you have just a single resource which isn't going to work unless you stall out the GPU every frame. For a 'dynamic' VB/IB, you going to need 2 or 3 copies of it so you can swap between them each frame. See DirectX Tool Kit for DirectX 12 and in particular the ResourceUploadBatch and GraphicsMemory classes.
73,269,925
73,270,217
C++ CUDA Gridsize meaning clarification
I am new to CUDA programming. I am currently in the process of doing Monte Carlo Simulations on a high number of large data samples. Im trying to dynamically maximize and calculate the number of Blocks to submit to the GPU. The issue i have is that i am unclear on how to calculate the maximum number of blocks i can submit to my GPU at one time. Here is the output of my GPU when querying it: ----------------------------------------------- CUDA Device #: 0 Name: NVIDIA GeForce GTX 670 Revision number: 3.0 Warp size: 32 Maximum threads per block: 1024 Maximum Grid size: 2147483647 Multiprocessor Count: 7 ----------------------------------------------- What i am unclear on is that the maximum number of thread per block is clearly defined as 1024 but the grid size is not (at least to me). when i looked around in the documentation and online the definition is as follow: int cudaDeviceProp::maxGridSize[3] [inherited] Maximum size of each dimension of a grid What i wanna know is the grid size reffering to: The maximum total number of threads that can be submitted to the GPU? (therefore i would calculate the number of blocks like so: MAX_GRID_SIZE / MAX_THREAD_PER_BLOCK) The Maximum number of blocks of 1024 threads (therefore i would simply use MAX_GRID_SIZE) The last one seems kind of insane to me since the MAX_GRID_SIZE = 2^31-1 (2147483647) therefore the maximum number of threads would be (2^31-1)*1024 = ~ 2.3 Trillions threads. Which is why i tend to think the first option is correct. But i am looking for outside input. I have found many discussion about the subject of calculating blocks but almost all of them were specific to one GPU and not the general way of calculating it or thinking about it.
On Nvidia CUDA the grid size signifies the number of blocks (not the number of threads), which are sent to the GPU in one kernel invocation. The maximum grid size can be and is huge, as the CUDA programming model does not (normally) give any guarantee that blocks run at the same time. This helps to run the same kernels on low-end and high-end hardware of different generations. So the grid is for independent tasks, the threads in a block can cooperate (especially with shared memory and synchronization barriers). So a very large grid is more or less the same as an automatic loop around your kernel invocation or within your kernel around your code. If you want to optimize the occupancy (parallel efficiency) of your GPU to the maximum, you should calculate, how many threads can run at the same time. The typical maximum is maximum number of threads per SM x number of SMs. The GTX 670 has 7 SMs (called SMX for that generation) with a maximum of 1024 threads each. So for maximum occupancy you can run a multiple of 7x1024 threads. There are other limiting factors for the 1024 threads per multiprocessor, mainly the amount of registers and shared memory each of your threads or blocks need. The GTX has 48 KB shared memory per SM and 65536 32-bit registers per SM. So if you limit your threads to 64 registers per thread, then you can use the 1024 threads per block. Sometimes, one runs kernels with less than the maximum size, e.g. 256 threads per block. The GTX 670 can run up to a maximum of 16 blocks per SM at the same time. But you cannot get more threads than 1024 per SM altogether. So nothing gained. To optimize your kernel itself or get nice graphical and numeric feedback, about the efficiency and bottlenecks of your kernel, use the Nvidia Compute Nsight tool (if there is a version, which still supports the 3.0 Kepler generation). To get full speed, it is typically important to optimize memory accesses (coalescing) and to make sure that the 32 threads within a warp are running in perfect lockstep. Additionally you should try to replace accesses to global memory with accesses to shared memory (be careful about bank conflicts).
73,270,155
73,270,298
C++: Using sizeof() division to find the size of a vector
I am trying to get the size of a vector as a number so that I can use it as a constexpr. The vector.size() returns a size type that is not a constant expression. Therefore, I thought to use sizeof(vector) / sizeof(vector[0]) to get an integer value which I can manually use in a constexpr initialization. const vector<int> int_vec = {1, 2, 3, 4, 5, 6, 7, 8, 9}; cout << sizeof(int_vec) / sizeof(int_vec[0]) << endl; My CLion compiler always prints 6. I do not understand why. Any help will be appreciated. Thanks for the response. I learned that I can use sizeof(arr) / sizeof(arr[0]) to find the length of an array. So how would this not work for a vector?
The reason why vector.size() isn't constexpr is that std::vector grows as you add data to it; it has a variable size that is not known at compile time. (That's what constexpr means, that the value of the expression is known at compile time.) What sizeof (vector) gets you is the size of the in-memory representation of the vector class, which has nothing to do with how many elements are stored in it. This obviously can't be correct because vector is a class name, not a variable name, so it can't possibly return the size of any one specific vector. Using sizeof int_vec, which by the way does not require parentheses, as sizeof is an operator and not a function, is a little more rational, since at least you're asking about the size of some specific vector and not all vectors in general. But again the problem is that you're going to get the size of the in-memory representation, which has to be fixed. After all, you can instantiate one on the stack, and so it has to be of some fixed size so that C++ knows how much space to allocate for it. It can't just expand in place as you add elements to it, because it would overwrite other data on the stack. It has to have some internal pointer to dynamically-allocated memory for storing the elements. When you do sizeof int_vec you're getting the space needed for this pointer and other internal data, not the space needed for the elements themselves. If you want an array-like container that has a size that's fixed at compile time, try std::array.
73,270,156
73,270,247
Does placement new start object's lifetime?
The following code example is from cppreference on std::launder: alignas(Y) std::byte s[sizeof(Y)]; Y* q = new(&s) Y{2}; const int f = reinterpret_cast<Y*>(&s)->z; // Class member access is undefined behavior It seems to me that third line will result in undefined behaviour because of [basic.life]/6 in the standard: Before the lifetime of an object has started but after the storage which the object will occupy has been allocated ... The program has undefined behavior if ... the pointer is used to access a non-static data member or call a non-static member function of the object. Why didn't placement new start the lifetime of object Y?
The placement-new did start the lifetime of the Y object (and its subobjects). But object lifetime is not what std::launder is about. std::launder can't be used to start the lifetime of objects. std::launder is used when you have a pointer which points to an object of a type different than the pointer's type, which happens when you reinterpret_cast a pointer to a type for which there doesn't exist an object of the target type which is pointer-interconvertible with the former object. std::launder can then (assuming its preconditions are met) be used to obtain a pointer to an object of the pointer's type (which must already be in its lifetime) located at the address to which the pointer refers. Here &s is a pointer pointing to an array of sizeof(Y) std::bytes. There is also an explicitly created Y object sharing the address with that array and the array provides storage for the Y object. However, an array (or array element) is not pointer-interconvertible with an object for which it provides storage. Therefore the result of reinterpret_cast<Y*>(&s) will not point to the Y object, but will remain pointing to the array. Accessing a member has undefined behavior if the glvalue used doesn't actually refer to an object (similar) to the glvalue's type, which is here the case as the lvalue refers to the array, not the Y object. So, to get a pointer and lvalue to the Y object located at the same address as &s and already in its lifetime, you need to call std::launder first: const int f = std::launder(reinterpret_cast<Y*>(&s))->z; All of this complication can of course be avoided by just using the pointer returned by new directly. It already points to the newly-created object: const int f = q->z;
73,270,169
73,270,233
Dereferencing iterators to int and int& in C++
int main() { vector<int> v={1,2,4}; int &a=*v.begin(); cout<<a; return 0; } In the above code segment, the dereferenced value of the iterator v.begin() assigned to &a. Printing a displays 1 int main() { vector<int> v={1,2,4}; int a=*v.begin(); cout<<a; return 0; } Here, the iterator is deferenced and the value is assigned to a (without the &) instead. Printing a still displays 1. I'm still learning C++ and it doesn't make sense to me why the first code block works. What does int &a signify?
int& a = *v.begin(); makes a a reference to the first element in the vector so anything you do to that reference is reflected upon the referenced element. Example: #include <vector> #include <iostream> int main() { std::vector<int> v = {1, 2, 4}; int &a = *v.begin(); a = 100; std::cout << v[0]; // prints 100 } If you instead do int a = *v.begin(); you copy the value held by v[0] into a and v[0] and a live their separate lifes: #include <vector> #include <iostream> int main() { std::vector<int> v = {1, 2, 4}; int a = *v.begin(); a = 100; std::cout << v[0]; // prints 1 }
73,270,664
73,270,667
C++ passing a value by reference that is created in the function call (inline)
I want to understand why C++20 complains when I try do the following, perhaps someone can help. I have a method defined, like so: void doStuff(Point& dest) { ... } When I try to do the following: doStuff(Point(x,y)); I get the error: C++ initial value of reference to non-const must be an lvalue This goes away when I make Point& dest -> const Point& dest or if I define a new variable for the Point(x,y) however in the case that I do not want to defined dest as a const or I dont need a variable, why is it that the compiler complains about this? There are cases where I want to pass it in as a reference and others where I want to keep it inline with the function call to keep things more straight forward. Obviously the example I gave here is really simple, but you get the idea. Of note I know that I can cast it like so: doStuff(static_cast<Point&>(Point())); But this seems really unnecessary, I'd like to find a way to achieve this without all the other nonsense. Any help is most appreciated! I might be missing something really obvious, I am no C++ expert.
you can accept (overload with) rvalue references void doStuff(Point&& dest) side note: you can pass it directly to lvalue reference version if that's what you want. void doStuff(Point& dest); inline void doStuff(Point&& dest) { doStuff(dest); }
73,270,933
73,271,038
Delphi interface to C++ Builder
I am trying to use a Delphi component and the callback function needs to be implemented as a typedef System::DelphiInterface<TButtonCallBack> _di_TButtonCallBack; which is defined in the C++ header file as: __interface TButtonCallBack : public System::IInterface { virtual void __fastcall Invoke(TConfirmButton ConfirmButton) = 0; }; How do I implement the above Delphi interface in C++Builder?
Ok I figured it out. For others if it is helpful, the answer is below: class TUniFSConfirmButtonInterface : public TCppInterfacedObject<TButtonCallBack> { public: void __fastcall Invoke(TConfirmButton nButton) { } }; All the best, Aggie85!
73,271,094
73,271,145
How to create a Template function that creates an instance of the class specified as a template parameter
I am trying to enumerate my I2C bus. I have a data structure that contains the I2C address range, the device name and a pointer to the function that needs to be called to "Create" that device. The Create Device functions are all very similar and I was wondering if I can create a template function, instead of creating n functions that only differ in the name of the device that they are creating A typical create function looks like this (the name AMS3935Creator is stashed in the data structure above and when that device is encountered, this function is called). I2cDeviceBase * AMS3935Creator ( I2cInterfaceBase & i2cBus, uint8_t i2cAddress, DeviceFactory * dfObject ) { return new AMS3935 ( i2cBus, i2cAddress ) ; } I tried to work this out like this, but the template function does not compile (See error comment below), is there a way to accomplish this ? #include <stdio.h> class BaseClass { protected: BaseClass () {} ; BaseClass ( int param1, int param2 ) { printf ( "in BaseClass Constructor\n" ) ; } ; } ; class ClassA : public BaseClass { public: // ClassA () {} ; ClassA ( int param1, int param2 ) { printf ( "in ClassA Constructor\n" ) ; } ; } ; class ClassB : public BaseClass { public: ClassB () {} ; ClassB ( int param1, int param2 ) { printf ( "in ClassB Constructor\n" ) ; } ; } ; template <typename ClassName> BaseClass * TemplateTest( int param1, int param2, ClassName className ) { BaseClass * bcPointer = new className ( param1, param2 ) ; // error: expected type-specifier before ‘className’ return bcPointer ; }
To your title question template<typename T> T create(){ return T{}; } As to you actual question. It is most of the time very tricky, sometimes bordering on impossible to make templates and inheritance play nice with each other. Also ClassName className in the argument list makes className a value. You cant do new value; // needs to be a type. If this was intended to be ClassName, see my first suggestion. My suggestion is: Scrap this design and redo it from scratch.
73,271,155
73,271,397
C++ include error: No such file or directory
I am using the SFML library to try and build a game (it's my first time so I'm really struggling). I have given an include path in the tasks.json file and c_cpp_properties.json file but still when I build it, it finds an error in the model.cpp file, saying 'No such file or directory' regarding the #include <SFML\Window.hpp> line. The code of my files are shown below: tasks.json { "tasks": [ { "type": "cppbuild", "label": "CUSTOM C/C++: g++.exe build active file", "command": "C:\\MinGW\\bin\\g++.exe", "args": [ "-I C:\\Users\\MY_NAME\\Desktop\\projects\\asteroids-game\\include", "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "compiler: C:\\MinGW\\bin\\g++.exe" } ], "version": "2.0.0" } c_cpp_properties { "configurations": [ { "name": "Win32", "includePath": [ "C:\\Users\\MY_NAME\\Desktop\\projects\\asteroids-game\\include", ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.19041.0", "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-msvc-x64" } ], "version": 4 } model.cpp // std libs #include <iostream> // SFML libs #include <SFML\Window.hpp> int main() { std::cout << "Hello World" << std::endl; return 0; } The exact directory (copy-pasted from file explorer) where the header file is stored is: C:\Users\MY_NAME\Desktop\projects\asteroids-game\include\SFML Surely the include path given in the tasks.json file, and the include line from model.cpp would point it to this location? This is the error it gives me in the VS Code terminal: C:\Users\wswil\Desktop\projects\asteroids-game\src\model\model.cpp:7:10: fatal error: SFML\Window.hpp: No such file or directory 7 | #include <SFML\Window.hpp> | ^~~~~~~~~~~~~~~~~ compilation terminated. Build finished with error(s). * The terminal process failed to launch (exit code: -1). Does anyone know how I can solve this?
Well this was a very stupid error and I've just fixed it. In the tasks.json file, the include directory had a space between -I and the file directory path: "-I C:\\Users\\wswil\\Desktop\\projects\\asteroids-game\\include" While trying to learn how to set everything up, I read that you can have the space or not, it won't make a difference. I added it in so it was easier to read but turns out this is incorrect. There cannot be a space or it won't read the file directory. Hopefully someone else sees this and can fix their own issue! thanks for any helpful comments too.
73,271,399
73,271,413
error: passing 'const obj' as 'this' argument discards qualifiers
The following code: #include <iostream> #include <string> #include <array> #include <iterator> using namespace std; class obj { public: obj() = default; obj(int i) : i_{i} {} void show() {cout << "addr = " << this << ", i_ = " << i_ << endl;} private: int i_{0}; }; int main () { std::array<obj, 4> o_l {131,223,333,344}; for (auto const & idx : o_l) {idx.show();} return 0; } ends up throwing the following error: source>: In function 'int main()': <source>:22:45: error: passing 'const obj' as 'this' argument discards qualifiers [-fpermissive] 22 | for (auto const & idx : o_l) {idx.show();} | ~~~~~~~~^~ <source>:12:17: note: in call to 'void obj::show()' 12 | void show() {cout << "addr = " << this << ", i_ = " << i_ << endl;} | My question is - obj::show() is not modifying any class member, so why does the compiler think otherwise?
You should make it a const member function explicitly: void show() const { cout << "addr = " << this << ", i_ = " << i_ << endl; }
73,271,400
73,271,898
C++ - Visual Studio tries to link against symbols with @[num], but compiles symbols without that suffix
I'm trying to link against ZLib, which has been built by my solution with the same respective configuration type as my project (Debug|Win32). When I build my main project, I get these unresolved symbols: __imp__compress@16 __imp__compressBound@4 __imp__uncompress@16 If I had to guess, I would say that the @[num] is the number of bytes for the function arguments, as that seems to line up nicely. (I have tried to search what the technical term for that suffix is, in hopes to find out how I can force the compiler to export with it, but with no luck.) Inspecting the symbols of my zlibd.lib, I can see all three of those symbols, except they don't have the suffix at all, nor do any other symbols in the lib. 6.zlibd.dll __imp__compress 6.zlibd.dll _compress 7.zlibd.dll __imp__compress2 7.zlibd.dll _compress2 8.zlibd.dll __imp__compressBound 8.zlibd.dll _compressBound 9.zlibd.dll __imp__crc32 9.zlibd.dll _crc32 Am I missing an option in Visual Studio to export them in that manner? Also, I know for sure that the linker can see my zlibd.lib, as it shows up in every search and even says at the end that it is unused. ... Searching C:\<path-to-lib>\zlibd.lib: ... Unused libraries: ... C:\<path-to-lib>\zlibd.lib If I inspect kernel32.lib, for example, I see the @ in the symbols: 10.KERNEL32.dll __imp__AddConsoleAliasA@12 11.KERNEL32.dll _AddConsoleAliasW@12 11.KERNEL32.dll __imp__AddConsoleAliasW@12 12.KERNEL32.dll _AddDllDirectory@4 12.KERNEL32.dll __imp__AddDllDirectory@4
@16 and @4 in the unresolved symbols mean __stdcall calling convention when you import those symbols. Missing sign @ in zlibd.lib means __cdecl calling convention is used while building zlib.dll. You should use the identical calling convention while exporting and importing function. Since you have not provided any debugging details (build settings, a minimal example), I can only guess: You use different compiler settings for the two projects: you maybe use /Gz in the app and /Gd in the dll. Use the same compiler setting. You do not define the macro ZLIB_WINAPI in the app. Add the macro definition -DZLIB_WINAPI=1. You define the macro ZLIB_WINAPI in the app. Remove the macro definition.
73,271,879
73,271,925
Compiler error when a templated member function needs a forward declared type to be completed
I have the following code: // a.h #ifndef HEADER_A #define HEADER_A #include "b.h" #include <iostream> struct A { B b; void bar(); }; #endif // b.h #ifndef HEADER_B #define HEADER_B #include "a.h" struct A; struct B { A* a = nullptr; template <typename T> void foo() { a->bar(); } }; #endif // main.cpp #include "a.h" void A::bar() { std::cout << "bar" << std::endl; } int main() { A a; a.b.foo<int>(); } And when I try to compile it with g++ -std=c++20 main.cpp -o main.o it works as expected (outputs bar) but gives me the warning: <source>:10:10: warning: invalid use of incomplete type 'struct A' 10 | a->bar(); | ^~ However, both MSVC and clang++ rejects the code when the standard is set to C++20. MSVC is a little bit weirder because it accepts the code without any warning in C++17. Here are the compiler explorer link for reference: https://godbolt.org/z/cj9Wo61d5 (preprocessors are manually expanded) I would expect this to work since B::foo doesn't get used until the 2nd line in main(), by which time A should have already been completed. In my understanding (which might be wrong), the implementation of member templates are only instantiated at the point of use, for one example is that you can create an std::map<std::string, T> with T lacking a default constructor, but only get an error when you are trying to do map["key"]. Is my understanding wrong or am I missing something obvious?
You may the solve circular dependencies and the invalid use of incomplete type 'struct A' by using a template class parameter. // a.h #ifndef HEADER_A #define HEADER_A #include "b.h" #include <iostream> struct A { B<A> b; void bar(); }; #endif // b.h #ifndef HEADER_B #define HEADER_B <typename U> struct B { U* a = nullptr; template <typename T> void foo() { a->bar(); } }; #endif // main.cpp #include "a.h" void A::bar() { std::cout << "bar" << std::endl; } int main() { A a; a.b.foo<int>(); }