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,977,805
73,978,141
IXAudio2Engine::CreateSourceVoice fails
I receive the Error XAUDIO2_E_INVALID_CALL when I try to call IXAudio2Engine::CreateSourceVoice. My code for creating a source voice is as follows: auto sample_rate = quality_to_sample_rate(settings.quality, sound_category::effect); WAVEFORMATEX wave_format{ // 8000Hz 16 bit mono WAV .wFormatTag = WAVE_FORMAT_PCM, .nChannels = 1, .nSamplesPerSec = sample_rate, .nAvgBytesPerSec = sample_rate* 2, .wBitsPerSample = 16, .cbSize = 0, }; XAUDIO2_SEND_DESCRIPTOR send_descriptor{.Flags = 0, .pOutputVoice = master_voice}; XAUDIO2_VOICE_SENDS sends{.SendCount = 1, .pSends = &send_descriptor}; res = sound_engine->CreateSourceVoice(&v, &wave_format, 0, 2.0f, nullptr, &sends); if(FAILED(res)) { log_error("Could not create effect source voice with", sample_rate, "Hz"); throw std::runtime_error("Could not create effect source voice"); } log_debug("Created effect source voice with ", sample_rate, "Hz at ", (void*)v); master_voice is not nullptr and is of type IXAudio2MasteringVoice* (i.e. CreateMasteringVoice returned S_OK!) What am I missing? Edit: According to XAudio2 and *.wav loading, HRESULT 0x88960001 , it is possible to set pSendList to NULL which would result in using the MasteringVoice. but that does not help either.
Reading the docs helps: nBlockAlign and nAvgBytesPerSecond need to be set correctly. nBlockAlign needs to be (nChannels * (nBitsPerSample/8)) / 8 and nAvgBytesPerSecond is nBlockAlign * nSamplesPerSecond
73,979,485
73,980,936
Get number of active threads spawned by current process on MacOS
I've been searching for the last 3 hours online and through system headers, but can not find a mechanism available to me in C/C++ for what I'm trying to do on MacOS. I'm looking to find a way to retrieve for the currently running process the total number of active/alive threads. I acknowledge that this would be trivial if I were counting threads that I myself spawn, but this is not the case. The code base I'm working on uses several threading libraries, and I require this basic information for debugging purposes. On linux I can just acces /proc/self/stat/ where the 20th element is the total number of alive threads, but this is not available on MacOS. If it helps, this has to work on MacOS 12.0 + Does anyone have any ideas?
From a bit of googling around, it seems to me like you should be able to obtain this information using task_threads(), after getting the right mach port from task_for_pid(): int pid = 123; // PID you want to inspect mach_port_t me = mach_task_self(); mach_port_t task; kern_return_t res; thread_array_t threads; mach_msg_type_number_t n_threads; res = task_for_pid(me, pid, &task); if (res != KERN_SUCCESS) { // Handle error... } res = task_threads(task, &threads, &n_threads); if (res != KERN_SUCCESS) { // Handle error... } // You now have `n_threads` as well as the `threads` array // You can use these to extract info about each thread res = vm_deallocate(me, (vm_address_t)threads, n_threads * sizeof(*threads)); if (res != KERN_SUCCESS) { // Handle error... } Note however that the usage of task_for_pid() might be restricted. I don't know much about how entitlements work on macOS, but you can check these other posts: task_for_pid stops working on OS X 10.11 Getting task_for_pid() to work in El Capitan This GitHub Gist containing an example with a commented .plist
73,979,818
73,979,930
Copying non-sequential columns from an array into another array C++ and removing duplicates based on 1 column
I want to copy columns from a std::vector<std::vector<double> > into another std::vector<std::vector<double> > in C++. This question answers that but only deals with the case where all the columns are in a sequence. In my case, the inner std::vector has 8 elements {C1, C2, C3, C4, C5, C6, C7, C8}. The new object needs to contain {C4, C5, C6, C8} and all the rows. Is there a way to do it directly? After this step, I will be manipulating this to remove the duplicate rows and write it into a file. Also, please suggest which activity to do first (deleting "columns" or duplicates). Just to put things in perspective - the outer std::vector has ~2 billion elements and after removing duplicates, I will end up with ~50 elements. So, a method that is faster and memory efficient is highly preferred.
I would use std::transform. It could look like this: #include <algorithm> // transform #include <vector> #include <iostream> #include <iterator> // back_inserter int main() { std::vector<std::vector<double>> orig{ {1,2,3,4,5,6,7,8}, {11,12,13,14,15,16,17,18}, }; std::vector<std::vector<double>> result; result.reserve(orig.size()); std::transform(orig.begin(), orig.end(), std::back_inserter(result), [](auto& iv) -> std::vector<double> { return {iv[3], iv[4], iv[5], iv[7]}; }); // print the result: for(auto& inner : result) { for(auto val : inner) std::cout << val << ' '; std::cout << '\n'; } } Output: 4 5 6 8 14 15 16 18 Note: If any of the inner vector<double>s in orig has fewer elements than 8, the transformation will access that array out of bounds (with undefined behavior as a result) - so, make sure they all have the required amount of elements. Or using C++20 ranges to create the resulting vector from a transformation view: #include <iostream> #include <ranges> // views::transform #include <vector> int main() { std::vector<std::vector<double>> orig{ {1, 2, 3, 4, 5, 6, 7, 8}, {11, 12, 13, 14, 15, 16, 17, 18}, }; auto trans = [](auto&& iv) -> std::vector<double> { return {iv[3], iv[4], iv[5], iv[7]}; }; auto tview = orig | std::views::transform(trans); std::vector<std::vector<double>> result(tview.begin(), tview.end()); // print the result: for (auto& inner : result) { for (auto val : inner) std::cout << val << ' '; std::cout << '\n'; } }
73,979,843
73,993,243
Using a swig wrapped c++ library with go
I have managed to successfully wrap a large C++ library with SWIG. I published the module and can install it okay, but when I go to build it I get a ton of undefined reference errors to the functions contained within the generated c file. I placed the generated so lib file in my system lib directory, and placed the header files from the library into my system include directory, but this has not solved the problem. I am guessing that I need a header file for wrapped c file as well so the interpreter can know what's in the so file, but given that SWIG didn't generate one, I don't know if I am missing anything else. I'm going to try to write my own header file to see if that resolves the errors, but even if it does, shouldn't that be something that SWIG would do automatically? My source files are below /** file: golibraw.i **/ %module librawgo %{ #define LIBRAW_LIBRARY_BUILD /* Put headers and other declarations here */ #include "libraw/libraw.h" #include "libraw/libraw_alloc.h" #include "libraw/libraw_const.h" #include "libraw/libraw_datastream.h" #include "libraw/libraw_internal.h" #include "libraw/libraw_types.h" #include "libraw/libraw_version.h" %} %include "libraw/libraw.h" %include "libraw/libraw_alloc.h" %include "libraw/libraw_const.h" %include "libraw/libraw_datastream.h" %include "libraw/libraw_internal.h" %include "libraw/libraw_types.h" %include "libraw/libraw_version.h" cmake_minimum_required(VERSION 3.14) if ( ${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR} ) message( FATAL_ERROR "In-source builds not allowed. Please make a new directory and run CMake from there. You may need to remove CMakeCache.txt." ) endif() find_package(SWIG 4.0 COMPONENTS python OPTIONAL_COMPONENTS go) if(SWIG_FOUND) message("SWIG found: ${SWIG_EXECUTABLE}") include (UseSWIG) if(NOT SWIG_go_FOUND) message(FATAL_ERROR "SWIG go bindings cannot be generated") endif() else() message(FATAL_ERROR "SWIG NOT FOUND") endif() set(PROJECT_NAME librawgo) project(${PROJECT_NAME}) SET (CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/librawgo CACHE PATH "Single Directory for all" ) find_program( CLANG_TIDY NAMES clang-tidy) set(${PROJECT_NAME}_sources ${CMAKE_SOURCE_DIR}/src/librawgo.i ) swig_add_library(${PROJECT_NAME} TYPE SHARED LANGUAGE go SOURCES ${${PROJECT_NAME}_sources}) if(CLANG_TIDY) set_property( TARGET ${PROJECT_NAME} PROPERTY CXX_CLANG_TIDY "${CLANG_TIDY}") endif() set_property(TARGET ${PROJECT_NAME} PROPERTY SWIG_COMPILE_OPTIONS -go -intgosize 64 -cpperraswarn) set_property(TARGET ${PROJECT_NAME} PROPERTY SWIG_USE_TARGET_INCLUDE_DIRECTORIES TRUE) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 11) set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_SOURCE_DIR})
The reason is that Go compiler has no idea about the library librawgo.so. Put the following line to the top of the C comment in librawgo.go: #cgo LDFLAGS: -L<path/to/dir/with/librawgo.so> -lrawgo -lraw This instruction tells the compiler to add this line to the linker flags. Sorry, I don't know how to modify your CMake and SWIG settings to generate this line automatically.
73,979,892
73,979,999
std::unique_lock::_Owns data member is not atomic?
Looking through the std::unique_lock implementation in MSVC14, I noticed it has a data member bool _Owns; Since _Owns is used by operator=, operator() and owns_lock() amongst other, I was expecting _Owns to be atomic. Anyone can comment as to why it is not? Thanks.
A std::unique_lock object cannot be accessed by multiple threads (that would be completely counter to its purpose), so it doesn't need to consider atomicity of the data stored in itself. The lock object has a reference to a mutex object (e.g. std::mutex) on which it calls member functions to lock or unlock the mutex for the thread owning the lock object. That mutex object is what is shared between threads.
73,980,275
73,980,507
Dynanically choose derived class to instantiate – how to take care of memory?
Consider the following setup: struct Base { virtual void f() = 0; virtual ~Base() {}; }; struct Helper: Base { virtual void f() {} }; struct Derived: public Base { Derived(Helper& helper): m_helper(helper) {} void f() {} Helper& m_helper; }; that I, at the moment, use conditionally using preprocessor: Helper h; #if condition Derived d(h); #else Helper& d(h); #endif If you wish, Derived is a class that enhances Helper. Now, how can I do that dynamically, at best as little error-prone as possible? std::unique_ptr<Base> p = new Helper(); if(condition){ p = new Derived(*helper); } won't work, I guess, because on the assignment p = new Derived, I will cause deletion of the original Helper, won't I? Of course, I can simply do something like Helper h; std::optional<Derived> d = condition ? Derived(h) : {}; Base& p = d ? d : h; Or, go fully manually, and do Helper h; Derived* d = condition ? new Derived(h) : 0; Base& p = d ? *d : h; ... if(d) delete d; None of these solutions really pleases me. What is the advisable way?
You can use std::shared_ptr instead of std:unique_ptr: auto h = std::make_shared<Helper>(); std::shared_ptr<Base> p; if (condition) { p = std::make_shared<Derived>(*h); } else { p = h; } Alternatively: auto h = std::make_shared<Helper>(); auto p = condition ? std::shared_ptr<Base>(new Derived(*h)) : h; Though, I would suggest sticking with the std::optional approach you proposed, as it doesn't rely on dynamic allocation. However, what you showed won't compile, but this does: Helper h; std::optional<Derived> d; if (condition) d.emplace(h); Base& p = d ? *d : static_cast<Base&>(h); Online Demo
73,980,365
73,980,978
Can gcc emit code as efficient as clang for the binary tree "LowerBound" algorithm?
I have been implementing various node based binary search trees using C-ish C++ code. When benchmarking these I have noticed surprisingly large performance variations both across compilers and in response to small code changes. When I focused on insertion and removal in a tree that allowed duplicates (as a C++ std::multiset<int> would), I found that almost all the time is spent zig-zagging down the tree's left and right pointers in operations like "find" and "lower_bound" rather than the conceptually "expensive" rebalancing steps that occur after inserts and deletes. So I began to focus on one case in particular: lower bound. // Node is a binary tree node. It has the // usual left and right links and an // integral key. struct Node { int key; Node* links[2]; }; // LowerBound returns the first node in // the tree rooted at "x" whose key is // not less than "key", or null if there // is no such key. Node* LowerBound(Node* x, int key) { Node* lower = nullptr; while (x != nullptr) { bool x_gte = !(x->key < key); lower = x_gte ? x : lower; x = x->links[!x_gte]; } return lower; } A few points and observations: I am on an AMD Ryzen 9 5900X 12-Core. My understanding is that the conditional move (cmov) instructions are faster on AMD than on Intel (my understanding was wrong, see Peter Cordes' comment on this post), but I find that when I spot check results on my 8 year old Intel laptop the code that is faster on AMD is faster on Intel too. I am running Linux. I've turned off hyperthreading, boost mode, and set the cpu scaling governor to "performance" using this script I wrote. The performance numbers are stable with little variation. The code above is the end of several optimization iterations. I have a benchmark (code here) that exercises various tree sizes, allocating nodes in an array according to either a random or ascending by key order, then writes a key access pattern to another array, and runs through them repeatedly. The key access patterns are either ascending or random. In larger trees, code that uses branches, rather than cmov or similar, is often much slower. One key optimization seems to be using an array of links (Node links[2]) in the node instead of explicit left and right pointers. With explicit fields gcc is very quick to switch to branchy code, which is slower. With the links array gcc will index it as I have written. In fact, when I use gcc's profile guided optimization it still switches to branch based code, for a 1.5x to 2x performance loss. In all cases, except for very tiny trees where branchy code can win, clang generates faster code for this function. With the code above on godbolt we can see clang generating the following: LowerBound(Node*, int): xorl %eax, %eax testq %rdi, %rdi je .LBB0_3 .LBB0_1: # =>This Inner Loop Header: Depth=1 xorl %ecx, %ecx cmpl %esi, (%rdi) setl %cl cmovgeq %rdi, %rax movq 8(%rdi,%rcx,8), %rdi testq %rdi, %rdi jne .LBB0_1 .LBB0_3: retq while gcc is doing worse: LowerBound(Node*, int): xorl %eax, %eax testq %rdi, %rdi je .L5 .L4: cmpl %esi, (%rdi) setl %dl cmovge %rdi, %rax movzbl %dl, %edx movq 8(%rdi,%rdx,8), %rdi testq %rdi, %rdi jne .L4 ret .L5: ret The gcc variant is roughly 2x slower on my machine (the geomean of the timings with tree heights 1 to 18). Can this be explained in a simple way? I notice that clang is clearing %ecx first, then sets %cl, then uses %ecx, whereas gcc sets %dl and then moves it to %edx before using %rdx. gcc's approach is equivalent logically, much slower in practice. Can it be improved?
Using llvm-mca, which is a tool from the LLVM suite to analyze the machine code for a given architecture, we can see that indeed there is a difference. For the Intel Skylake architecture the code generated by GCC versus LLVM: Instructions: 1200 vs 1200 Total Cycles: 1305 vs 1205 Total uOps: 1700 vs 1400 For the AMD Zen3 architecture the code generated by GCC versus LLVM: Instructions: 1200 vs 1100 Total Cycles: 1205 vs 1105 Total uOps: 1200 vs 1100 The average wait times for GCC were 20% higher Average Wait times (based on the timeline view): [0]: Executions [1]: Average time spent waiting in a scheduler's queue [2]: Average time spent waiting in a scheduler's queue while ready [3]: Average time elapsed from WB until retire stage [0] [1] [2] [3] 0. 3 0.0 0.0 12.0 xorl %eax, %eax 1. 3 11.0 0.3 0.7 testq %rdi, %rdi 2. 3 12.0 0.0 0.0 je .L5 3. 3 11.0 0.3 0.0 cmpl %esi, (%rdi) 4. 3 16.0 0.0 0.0 setl %dl 5. 3 17.0 0.0 0.0 movzbl %dl, %edx 6. 3 15.0 0.0 1.0 cmovgeq %rdi, %rax 7. 3 17.0 0.0 0.0 movq 8(%rdi,%rdx,8), %rdi 8. 3 22.0 0.0 0.0 testq %rdi, %rdi 9. 3 23.0 0.0 0.0 jne .L4 10. 3 1.0 1.0 18.0 retq 11. 3 1.7 1.7 17.3 retq 3 12.2 0.3 4.1 <total> Against the code generated by LLVM Average Wait times (based on the timeline view): [0]: Executions [1]: Average time spent waiting in a scheduler's queue [2]: Average time spent waiting in a scheduler's queue while ready [3]: Average time elapsed from WB until retire stage [0] [1] [2] [3] 0. 3 0.0 0.0 11.7 xorl %eax, %eax 1. 3 10.3 0.3 0.7 testq %rdi, %rdi 2. 3 11.0 0.0 0.0 je .LBB0_3 3. 3 0.0 0.0 12.0 xorl %ecx, %ecx 4. 3 10.0 0.3 0.0 cmpl %esi, (%rdi) 5. 3 15.0 0.0 0.0 setl %cl 6. 3 14.7 0.0 0.0 cmovgeq %rdi, %rax 7. 3 15.3 0.0 0.0 movq 8(%rdi,%rcx,8), %rdi 8. 3 20.0 0.0 0.0 testq %rdi, %rdi 9. 3 21.0 0.0 0.0 jne .LBB0_1 10. 3 1.0 1.0 16.0 retq 3 10.8 0.2 3.7 <total> We can see also that the resource pressure per iteration on GCC is much higher Resources: [0] - Zn3AGU0 [1] - Zn3AGU1 [2] - Zn3AGU2 [3] - Zn3ALU0 [4] - Zn3ALU1 [5] - Zn3ALU2 [6] - Zn3ALU3 [7] - Zn3BRU1 [14.0] - Zn3LSU [14.1] - Zn3LSU [14.2] - Zn3LSU [15.0] - Zn3Load [15.1] - Zn3Load [15.2] - Zn3Load Resource pressure per iteration: [0] [1] [2] [3] [4] [5] [6] [7] 1.33 1.33 1.34 3.33 1.35 1.65 2.65 2.02 [14.0] [14.1] [14.2] [15.0] [15.1] [15.2] 1.33 1.33 1.34 1.33 1.33 1.34 Against LLVM [0] [1] [2] [3] [4] [5] [6] [7] 1.00 1.00 1.00 2.55 0.99 1.01 2.50 1.95 [14.0] [14.1] [14.2] [15.0] [15.1] [15.2] 1.00 1.00 1.00 1.00 1.00 1.00 It looks like the LLVM compiler does a much better job of optimizing the pipeline pressure. Compiler Explorer (original): https://godbolt.org/z/abde4vv7r Compiler Explorer (ret instructions excluded as suggested by Peter Cordes, select zen3 arch): https://godbolt.org/z/4K6814chq If you are interested in only certain portions of the execution as the inner loop, you can mark the regions to be analized as in Node* LowerBound(Node* x, int key) { Node* lower = nullptr; while (x != nullptr) { __asm volatile("# LLVM-MCA-BEGIN foo":::"memory"); bool x_gte = !(x->key < key); lower = x_gte ? x : lower; x = x->links[!x_gte]; __asm volatile("# LLVM-MCA-END foo":::"memory"); } return lower; } This brings total cycles to 1303 for GCC and 1203 for LLVM. Compiler Explorer: https://godbolt.org/z/8KoKfab34
73,981,222
73,982,351
Attaching .pdb to a compiled .exe in Visual Studio 2022
I am trying to debug a .exe file with a .pdb. The project is using SCons, and here is the part where it compiles in sconstruct: env.Append( CCFLAGS=["/EHsc"]) env.Append( CCFLAGS=["/DEBUG", "/Zi", "/Fdgame.pdb"]) env.Program('game', ['game.cpp', Glob('feather/*.cpp')], LIBS=['SDL2', 'SDL2_image', 'SDL2_ttf', 'SDL2_mixer', 'SDL2main'], LIBPATH='lib/Windows/lib') So I'm adding the flags that are correct (I think) to generate the .pdb. The pdb shows up in my project directory, in the same location where the .exe is. After looking at its contents, I'm pretty sure that it has the correct information to work (at least, it is not empty). I am setting game.exe as the startup item, then running it from VS 2022. However, after running the .exe, Visual Studio claims that the "Binary was not built with debug information." Modules tab showing this message under "Symbol Status." According this page on the Microsoft VS documentation, it says: The debugger searches for symbol files in the following locations: The project folder. The location that is specified inside the DLL or the executable (.exe) file. By default, if you have built a DLL or an .exe file on your computer, the linker places the full path and filename of the associated .pdb file in the DLL or .exe file. The debugger checks to see if the symbol file exists in that location. The same folder as the DLL or .exe file. My .pdb should fulfill conditions 1 and 3, so I'm confused as to why it can't be found (if that's the issue). The docs do mention that this applies when you build a project, but I've seen other video tutorials online where they just attach .pdbs to running processes and it still works. Is there anything I'm missing?
Try changing to env.Append( CCFLAGS=["/EHsc"]) env.Append( CCFLAGS=["/DEBUG", "/Zi"]) env.Program('game', ['game.cpp', Glob('feather/*.cpp')], LIBS=['SDL2', 'SDL2_image', 'SDL2_ttf', 'SDL2_mixer', 'SDL2main'], LIBPATH='lib/Windows/lib', PDB="game.pdb") If that's still not in the correct location then change to PDB="${TARGET.dir}/game.pdb" See the manpage for info on the PDB environment variable: https://scons.org/doc/production/HTML/scons-man.html#cv-PDB
73,981,381
73,981,864
why is GNU make not filling out the $^ variable here?
I can compile the project just fine if I run the project by hand with g++ source/* -lSDL2 -o bin/fly_fishing. When I do run make, I get mkdir -p bin g++ -lSDL2 -o bin/fly_fishing /usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/12/../../../x86_64-linux-gnu/Scrt1.o: in function `_start': (.text+0x17): undefined reference to `main' collect2: error: ld returned 1 exit status make: *** [Makefile:20: bin/fly_fishing] Error 1 Which tells me that it's not populating from $^ for linking. So what have I missed here? Here's the makefile for reference. SRC_DIR := source OBJ_DIR := objects BIN_DIR := bin EXE := $(BIN_DIR)/fly_fishing SRC := $(wildcard $(SRC_DIR)/*.c) OBJ := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o) CXXFLAGS := -Wall #CFLAGS := -Wall LDLIBS := -lSDL2a LDFLAGS := .PHONY: all clean all: $(EXE) $(EXE): $(OBJ) | $(BIN_DIR) $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@ $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | $(OBJ_DIR) $(CXX) -c $(CXXFLAGS) $(CFLAGS) $< -o $@ $(BIN_DIR) $(OBJ_DIR): mkdir -p $@ clean: @$(RM) -rv $(BIN_DIR) $(OBJ_DIR) -include $(OBJ:.o=.d)
Which tells me that it's not populating from $^ for linking. That seems unlikely. Much more likely would be that $^ expands to nothing. Which would be the case if $(OBJ) expands to nothing. Which seems plausible because I don't see any corresponding objects being built (though perhaps you've omitted that, or they were built on a previous run). And $(OBJ) expanding to nothing implies that $(SRC) expands to nothing. So what have I missed here? That $(SRC) expands to nothing is not inconsistent with the data presented. I observe that the manual compilation command you present is g++ source/* -lSDL2 -o bin/fly_fishing That does seem to suggest that there are indeed source files in source/, but do they match the pattern source/*.c? Since you're compiling with g++, I bet not. It would be highly unconventional to name C++ source files to end with .c, and surely you would not attempt to compile C source files with a C++ compiler. I infer, then, that your source files are all named with .cpp, or maybe .cc or .C, all of which forms are conventions for C++ source names. If all your source names follow one or another of those patterns then indeed, this ... SRC := $(wildcard $(SRC_DIR)/*.c) ... will result in $(SRC) being empty.
73,981,511
73,981,751
How to Access a Struct in a Class through a Function in Main?
I'm using a function void displayStudent(Student stu), which displays the student's info. In my main(), I did this (all the parameters have been created in main() respectively already, and Student is my class): Student student1(name1, id1, dept1, year1); displayStudent(student1); Now, in my display function, here is my syntax which works for everything correctly besides the name of the student: void displayStudent(Student stu) { // Does not work, gives error saying "no type named 'type" // and no operator "<<" matches these operands. cout << "Name: " << stu.getName() << endl; cout << "ID Number: " << stu.getidNumber() << endl; cout << "Department: " << stu.getDepartment() << endl; cout << "Year: " << stu.getYear() << endl;; } Furthermore, for info here are my getter/setter functions for the name in Student.cpp, and the struct Name in Student.h, which looks like this: struct Name { string firstName; string lastName; }; The variables in this instance of Student have already been initialized with random info from another function in this Student.cpp file: void Student::setName(Name n) { name.firstName = n.firstName; name.lastName = " " + n.lastName; } Name Student::getName() const { return name; } Essentially, what I can't figure out is, why can I display everything but the name in my main()? How do I fix this to access elements of the name struct in this instance of Student? I initialized them earlier like this: Student::Student(Name a, int b, string c, Year d) { // Assigns student info to the 4 parameter variables a.firstName = "Roger"; a.lastName = "Federer"; b = 12345; c = "Art"; d = SENIOR; name.firstName = a.firstName; name.lastName = " " + a.lastName; idNumber = b; department = c; year = d; }
On this line: cout << "Name: " << stu.getName() << endl; stu.getName() returns a Name struct, but by default the compiler doesn't know how to print a Name struct to an std::ostream, like std::cout, when using operator<<. So you need to implement your own operator<< overload for printing a Name, eg: struct Name { string firstName; string lastName; }; // add this! ostream& operator<<(ostream &out, const Name &name) { return out << name.firstName << " " << name.lastName; } On a side note, there is code in your Student constructor that does not belong there: Student::Student(Name a, int b, string c, Year d) { /* these assignments do not belong here!!! The caller is responsible for providing the appropriate values when it calls Student()... // Assigns student info to the 4 parameter variables a.firstName = "Roger"; a.lastName = "Federer"; b = 12345; c = "Art"; d = SENIOR; For example: Name name1; name1.firstName = "Roger"; name1.lastName = "Federer"; int id1 = 12345; string dept1 = "Art"; Year year1 = SENIOR; Student student1(name1, id1, dept1, year1); */ name.firstName = a.firstName; name.lastName = /*" " +*/ a.lastName; // <-- the space character does not belong, either! // which can be simplified to just this! // name = a; idNumber = b; department = c; year = d; } And same with setName(): void Student::setName(Name n) { name.firstName = n.firstName; name.lastName = /*" " +*/ n.lastName; // <-- // or, simply: // name = n; }
73,981,813
73,981,901
What is a bfloat16_t in the C++23 standard?
Cppreference documents that stdfloat includes 5 new types: float16_t, float32_t, float64_t, float128_t and bfloat16_t. While the first 4 types are self-explanatory (a float with 16, 32, 64, and 128 bits respectively), the last type bfloat16_t is not at all clear to me. What does this type represent? What does the b in its name mean?
"bfloat16" refers to a fairly recent 16-bit floating-point format that is not a valid IEEE-754/IEC 60559 defined format. But it is related to them. BINARY16 is just BINARY32 with smaller numbers for its components. But the size changes are evenly distributed; it has both a smaller mantissa and a smaller exponent. Bfloat16 opts for a different way to spend its 16 bits. It elects to keep the exponent the same size as BINARY32 (8-bit) while shrinking the mantissa down to 7-bits (explicit). This makes transforming between bfloat16 and BINARY32 a faster operation. It does have some special-case weirdness, but overall, it's a truncated BINARY32. And while it's widely supported in a surprising amount of GPU hardware, it's not truly a standard. The utility of bfloat16 comes down to two things: the speed of conversion, and the compromises of BINARY16. BINARY16 is a great format... for colors. Having a maximum range of only 5 decimal orders of magnitude above zero is adequate for many cases of high-dynamic range rendering. But this compromise is a problem for machine learning operations. If precision matters, you're going to have to spend 32-bits to get it. But if precision isn't all that important, being able to save 16 bits without the range compromise can be useful in these applications.
73,982,002
73,982,470
C++20 concepts: accumulate values of all good types passed to function variadic template
I write a function variadic template that can be used like this: auto result{ Accum<int>(10, 20, 1.1, "string") }; // result is 31.1; Using binary operator+ Accum accumulates values of types from parameter pack for which init_type{} + value; arithmetical operation makes sense. If used with empty parameters pack, Accum<int>(), it just returns default constructed value of type Init: auto result{ Accum<int>(10, 20, 1.1, "string") + Accum<int>() }; // still 31.1; Please look at code below. As first template parameter Accum accepts type which default constructed value is used for initialization in folding expression, optional parameters pack contains values of heterogenous types which are candidates for binary addition operation. Values of types that cannot be used for binary addition operation are substituted with Init{}, and values of good types used as-is: to achieve this helper AccumValue, overloaded function template, utilized. Overload of AccumValue constrained with concept AddableC returns passed value as-is, non-constrained overload returns default constructed value of type Init. There's also another, less general, approach: helpers are overloaded for good types, no concept is used. Please help me to understand why 1st approach doesn't work. Is there a way to make it work? What am I missing conceptually or/and in syntax? How would you approach this task? import <iostream>; // Approach 1. Concept. template <typename Init, typename T> concept AddableC = requires (T&& t) { Init{} + t; }; template <typename Init, typename T> Init AccumValue(T const&) { return Init{}; } template <typename Init, typename T> requires AddableC<Init, T> auto AccumValue(T const& value) { return value; } template<typename Init, typename ... Args> auto Accum(Args&& ... args) { return (Init{} + ... + AccumValue<Init>( std::forward<Args>( args ) )); } // Approach 2. Overloads for target types. template<typename Init, typename T> auto Value(T const&) { return Init{}; } template<typename Init> auto Value(int const& i) { return i; } template<typename Init> auto Value(double const& d) { return d; } template<typename Init, typename ... Args> auto Sum(Args&& ... args) { return (Init{} + ... + Value<Init >(std::forward<Args>(args))); } int main() { auto result1{ Accum< int >(10, 20, 1.1) }; // works std::cout << result1 << std::endl; //auto result2{ Accum< int >(20, 40, 2.2, "string")}; // doesn't compile //std::cout << result2 << std::endl; auto result3{ Sum< double >(1, 2, 3.3, "asda") + Sum< double >()}; // works std::cout << result3 << std::endl; } Tested on: Microsoft Visual Studio Community 2022 Version 17.3.5 VisualStudio.17.Release/17.3.5+32922.545 Microsoft .NET Framework Version 4.8.04084 Installed Version: Community Visual C++ 2022 00482-90000-00000-AA918 Microsoft Visual C++ 2022 UPD. Changed helper function as following and it works as I feel it should: template <typename Init, typename T> requires AddableC< Init, T > && not std::is_pointer_v< std::decay_t< T > > auto AccumValue(T&& value) { return std::forward< T >(value); }
A string literal is of type const char[/*...*/] which can be added to an integral type. The array decays to a const char* pointer and int + const char* is then pointer arithmetic advancing the pointer by the given integer value. So the string literal will never be replaced in your scheme. You are only checking that each args individually can be applied with + to Init, but you never check whether the result of that operation is of type Init as well. The type could be completely different. In this specific case the usual arithmetic conversions imply that int + double = double, but then adding an array of const char (the string literal) to that is impossible. You verified int + const char[/*...*/], but not double + const char[/*...*/]. Possible solutions include: Require that + doesn't change the type of the accumulator, i.e. { Init{} + t } -> std::same_as<Init> instead of Init{} + t;. However this will cause the floating point value to be replaced as well. Force conversion of the operands to the target type instead of adding them directly, e.g.: template <typename Init, typename T> Init AccumValue(T&&) { return Init{}; } template <typename Init, typename T> requires std::convertible_to<T&&, Init> Init AccumValue(T&& value) { return std::forward<T>(value); } However this will e.g. round the floating point values. Constraint your function so that only arithmetic types are non-substituted (e.g. with std::is_arithmetic). I am not sure whether that matches your intentions. There are other possibilities, but you haven't given a use case for the function, so I don't want to list everything I can think of.
73,982,242
73,982,753
leetcode question 81 c++ returns wrong answer
question: There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4]. Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible. class Solution { public: int search(vector<int>& nums, int target) { int s=0; vector<int> f(4999); vector<int> x(4999); int y=f.size()-1; int z=x.size()-1; for (int i=0;i<nums.size();i++){ for (int j=1;j<nums.size();j++){ if (i<=j){ f.push_back(nums[i]); }else if (i>j){ f.push_back(nums[i]); x.push_back(nums[j]); for (int k=j;k<nums.size();k++) x.push_back(nums[k]); break; } } } if (target==x[0]||target==f[0]){ return true; } else if (target>f[0]){ while (s<=y){ int mid=0; mid=(y+s)/2; if (f[mid]>target){ y=mid-1; }else if (f[mid]<target){ s=mid+1; }else if (f[mid]==target){ return true; } } return false; }else if (target<f[0]){ while (s<=z){ int mid=0; mid=(z+s)/2; if (x[mid]>target){ z=mid-1; }else if (x[mid]<target){ s=mid+1; }else if (x[mid]==target){ return true; } } return false; } else{ return false; }return false; } }; input [2,5,6,0,0,1,2] target 2 returned false expected true input [1] target 1 returned false expected true input [1] target 0 returned true expected false trying to stick to a binary search solution how can this work help is appriciated thanks
To figure out why it's not working, you can walk through one of the failing test cases. You'd want to pick the easiest one to manage in your head, so in this case I recommend one of those with an array length of 1. So let's walk through input [1] target 1 returned false expected true Your function first creates two large arrays, each with 4999 zeros in them. See this answer for why they're zero. Then that nested for loop runs, but it doesn't actually do anything because the inner loop will not run -- j=1 is not less than nums.size(), which is 1. So by the time you do your binary searches below, both f and x are filled with 4999 zeros. Your code does the binary search on f, so it won't find your target of 1. If you want to see the solution to this problem, check out this Stack Overflow answer.
73,982,638
73,982,974
custom std::set.find() for a set of pointers
class Node{ public: Node* back1 = nullptr; Node* back2 = nullptr; int value; Node(int value) { this->value = value; } //bool operator< (const Node& rhs) const {return this->value < rhs.value;} bool operator< (const Node* rhs) const {return this->value < rhs->value;} }; std::unordered_map<int, std::set<Node*>> nodes; void subtractOneOrDouble(int current, int m, Node& prevNode) { if (current != 0 && current < m && nodes[current % 10].find(current) == nodes[current % 10].end()) { I have a set of Nodes* and not only do I want to sort them by the value of each node, I want to use find(), input a value, and get the pointer to the node that corresponds to that value. From what I think is going on, find() is taking in pointers, not actual values. What would I need to change so that find() takes in an integer value and gives me the pointer to the Node with that value?
find takes as input the key type. In your std::unordered_map, that key type is int, and in your std::set that key type is Node*. If you want to use your elements' sorting, then you can change your std::set's key to be Node instead of Node*. std::set's comparison uses operator < (via std::less) by default, so you can get this working with some tweaks to your code. Here's an example that shows how finding by value can work: #include <iostream> #include <set> struct Node { int value; Node(int v):value(v) {} bool operator <(const Node& rhs) const { return value < rhs.value; } }; int main() { std::set<Node> nodes; nodes.emplace(1); nodes.emplace(2); nodes.emplace(3); auto found = nodes.find(Node(2)); if (found != nodes.end()) { std::cout << "Found node " << found->value << std::endl; } else { std::cout << "Didn't find node!" << std::endl; } return 0; } This prints: Found node 2 As it is in your question, your std::set will be sorted by memory address (because that's how Node* is sorted), and not by Node::value.
73,982,834
73,982,879
C++ function type and callable object
I'm trying to assign callable object to function object with conforming call signature. This is my code: #include <functional> int add(int i, int j) { return i + j; } struct div { int operator()(int denominator, int divisor) { return denominator / divisor; } }; int main() { auto mod = [](int i, int j) { return i % j; }; std::function<int(int, int)> f1 = add; std::function<int(int, int)> f2 = div(); std::function<int(int, int)> f3 = mod; return 0; } By compiling this I get: function.cc: In function ‘int main()’: function.cc:17:43: error: too few arguments to function ‘div_t div(int, int)’ 17 | std::function<int(int, int)> f2 = div(); | ^ In file included from /usr/include/c++/9/cstdlib:75, from /usr/include/c++/9/ext/string_conversions.h:41, from /usr/include/c++/9/bits/basic_string.h:6496, from /usr/include/c++/9/string:55, from /usr/include/c++/9/stdexcept:39, from /usr/include/c++/9/array:39, from /usr/include/c++/9/tuple:39, from /usr/include/c++/9/functional:54, from function.cc:1: /usr/include/stdlib.h:852:14: note: declared here 852 | extern div_t div (int __numer, int __denom) | ^~~ Why compiler raises too few arguments error in this case?
Including <functional> includes <cstdlib> which brings a function div into your current namespace. Change your struct div to struct Div and the error goes away.
73,983,024
73,983,543
Minimum number of jumps
Given an array of N integers arr[] where each element represents the max length of the jump that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element. Note: Return -1 if you can't reach the end of the array. My code -- int minJumps(int arr[], int n){ int i=0, count=0; while(i<n-1){ if(arr[i]==0){ return -1; } i+=arr[i]; count++; } return count; } Input: n=10 arr[ ]=2 3 1 1 2 4 2 0 1 1 So here first jump goes from to 2 to 1, second jump goes from 1 to 1, third jump goes from 1 to 2, fourth jump goes from to 2 to 2, fifth jump goes from 2 to 1 and last sixth jump goes from 1 to 1. So I got 6 jumps. But the answer is 4 jumps. If we start particularly from the first element, we can only have one way of going na? So I think my understanding is wrong, please explain anyone.
There are multiple ways through the array. The one you described is: 2 1 1 2 2 1 6 jumps ┌───┬─┬─┬───┬───┬─┐ 2 3 1 1 2 4 2 0 1 1 But you can also do: 1 3 2 2 1 5 jumps ┌─┬─────┬───┬───┬─┐ 2 3 1 1 2 4 2 0 1 1 ↑ jump 1 forward, not 2 You can find an optimal solution as: 1 3 1 4 4 jumps ┌─┬─────┬─┬───────┐ 2 3 1 1 2 4 2 0 1 1 For any given array, there may be more than one optimal solution. The trick is to explore them all Every time you have a decision to make, make them all. For example, given our first jump of 2, we could also choose to jump 1. Whenever you have a choice like this you will need to build yourself a recursive solution. Conveniently, you only need to return the minimal number of jumps. You do not actually have to return the jump path. So your function can be written to return exactly that information: int minJumps( int array[], int size ) The thing that will change is your starting index. You can add that as an additional argument: int minJumps( int array[], int size, int index = 0 ) Or you can just adjust the array value when you recurse: ... = minJumps( array + n, size - n ); Either way you do the same thing: index a smaller and smaller array. For example, you can easily answer for this array: 1 zero jumps. (You are at the end of the array) And this array: 0 zero jumps. (You are at the end of the array) How about this array: 1 1 Or this array: 5 1 The answer to both is 1 jump, because if we choose a jump-by-1 we get the result of 0 == end of array. For this array, though: 0 1 The answer is no jumps. So can you answer for this array? 1 1 1 Or this array? 1 5 1 How about this array? 1 0 1 Aaaannnd... how about these arrays? 2 1 1 2 0 1 The decision factor here is where recursion is useful. Each time you recurse you are working on a smaller array. For the penultimate example, I can get to the end of the array with two possible paths: ┌───┐ 1 jump 2 1 1 2 straight to end works. return 1 jump ┌─┬─┐ 2 jumps 2 1 1 recurse to get 1 jump for the end of the array. return that + 1. ↑ decision point But there is only one way with: ┌───┐ 1 jump 2 0 1 2 straight to end works. return 1 jump ┌─┬─┐ no jumps 2 0 1 recurse to get -1 for the end of the array. ↑ decision point With both of these examples we see that the minimum number of jumps is if we choose the jump-by-2. So, each time you have a decision, take them all. Ignore the bad ones (stuff that returns -1) and choose the smallest number of jumps every time. Oh, don’t forget to not jump past the end of the array. So 5 1 ↑ decision point Since the array is size 2, you cannot jump more than 1 forward. Putting it together Here are the conditions given you: You have one element in the array. Return 0. The current element is zero. Return -1. (Cannot advance.) The current element is n. Recurse for each 1,2,...,n, making sure that you do not exceed the bounds of the array. Return the smallest value you got from your recursive calls. That’s it! It takes some time to work your mind around recursion, but the main idea is to solve for the simplest case (a single element array), then solve for that with one more element. Or, if I can do a thing to the first element of an array in relation to the rest of the array, then I can do it to the whole array. Edit: I have written this answer assuming that you have not been given instruction about Graph Theory. If you have, then do as bitmask instructs and look at the algorithms you have been studying. At least one of them will apply to traversing this graph.
73,984,557
74,078,792
Why do some assignment operators for the helper classes of std::valarray return void?
For example, the assignment operators for std::slice_array: void operator=(const valarray<T>&) const; //#1 void operator=(const T&) const; //#2 const slice_array& operator=(const slice_array&) const; //#3 #1 and #2 return void, but #3 returns const slice_array&. It prohibits some code, such as: std::valarray<int> va{1, 2, 3, 4, 5, 6}; va[std::slice(3, 2, 2)] = va[std::slice(0, 2, 2)] = va[0]; Why?
While returning a reference from operator= is the common and reasonable way for implementations, keep in mind that valarray is a rarely used and an unsupported library. See C++ valarray vs. vector for more detailed answers on this topic. From one of the answers: ISTR that the main reason it wasn't removed from the standard is that nobody took the time to evaluate the issue thoroughly and write a proposal to remove it. Even before going into debates about opinions, there are bugs in the current implementation. See assigning to gslice_array gives runtime error for instance.
73,985,013
73,985,433
Beaglebone black gpio pin out not as expected, LED blink program
Im follwoing this guide: https://www.teachmemicro.com/beaglebone-black-blink-led-using-c/ And when connecting at P9_13 i do not get any LED Blinking. ( I also tried to set it manually, and can check that gpio is high, but LED is still dark). I move the right-hand side wire (green) from the breadboard to P9_2 and P9_4 and the LED light up confirming that the wiring is correct. (according to this: https://vadl.github.io/beagleboneblack/2016/07/29/setting-up-bbb-gpio that should be VDD_3V3 and SYS_5V). If i move it to P9_5 the LED does NOT light up, is there no power here? P9_13 as used in the guide is UART4_TXD, is that the one I'm supposed to use for LED blinking following this tutorial?
The guide actually is referencing P9, while shematic is according to P8. And in addition, the program should use gpio26 (not gpio23) if using P8 Header (Atleast for my board). UART is used for serial commnunication, so i guess that is not a general purpose io.... Anyway, question solved after realizing this :)
73,985,352
73,987,241
concept for check and out-of-bounds
I am trying to define a C++20 concept that enforces the implementors to check for an out of bounds. template <size_t Num> concept IsInBounds = requires (const size_t idx) { requires idx >= Num; }; So, for a method that I have in a custom container that returns a non-const reference to an element inside it, I want to check with the concept if the index required is out-of-bounds. auto mut_ref_at(const size_t idx) const -> T(&) requires IsInBounds<N> { return (T&) array[idx]; } That's obviously doesn't works: error: substitution into constraint expression resulted in a non-constant expression requires idx >= Num; function parameter 'idx' with unknown value cannot be used in a constant expression requires idx >= Num; So, if I understand something about concepts, the concept is understanding that the requires (const size_t idx) clause, where I have a parameter idx, is substituting the parameter idx of my method? And, exists some way with the concept of constraint the value idx of the mut_ref_at method to the size of the T array[N] member? Full class declaration: template <typename T, zero::size_t N> class StackArray{ private: T array[N]; public: template <typename... InitValues> StackArray(InitValues... init_values) : array{ init_values... } {} /** * @brief delete the `new` operator, since the intended usage of * the type is to be a wrapper over a C-style array. * * @return void* */ void* operator new(std::size_t) = delete; /** * @brief Returns a mut reference to the element at specified location `idx`, * with bounds checking. * * @param idx a `size_t` value for specifiying the position of * the element to retrieve. * @return T& to the element at idx position */ constexpr auto mut_ref_at(const size_t idx) const -> T(&) requires IsInBounds<N> { return (T&) array[idx]; } Edit: changed concept declaration
If you want to provide the out-of-bounds checking at compile time, you must provide the index via template parameter. You should rely on a std::size_t value to provide the index that the client code wants to retrieve, and, with the concept, index will be determined when the template is instanciated. This will lead the compiler to refuse to compile if the index is out-of-bounds. Your code will looks like: template <size_t I, size_t N> concept IsInBounds = requires () { requires I <= N; }; You use your class template parameter N to determine the array capacity. So, you can check I against N. If I is greater than N, concept will fail, and code will not compile. And your method will looks like: template <size_t I> constexpr T& mut_ref_at() requires IsInBounds<I, N> { return arr[I]; } Note that, as others pointed out, cast to (T&) it's ugly and unnecessary. Trailing return is also verbose, the return type it's clearly always T&.
73,985,869
73,989,665
Passing variables to an embedded Python script from C++
I need to run a Python script from c++, but I need also to pass it some variables. It can't be a function with parameters, because there are hundreds of variables, so the syntax would become too messy. I will post a simple example, analogue to my case. This is the Python script: script.py c = 10 * 5 + a print(c) And this is the calling code: #include "Python.h" int main() { Py_Initialize(); PyObject *pName = PyUnicode_FromString("script"); PyObject *pModule = PyImport_Import(pName);; // Add something to set the cariable "a" in the script Py_Finalize(); } Could you help with the code to add to set the variable "a" in the script?
The following will do the trick: Py_Initialize(); PyObject *locals = PyDict_New(); PyObject *globals = PyDict_New(); PyDict_SetItemString(locals, "a", PyLong_FromLong(123)); PyDict_SetItemString(locals, "b", PyLong_FromLong(9)); PyRun_FileExFlags(fopen("script.py", "r"), "script.py", Py_file_input, globals, locals, 1, NULL); Py_Finalize();
73,986,076
73,986,399
What is the difference between x+=x and x = x +y in C++
I don't understand why my two expressions produce the same result even though the second expression calls f() twice. I am using gcc with C++20 enabled. #include <iostream> using namespace std; int& f(int& i, string name); int main() { puts("\n-------------------------------------\n"); int x = 5; /* expression one */ printf("the result of (f(x) += 1) is:--> %d\n", f(x, "one") += 1); printf("x is: %d\n",x); printf("********************\n"); x = 5; /* expression two */ printf("the result is:--> %d\n", f(x, "two") = f(x, "three") + 1); printf("x is: %d\n", x); puts("\n-------------------------------------\n"); return EXIT_SUCCESS; } int& f(int& i, string name) { ++i; printf("<%s> value of i is: %d\n", name.c_str(), i); return i; } The output of my program is: ------------------------------------- <one> value of i is: 6 the result of (f(x) += 1) is:--> 7 x is: 7 ******************** <three> value of i is: 6 <two> value of i is: 7 the result is:--> 7 x is: 7 -------------------------------------
Note that this is undefined behaviour before (and correct after) C++17 which explicitly sequences evaluation of left, right sides including their side-effects. f(x, "one") += 1 is evaluated as: Evaluate right side to 1. Evaluate left side: Set i: 5->6 Return ref to i which holds 6. Evaluate += by adding one to the returned reference, setting i: 6->7. The expression is evaluated to ref to i holding 7. f(x, "two") = f(x, "three") + 1 Evaluate right side: Set i: 5->6 Return ref to i which holds 6 now. Add 1 -> right side is 7. Evaluate left side: Set i: 6->7. Return ref to i which holds 7 now. Evaluate = by assigning the right side(7) to left side(i), setting i to 7. The expression is evaluated to ref to i holding 7. In the second expression it doesn't matter what happens to i inside left f call - if it returns i ref, it will be set to 7.
73,986,528
73,986,699
subtraction of iterators that give integer number
can someone tell me what happens under in this subtraction? why did I get a number in the end? its build operator '-' or something else? int main(){ vector<int> v{5,3,8,3,9}; auto p=remove(begin(v),end(v),3); cout<<p-begin(v); return 0; } output: 3
Iterators for std::vector are LegacyRandomAccessIterators, and you can see in that link that subtracting one such iterator from another yields a difference_type. For std::vector, this is defined as "a signed integer type (usually std::ptrdiff_t)", which sounds like what you wanted. And yes, the magic occurs inside operator-() (for the iterator).
73,986,853
74,018,009
How can I create a cmake configuration for tensorflow lite?
I want to create a cmake configuration for my tensorflow lite project. The problem is that I do not know how to link my project with tensorflow. Here is my project tree: . ├── app │   ├── include │   └── src │   └── main.cpp ├── build ├── CMakeLists.txt ├── README.md └── tensorflow # <-- submodule of the tensorflow/tensorflow.git repo I want to within ./build run cmake -G Ninja .. to create the build files for ninja. This is the simple CMakeLists.txt I have right now, not linked to tensorflow and therefor won't build: cmake_minimum_required(VERSION 3.2.2) project(trash-finder-tf LANGUAGES CXX) option (FORCE_COLORED_OUTPUT "Always produce ANSI-colored output (GNU/Clang only)." TRUE) if (${FORCE_COLORED_OUTPUT}) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") add_compile_options (-fdiagnostics-color=always) elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") add_compile_options (-fcolor-diagnostics) endif () endif () add_executable(main src/main.cpp ) include_directories(main PRIVATE include/ )
This website answers the question: https://www.tensorflow.org/lite/guide/build_cmake#create_a_cmake_project_which_uses_tensorflow_lite For anyone in the future, here is my cmakelists.txt: cmake_minimum_required(VERSION 3.2.2) project(app LANGUAGES CXX) option (FORCE_COLORED_OUTPUT "Always produce ANSI-colored output (GNU/Clang only)." TRUE) if (${FORCE_COLORED_OUTPUT}) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") add_compile_options (-fdiagnostics-color=always) elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") add_compile_options (-fcolor-diagnostics) endif () endif () add_subdirectory( "tensorflow/tensorflow/lite" "$(CMAKE_CURRENT_BINARY_DIR}/tensorflow-lite" EXCLUDE_FROM_ALL) add_executable(main src/main.cpp ) include_directories(main PRIVATE include/ ) target_link_libraries(main tensorflow-lite) Though this is without the directory app/ which I chose to remove.
73,987,256
73,987,312
Why base class copy and move constructors should not be inherited?
CWG2356: Base class copy and move constructors brought into a derived class via a using-declaration should not be considered by overload resolution when constructing a derived class object. But other constructors that are inherited from the base class only initializes the base class subobject, too. So, why base class copy and move constructors should not be inherited?
Keep in mind, the default implementations of the copy/move constructors of the derived class already call the base class copy/move constructors. If the base class copy and move constructors were eligible for overload resolution, you would make the following legal, which in general is not desirable: Base b; Derived d = b;
73,988,300
74,009,824
Using a package from packages.config in C++ visual studio 2017
I am developing a code in C++ using as IDEE Visual Studio 2017 on my Windows 10 workstation. I need the onnxruntime library, so I have installed it by the NuGet package menager. The installation went ok and in my solution I have a folder Resource files and within it I have the file packages.config. Its content is: <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.ML.OnnxRuntime" version="1.12.1" targetFramework="native" /> </packages> My main.cpp is quite simple. It is a simple hello world where I try to use the installed package. But when I compile, it gives me an error on the using Microsoft.ML.OnnxRuntime; directive. I have followed the instructions in https://learn.microsoft.com/en-us/nuget/consume-packages/overview-and-workflow. #include <iostream> using namespace std; using Microsoft.ML.OnnxRuntime; int main() { cout<<"Hello world\n" return 0; }
OnnxRuntime lib and dll can be found in folder Yourproject\packages\Microsoft.ML.OnnxRuntime.XXX\runtimes\win-x64\native.Header file folder XXX\packages\Microsoft.ML.OnnxRuntime.XXX\build\native\include Try adding them as dependencies.
73,988,574
73,990,872
Given x>0, is it possible for sqrt(x) = 0 to give a floating point error?
Question in title. I have a section of code: double ccss = c * c + s * s; double sqrtCCSS = sqrt(ccss); if (sqrtCCSS != 0) { n = n1 / sqrtCCSS; } and am just wondering if this is safe: double ccss = c * c + s * s; if (ccss != 0) { n = n1 / sqrt(ccss); } My gut tells me yes, but floating point error is still somewhat mysterious. Update: At least for Python so far this seems impossible: [ins] In [4]: x = np.nextafter(0, 1) ...: print(x) ...: print(np.sqrt(x)) 5e-324 2.2227587494850775e-162 If the smallest possible float in numpy (given numpy is mostly in C, this seems relevant), cannot result in zero, the only possible number that would result in zero would have to be something that introduces grave floating point error but is not the smallest floating point number. Update: I changed the variables to satisfy comments
and am just wondering if this is safe: double xxyy = x * x + y * y; if (xxyy != 0) { n = n1 / sqrt(xxyy); } It's always safe because floating-point math doesn't trap and you can freely divide by zero or even Inf/NaN, unless you tell the compiler to trap on those cases Anyway if you just want to check whether the denominator is zero then the question on the title is actually different from what you're talking about in the question's content. The answer to the question Given x>0, is it possible for sqrt(x) to be zero? is yes, if denormals-are-zero (DAZ) and/or flush-to-zero (FTZ) are turned on. In fact most non-x86 architectures have DAZ/FTZ enabled by default, or don't even support denormals and always turn DAZ/FTZ on, because operation on denormal numbers are very slow (see Why does changing 0.1f to 0 slow down performance by 10x?). In x86 you can also turn those flags on and some compilers will turn them on by default flush-to-zero behavior in floating-point arithmetic Disabling denormal floats at the code level Setting the FTZ and DAZ Flags For example the below sample code f = 0x0Cp-1022; _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); printf("%a %a\n", f, sqrt(f)); may print 0x0.000000000000cp-1022 0x0p+0 because f is treated as zero by sqrt due to DAZ Some demo on Godbolt. And gcc demo on ideone The above snippet can also print 0x0p+0 0x0p+0 because f is treated as zero by printf due to FTZ even though it contains a non-zero denormalized value If you set DAZ/FTZ before assigning f like this _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); f = 0x0Cp-1022; printf("%a %a\n", f, sqrt(f)); then it'll likely also print 0x0p+0 0x0p+0, but in this case f can be assigned an actual zero value instead, and printing its bit pattern will result in all zero bits However if you've asked this Given x and y which aren't both zero at the same time, is it possible for sqrt(x*x + y*y) to be zero then the answer to that question is yes even if DAZ/FTZ aren't enabled, because the numbers can be so small that their product became underflow. Try something like this and see double x = 0x1p-1021; double y = 0x2p-1020; // or y = 0 double xxyy = x * x + y * y; printf("%a %a\n", x, y); printf("%a %a\n", xxyy, sqrt(xxyy));
73,988,769
73,993,565
Returning range of different containers
I have multiple containers with the same element type T. I would like to select one of the containers depending on a enum. I tried something like this: auto range = [category,system]() -> auto { switch(category) { case sound_category::voice: return std::ranges::views::all (system->dialogue_voices); // could be std::array case sound_category::mono: return std::ranges::views::all (system->mono_voices); // could be std::vector case sound_category::music: return std::ranges::views::all (system->music_voices); // could be std::list default: return std::ranges::views::all (system->sfx_voices); // could be std::deque } }(); but that will result in a compiler error, since the deduced type in the cases is different. Is there some way to achieve that?
ranges-v3 has any_view for type erasure view. So it would be something like: auto range = [category,system]() -> ranges::v3::any_view<Voice> { switch(category) { case sound_category::voice: return std::ranges::views::all (system->dialogue_voices); // could be std::array case sound_category::mono: return std::ranges::views::all (system->mono_voices); // could be std::vector case sound_category::music: return std::ranges::views::all (system->music_voices); // could be std::list default: return std::ranges::views::all (system->sfx_voices); // could be std::deque } }();
73,989,392
73,997,506
GDK: Expression must be a modifiable value
I have a function which works with GdkPixbufs (simplified): void test_function(std::vector<GdkPixbuf> &images) { std::vector<std::filesystem::path> filenames = {"path/a", "path/b"}; for(int i = 0; i < 2; i++) { images[i] = *gdk_pixbuf_new_from_file(filenames[i].string().c_str(), NULL); } return; } GCC throws expression must be a modifiable value error at the images assignment line. Everything seems fine to me. Why does it happen?
Compiling on Gtk4, I got this error, usr/include/c++/12/bits/stl_vector.h:1124:41: error: invalid use of incomplete type ‘struct _GdkPixbuf’ 1124 | return *(this->_M_impl._M_start + __n); | ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~ /usr/include/gdk-pixbuf-2.0/gdk-pixbuf/gdk-pixbuf-core.h:89:16: note: forward declaration of ‘struct _GdkPixbuf’ 89 | typedef struct _GdkPixbuf GdkPixbuf; Incomplete type means you should always refer to the type with a pointer. You can only have a vector of std::vector<GdkPixbuf*>, but not std::vector<GdkPixbuf>. This is also the expected way to work with other gtk widgets. If you are unfamiliar with incomplete type(or opaque type), the following question servers a good reference. What is an opaque value in C++?
73,989,424
74,053,302
Custom values in Qt Creator (CMake) build settings
I want to achieve the equivalent of C++ #define foo "bar" but I don't want the value "bar" to be part of my code repository, and the value will depend on whether the build is Debug or Release. How can I do this? NB: I like the idea of using the following in CMakeLists.txt add_compile_definitions(foo="bar") but I don't know how to supply "bar" from the Qt Creator build settings. Presumably I'd add a Key/Value pair but what would I put?
You need a 2 step process: Add a Qt Creator build setting to create a CMake cache variable. In CMakeLists.txt use the cache variable within a command. For your example: In Qt Creator build settings, either click Add > String setting Key to MYPROJECT_FOO and Value to bar or click Batch Edit... and add -DMYPROJECT_FOO:STRING=bar In CMakeLists, target_compile_definitions(mytarget PUBLIC foo="${MYPROJECT_FOO}") (As advised by Guillaume Racicot it's better to apply the definition to a single target, as opposed to the entire project, which would be add_compile_definitions(foo="${MYPROJECT_FOO}").) See also Qt Creator documentation CMake Build Configuration: Modifying Variable Values. Thanks to Guillaume Racicot for deeper explanation of how CMake cache variables can be used.
73,990,029
74,508,778
Difference between a vector and a dynamically allocated array
What are the internal differences of choosing to use an std::vector vs a dynamically allocated array? I mean, not only performance differences like in this matching title question. I mean, I try to design a library. So I want to offer a wrapper over an StackArray, that is just a C-Style array with some member methods that contains as a member T array[N]. No indirections and the new operator removed to force the implementor to have a array type always stored in the stack. Now, I want to offer the dynamic variant. So, with a little effort, I just can declare something like: template <typename T> class DynArray { T* array, size_t size, size_t capacity }; But... this seems pretty similar to a base approach to a C++ vector. Also, an array stored in the heap can be resized by copying the elements to a new mem location (is this true?). That's pretty much the same that makes a vector when a push_back() operation exceeds its allocated capacity, for example, right? Should I offer both API's if exists some notable differences? Or I am overcomplicated the design of the library and may I just have my StackArray and the Vector should be just the safe abstraction over a dynamically allocated array?
First there is a mindset (usually controversial) between the usage of the modern tools that the standard provides and the legacy ones. You usually must be studing and asking things about C++ modern features, not comparing them with the old ones. But, for learning purposes, I have to admit that it's quite interesting dive deep somethimes in this topics. With that in mind, std::vector is a collection that makes much more that just care about the bytes stored in it. There is a constraint really important, that the data must lie in contiguous memory, and std::vector ensures this in its internal implementation. Also, has an already well known, well tested implementation of the RAII pattern, with the correct usage of new[] and delete[] operators. You can reserve storage and emplace_abck() elements in a convenient and performant way which makes this collection really unique... there are really a lot of reasons that shows why std::vector is really different from a dynamically allocated array. Not only is to worry about manual memory management, which almost an undesirable thing to do in modern C++ (embedded systems, or operating system themselves are a good point to discuse this last sentence). It's about to have a tool, std::vector<T> that makes your life as developer easier, specially in a prone-error language like C++. Note: I say error-prone because it's a really hard to master language, which needs a lot of study and training. You can make almost everything in the world, and has an incredible amount of features that aren't begginer friendly. Also, the retrocompatibility constraint makes it really bigger, with literally thousand of things that you must care about. So, with a great power, always comes a great responsability.
73,990,342
73,992,226
Showing the unlock from std::condition_variable::wait
I've read from https://en.cppreference.com/w/cpp/thread/condition_variable/wait that wait() "Atomically unlocks lock". How do I see this via std::cout? I am trying to understand conditional variables better on what they're actually doing. I've wrote an attempt below. #include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <thread> using namespace std; condition_variable cv; mutex m; bool stopped = false; void f1() { unique_lock<mutex> ul{m}; cout << "f1: " << ul.owns_lock() << endl; cv.wait(ul, [&]{ cout << "f1: " << ul.owns_lock() << endl; return stopped; }); cout << "f1 RUNNING\n"; cout << "f1: " << ul.owns_lock() << endl; } void f2() { lock_guard<mutex> lg{m}; cout << "f2 RUNNING\n"; } int main() { unique_lock<mutex> ul{m}; thread t1(&f1); thread t2(&f2); cout << ul.owns_lock() << endl; this_thread::sleep_for(chrono::seconds(1)); stopped = true; cv.notify_one(); cout << ul.owns_lock() << endl; ul.unlock(); cout << ul.owns_lock() << endl; this_thread::sleep_for(chrono::seconds(1)); t1.join(); t2.join(); return 0; }
std::unique_lock and std::lock_guard work with any class type that satisfies the requirements of BasicLockable. So, just write your own class that wraps a std::mutex, then you can add whatever logging you want. UPDATE: However, std:condition_variable only works with std::mutex specifically, so if you write your own mutex wrapper class then you will have to use std::condition_variable_any instead. For example: #include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <thread> using namespace std; struct LoggingMutex { mutex m; void lock() { cout << "Locking" << endl; m.lock(); cout << "Locked" << endl; } bool try_lock() { cout << "Attempting to lock" << endl; bool result = m.try_lock(); cout << (result ? "Locked" : "Not locked") << endl; return result; } void unlock() { cout << "Unlocking" << endl; m.unlock() cout << "Unlocked" << endl; } }; condition_variable_any cv; LoggingMutex lm; bool stopped = false; void f1() { unique_lock<LoggingMutex> ul{lm}; cout << "f1: " << ul.owns_lock() << endl; cv.wait(ul, [&]{ cout << "f1: " << ul.owns_lock() << endl; return stopped; }); cout << "f1 RUNNING\n"; cout << "f1: " << ul.owns_lock() << endl; } void f2() { lock_guard<LoggingMutex> lg{lm}; cout << "f2 RUNNING\n"; } int main() { unique_lock<LoggingMutex> ul{lm}; thread t1(&f1); thread t2(&f2); cout << ul.owns_lock() << endl; this_thread::sleep_for(chrono::seconds(1)); stopped = true; cv.notify_one(); cout << ul.owns_lock() << endl; ul.unlock(); cout << ul.owns_lock() << endl; this_thread::sleep_for(chrono::seconds(1)); t1.join(); t2.join(); return 0; }
73,990,548
73,990,575
How to provide C++ version when extending python
I want to make c++ code callable from python. https://docs.python.org/3/extending/ explains how to do this, but does not mention how to specify c++ version. By default distutils calls g++ with a bunch of arguments, however does not provide the version argument. Example of setup.py: from distutils.core import setup, Extension MOD = "ext" module = Extension("Hello", sources = ["hello.cpp"]) setup( name="PackageName", version="0.01", description="desc", ext_modules = [module] ) I'm using linux, if that matters.
You can pass compiler arguments as extra_compile_args so for example module = Extension( "Hello", sources = ["hello.cpp"], extra_compile_args = ["-std=c++20"] )
73,990,941
74,014,524
How to find out the coordinates of the two vertices of a TopoDS_Edge (Openscascade)?
I want to find out the coordinates of the two vertices of a TopoDS_Edge. I couldn't find any solution on the Public Member Functions list on https://dev.opencascade.org/doc/refman/html/class_topo_d_s___edge.html
With this you can get the vertices of any topological object in OpenCascade: TopoDS_Edge edge; for (TopExp_Explorer ex(edge, TopAbs_VERTEX); ex.More(); ex.Next()) { gp_Pnt point = BRep_Tool::Pnt(TopoDS::Vertex(ex.Current())); double xCoord = point.X(); } This is also capable of iterating over other types of topological entities like edges in a body when you replace TopAbs_VERTEX with TopAbs_EDGE.
73,991,485
73,992,662
What parameters should I put in functions
How do I know which variables to declare as parameters and which ones I should just declare inside the function?
Let's say I want to write a function that prints a name. So you can say that the function needs information that is not in the function. One method is to ask the User: void print_name() { std::string name; std::cout << "Enter name: "; std::cin >> name; std::cout << "\nname is: " << name << "\n"; } The above function is limited in usage: a Console or User is required. For example, if I have a list of names, I can't use the above function to print the names. So, the function will need information from elsewhere. The information will be passed by parameter. The parameter contains information for the print function: void print_name_from_parameter(const std::string& name) { std::cout << "Name is " << name << "\n"; } The print_name_from_parameter function is more versatile than the above print_name function. The name to print can come from anywhere, database, other computers, other devices, etc. The print_name function is restricted to inputting the name from the console (keyboard). There are many platforms that don't have a keyboard, so the name can't be input.
73,991,545
73,991,845
Can I avoid a second object when using a unary operator on a temporary?
The usual meaning of unary operators such as bitwise inversion, postfix increment, and unary minus is to return a modified copy of their argument. When their argument is a temporary, is there a way to modify that original object, thus avoiding the creation and destruction of a second object? The examples below both involve two objects: #include <utility> #include <iostream> using namespace std; struct X { ~X() { cout << "destroy\n"; } X() { cout << "default construct\n"; } X(const X& ) { cout << "copy construct\n"; } X( X&&) { cout << "move construct\n"; } X& operator=(const X& ) { cout << "copy assign\n"; return *this; } X& operator=( X&&) { cout << "move assign\n"; return *this; } X operator~() const & { cout << "~lvalue\n"; return *this; } X operator~() && { cout << "~rvalue\n"; return move(*this); } }; int main(int, char**) { { cout << "Example 1\n"; auto a = X(); auto b = ~a; } { cout << "Example 2\n"; auto a = ~X(); } } I get this output (ignore that ~lvalue and copy construct "appear" out of order): Example 1 default construct ~lvalue copy construct destroy destroy Example 2 default construct ~rvalue move construct destroy destroy Is there a way to rewrite the struct so that example 2 only creates and destroys a single object?
Is there a way to rewrite the struct so that example 2 only creates and destroys a single object? But your code says to create two objects. You create a prvalue and then perform an operation on it which is not initializing some other object. That operation requires manifesting a temporary from that prvalue. That's object 1. Then you use auto a to create a new object. That's object 2. It doesn't matter what operator~ is doing; you must manifest a temporary from the prvalue, since operator~ needs to have a this. Even if the return value is a && to this (which is absolutely should not, because operator~ should be a const function), that wouldn't help, because a is a separate object. You can move construct a, but it won't ever not be a separate object. If you only want one object, you have to use code that says to create only one object: auto a = X(); a.invert();.
73,991,660
73,991,924
Vulkan RAII. Got VK_ERROR_NATIVE_WINDOW_IN_USE_KHR when trying to create VkSurfaceKHR
I'm learning Vulkan_raii API and ran into this problem: I have the source file: #include <vulkan/vulkan_raii.hpp> #include <GLFW/glfw3.h> #include <iostream> int main() { glfwInit(); GLFWwindow *window = glfwCreateWindow(800, 600, "First window", nullptr, nullptr); if (!window) { std::cerr << "Failed to create a window!" << std::endl; return 0; } vk ::raii::Context context; uint32_t version = context.enumerateInstanceVersion(); vk::ApplicationInfo appInfo{"instance", version, "instance", version, version}; vk::InstanceCreateInfo create_info{ vk::InstanceCreateFlags{},nullptr, 0, nullptr, 0, nullptr }; vk::raii::Instance instance{context, create_info}; VkSurfaceKHR c_style_surface; auto res = glfwCreateWindowSurface(*instance, window, nullptr, &c_style_surface); if (res != VK_SUCCESS) { std::cerr << "Failed to create a surface! ERROR: " << res << std::endl; return 0; } } And when I compiled and run it, I got this: Failed to create a surface! ERROR: -1000000001 I found that this error code is VK_ERROR_NATIVE_WINDOW_IN_USE_KHR. GLFW sources describe this code as "The requested window is already connected to a VkSurfaceKHR, or to some other non-Vulkan API". But I can't even imagine how my window can be already connected to the surface. Does anyone know what causes this error and how to fix it in my example? Thank you in advance.
But I can't even imagine how my window can be already connected to the surface. Because that's what glfwCreateWindow does. The library is called "GLFW" because, by default, it creates OpenGL windows. Which counts as "some other non-Vulkan API". If you want to use it with Vulkan, you have to follow special rules for that. Rules that include telling it not to attach OpenGL to the window via glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API).
73,992,048
73,995,287
Detect if there is an error when importing a point cloud and display alert message without closing application PCL and C++
I am trying to import a point cloud into a program I have made with the PCL and C++ library. This program must be able to load different files and that, in case of encountering one that has some error at the time of having made its coding, it indicates that there has been an error but in no case makes the application break. The header of a point cloud that right now is causing the program to break is as follows. ply format ascii 1.0 comment PCL generated element vertex 88655 property float x property float y property float z property uchar red property uchar green property uchar blue element face 0 element camera 1 property float view_px property float view_py property float view_pz property float x_axisx property float x_axisy property float x_axisz property float y_axisx property float y_axisy property float y_axisz property float z_axisx property float z_axisy property float z_axisz property float focal property float scalex property float scaley property float centerx property float centery property int viewportx property int viewporty property float k1 property float k2 end_header And I'm trying to import the cloud as pcl::PointCloud<pcl::PointXYXRGB> and also as a pcl::PolygonMesh. In this case, the cloud does not have mesh information but as far as I was noticing with other clouds, the system is able to detect it and import it without any problem. The code I'm using to import the files is: std::string filepath = "cloud.ply"; // Load cloud pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::PolygonMesh::Ptr cloud_mesh (new pcl::PolygonMesh); if (pcl::io::loadPLYFile(filepath_cloud, *cloud) == -1) { std::cerr << "Error reading cloud" << std::endl; } std::cout << "Reading cloud OK" << std::endl; if (pcl::io::loadPolygonFilePLY(filepath_cloud, * cloud_mesh) == -1) { std::cerr << "Error reading cloud mesh" << std::endl; } std::cout << "Reading cloud mesh OK" << std::endl; Whith this code I obtain these messages until the application crush: [pcl::PLYReader] C:/Users/Ale/Documents/tmp/cloud.ply:25: property 'float32 focal' of element 'camera' is not handled [pcl::PLYReader] C:/Users/Ale/Documents/tmp/cloud.ply:26: property 'float32 scalex' of element 'camera' is not handled [pcl::PLYReader] C:/Users/Ale/Documents/tmp/cloud.ply:27: property 'float32 scaley' of element 'camera' is not handled [pcl::PLYReader] C:/Users/Ale/Documents/tmp/cloud.ply:28: property 'float32 centerx' of element 'camera' is not handled [pcl::PLYReader] C:/Users/Ale/Documents/tmp/cloud.ply:29: property 'float32 centery' of element 'camera' is not handled [pcl::PLYReader] C:/Users/Ale/Documents/tmp/cloud.ply: property 'float32 k1' of element 'camera' is not handled [pcl::PLYReader] C:/Users/Ale/Documents/tmp/cloud.ply: property 'float32 k2' of element 'camera' is not handled Reading cloud OK Warning: Can't find property 'vertex_indices' in element 'face' So, what you can see is that, until the time comes to import it to pcl::PolygonMesh, no error occurs. What I want to manage is that, although it is not possible to be read as polygonmesh, the application does not close. In other words, to put the reading of pcl::PolygonMesh in a kind of try{} catch{} so that it simply reads the file if possible. But I don't know if that can be done or what, if it can be done, how it would have to be done.
Try pcl::io::loadPLYFile() (https://pointclouds.org/documentation/group__io.html#ga0cfc645cc531647728e16088b6342204) instead of pcl::io::loadPolygonFilePLY()
73,992,176
73,992,395
Segfault when deleting from a set C++
Segfaulting code Hey all, was just wondering how to delete elements from a set if its detected in another set. The current code iterates through both sets using a for loop, then if the value the iterators hold is the same, it attempts to erase from the first set. It would look something like this: #include <iostream> using namespace std; #include <vector> #include <string> #include <set> int main() { set<int> myset; set<int> myset2; for (int i = 0; i < 10; i++) { myset.insert(i); } for (int i = 0; i < 5; i++) { myset2.insert(i); } for (auto iter = myset.begin(); iter != myset.end(); iter++) { for (auto iter2 = myset2.begin(); iter2 != myset2.end(); iter2++) { if (*iter == *iter2) { myset.erase(*iter); } } } for (auto it = myset.begin(); it != myset.end(); it++) { cout << *it; } }
The simple solution is to use one for loop. for (auto val : myset2) myset.erase(val); and not the doubly-nested for loop you're using now. The std::set::erase can erase by key or iterator. All you need to do is provide the key element in this case. Full example.
73,992,532
73,999,129
Segfault when reading ELF Shdr of own executable
I'm trying to read the symbol table of the program's own ELF binary as part of a symbolizer. Part of this involves finding the ELF start, then ELF shdr, etc. I must be doing something wrong, though, because despite e_shoff matching what I see by readelfing the binary manually and the start address looking reasonable, I cannot read the shdr. #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <assert.h> #include <dlfcn.h> #include <elf.h> #include <link.h> #include <stdio.h> #include <stdlib.h> static int findELFStartCallback(struct dl_phdr_info *info, size_t size, void *data) { static_cast<void>(size); static int address_found = 0; if (address_found) { return 0; } address_found = 1; fprintf(stderr, "relocation: 0x%lx\n", (long)info->dlpi_addr); for (ElfW(Half) i = 0; i < info->dlpi_phnum; i++) { if (info->dlpi_phdr[i].p_type == PT_LOAD) { auto result = reinterpret_cast<void *>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); fprintf(stderr, "a.out loaded at %p\n", result); *reinterpret_cast<void **>(data) = result; break; } } return 0; } static void *findELFStart() { void *result = nullptr; dl_iterate_phdr(findELFStartCallback, &result); return result; } static void checkELF(ElfW(Ehdr) * ehdr) { assert(ehdr->e_ident[EI_MAG0] == ELFMAG0 && "bad magic number"); assert(ehdr->e_ident[EI_MAG1] == ELFMAG1 && "bad magic number"); assert(ehdr->e_ident[EI_MAG2] == ELFMAG2 && "bad magic number"); assert(ehdr->e_ident[EI_MAG3] == ELFMAG3 && "bad magic number"); } int main(int argc, char *argv[]) { char *exe_ = nullptr; exe_ = reinterpret_cast<char *>(findELFStart()); assert(exe_ != nullptr && "could not find ELF header"); checkELF(reinterpret_cast<ElfW(Ehdr) *>(exe_)); auto elf = reinterpret_cast<ElfW(Ehdr) *>(exe_); fprintf(stderr, "e_shoff is %ld (0x%lx)\n", elf->e_shoff, elf->e_shoff); auto shdr = reinterpret_cast<ElfW(Shdr) *>(exe_ + elf->e_shoff); fprintf(stderr, "shdr is %ld (%p)\n", (size_t)shdr, (void*)shdr); const char *str = exe_ + shdr[elf->e_shstrndx].sh_offset; // boom } I get a segfault. When I load it in GDB, it looks like shdr is indeed a bad pointer. What am I missing here? Sample output: computer% ./p/dladdr relocation: 0x0 a.out loaded at 0x400000 e_shoff is 24528 (0x5fd0) shdr is 4218832 (0x405fd0) zsh: segmentation fault (core dumped) ./p/dladdr computer% EDIT: After seeing Reading ELF header of loaded shared object during runtime maybe the sections just aren't loaded into memory... EDIT: I finished the symbolizer and it's available here
maybe the sections just aren't loaded into memory... That's exactly right. Here is readelf -WS /bin/date on my system: Section Headers: [Nr] Name Type Address Off Size ES Flg Lk Inf Al [ 0] NULL 0000000000000000 000000 000000 00 0 0 0 [ 1] .interp PROGBITS 0000000000000318 000318 00001c 00 A 0 0 1 [ 2] .note.gnu.property NOTE 0000000000000338 000338 000050 00 A 0 0 8 [ 3] .note.gnu.build-id NOTE 0000000000000388 000388 000024 00 A 0 0 4 [ 4] .note.ABI-tag NOTE 00000000000003ac 0003ac 000020 00 A 0 0 4 ... [26] .bss NOBITS 000000000001a0a0 019098 000130 00 WA 0 0 32 [27] .gnu.build.attributes NOTE 000000000001c1d0 019098 000248 00 0 0 4 [28] .gnu_debuglink PROGBITS 0000000000000000 0192e0 000024 00 0 0 4 [29] .gnu_debugdata PROGBITS 0000000000000000 019304 0005a0 00 0 0 1 [30] .shstrtab STRTAB 0000000000000000 0198a4 00013e 00 0 0 1 Note that .shstrtab does not have the A (allocated) flag. The contents of this section is not used at runtime, so there is no reason to load it into memory, and so it isn't. If you want to access .shstrtab, you need to either read it from the file on disk, or mmap the entire file (the kernel only mmaps the parts covered by PT_LOAD segments, not the entire file).
73,992,908
73,992,993
Manipulation with an array using iterators
I want to reverse an array of chars using 2 iterators, but i figured out that i entry the loop once and swap() never worked. ` std::vector<char> s = {'a','b','c','d'}; std::vector<char>::iterator it1{s.begin()}, it2{s.end() - 1}; while(it1 < it2){ swap(it1,it2); ++it1; --it2; } ` If i write while(it1 != it2),I will never get out of the loop. Could you explain where the mistake is.
The problem is that the std::swap function requires two references. The iterators need to be dereferenced for the swap, as you are swapping the values that the iterators point to, not the iterators themselves. swap(it1, it2); needs to be replaced with swap(*it1, *it2); The rest of your code seems to be fine and without any errors. I haven't used iterators before, but it seems that they behave a lot like pointers. Apologies for any errors as this is my first answer.
73,993,084
73,993,278
Why does Gio::Settings require a delay?
I'm writing an application in C++ that uses both Qt and GIO. It happens to be an embedded Linux platform, but I don't know if that matters much. I have a function that sets a setting that another program uses: void setCityName(const QString &cityName) { const Glib::RefPtr<Gio::Settings> settings = Gio::Settings::create("org.example.city"); settings->set_string("city-name", cityName.toUtf8().data()); } This is done at the very end of my program appears to work, but only if I add a delay: void finish(QString* cityname) { qDebug() << "Cityname: " << *cityname; setCityName(*cityname); // TODO: this is an ugly hack. Without it, the settings // do not seem to take effect, but I can find no reason // for this. std::this_thread::sleep_for(200ms); emit done(); } I have instrumented the code and verified that cityname which belongs to another object, is not destroyed until after this code runs, either with or without the delay. Without the delay, everything appears to run normally, but the settings are not actually changed. Can someone explain why the delay is necessary, and how I can replace it with something more elegant?
As the documentation says: Writes made to a GSettings are handled asynchronously. Call Gio::Settings.sync: https://docs.gtk.org/gio/type_func.Settings.sync.html
73,993,434
73,993,683
Method pointer and constness
Consider the following hypothetical example: template<typename T, typename R, typename... Ps> R call(T& t, R (T::*method)(Ps...), Ps... ps){ return (t.*method)(ps...); } struct A{ int f(int i) const {return i;} }; A a; Then call(a, &A::f, 3) wont compile, because f is const. Can I make call work without providing the following overload: template<typename T, typename R, typename... Ps> R call(T& t, R (T::*method)(Ps...) const, Ps... ps){ return (t.*method)(ps...); }
There is already a standard library function that allows calling any callable, including member function pointers. You can simply use that for your wrapper function and it will automatically allow using any kind of callable as well: With C++20: decltype(auto) call(auto&& f, auto&&... args) { /* do whatever you want here */ return std::invoke(decltype(f)(f), decltype(args)(args)...); } This would be passed the member function pointer as first argument, the class object as second argument and the member function arguments after that. If you need access to the class object you can split this out and use the member function pointer call syntax specifically: decltype(auto) call(auto&& f, auto&& t, auto&&... args) { /* do whatever you want with t here */ return (decltype(f)(f).*decltype(t)(t))(decltype(args)(args)...); }
73,993,667
73,993,697
Why does Microsoft use types like __int32 etc instead of int32_t?
While browsing the implementation of standard library headers in Visual Studio with C++ 20, I came across the type __int64, it looked like a built-in type and I couldn't go to its definition. I googled it and found this article by Microsoft. Apparently the types __int32, __int64 etc are Microsoft-specific built-in types. I wondered why Microsoft uses these types instead of the non-Microsoft-specific int32_t, int64_t types, shouldn't they achieve the same thing? When I went to the definitions of those, they were just typedefs for types like int and long long, but I assume the implementation still guarantees that types like int32_t have the amount of bits you'd expect. If these types/typedefs are good enough and reliable for the normal user, why does Microsoft use their own ones? If there's an advantage to using these types, why didn't they typedef int32_t etc as __int32 etc? Is there a situation where I might want to use types like __int32 over int32_t?
Because MSVC existed long before C++11 was introduced. For things that need a fixed size obviously they have to user their own internal type. That's why those have the __ prefix because the standard says that names beginning with double underscores are reserved in the global namespace That's also the reason why lots of libraries define their own fixed-width types or even C and C++ keywords, for exampe gstreamer's guint32, gint..., OpenCL's cl_int and cl_uint..., Qt's quint32, quint64..., boost's boost::uint32_t, zlib's z_off64_t... because only decades after their advent the standard stdint.h would come into existence Why do so many libraries define their own fixed width integers? Why do c++ libraries often define their own primitive types?
73,993,910
73,994,076
Fastest way to read / write text file, excluding specific string
I am writing a program which reads large (10Gb+) text files, structured in chunks, like this: @Some_header ATCCTTTATTCGGTATCGGATATATTACGCGCGGGGGATATCGGGG + FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF::::::::: @Some_header unfixable_error ATTTATTTAGAGGAGACTTTTATTTACCCCCCCCGGGGGGATTTTA + FFFFFFF:::::::::::::::FFFFFFFFFFUUUUUUUFFUUFUU @Some_header ATTATTCCCCTTTTTATACCGGGGGGAAATTAGGGGGGGCCCCTTT + FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF A chunk consists of the @header, the ATCG sequence, the '+', and then another string with the same length as the ATCG sequence. Some @header lines have 'unfixable_error' just before the newline. My program must read through these files and write all chunks, except for those with a @header unfixable_error, to a new file. Currently, my approach is to utilize 'getline()', like so: std::ifstream inFile(inFileStr); std::ofstream outFile(outFileStr); std::string currLine; while (getline(inFile, currLine)) { if (currLine == "+" || currLine.substr(currLine.length()-5, 5) != "error") { outFile << currLine << std::endl; } else { for (int i = 0; i < 3; i++) { getline(inFile, currLine); } } } inFile.close(); outFile.close(); I'm certain there's a better solution to this, however. What is the fastest feasible way to accomplish this?
Here is few points: substr creates a new string which is quite expensive for a simple comparison. You can use string views since C++17 to avoid new strings to be created. An alternative solution is to use compare with a position and size. Since C++20, there is also ends_with which is simpler here. std::endl flushes the output which is inefficient. Please consider just using '\n' instead. getline tends to be a bit slow in practice. You can read big chunks and parse it yourself while avoiding copies as much as possible. Writting chunks is more efficient too. The chunks needs not to be too big so to fit in the caches of the CPU (the RAM is slow compared to caches). For example, skipping lines with getline is not efficient since it copies data in memory. With chunks, you can directly search for the next three \n without any write. This operation can be easily vectorized using SIMD instruction so it can be very fast (compilers should be able to do that for you). Pre-reserving some space for currLine might result in a small speed up. One can try to parallelize the algorithm but it certainly does not worth it since the processing should be IO bound (unless if the files are cached or you use a high-performance Nvme SSD) and it is not easy.
73,993,950
73,994,559
Create *.o files in a separate folder
I'm trying to make so that the *.o files are kept in /bin however after running it, the *.o files are not kept. my file systems is as follows: > bin > src *.cpp > headers *.h makefile . CC := g++ CFLAGS := -Isrc/headers NAME := run SRC := src/ HSRC := $(SRC)/headers/ OBJ := bin/ SOURCES := $(wildcard $(SRC)*.cpp) DEPS = $(wildcard $(HSRC)*.h) OBJECTS := $(patsubst $(SRC)*.cpp,$(OBJ)*.o,$(SOURCES)) $(OBJ)/%.o: %.cpp $(DEPS) $(CC) -c -o $@ $< $(CFLAGS) $(NAME): $(OBJECTS) $(CC) -o $@ $^ $(CFLAGS) .PHONY: clean clean: rm -f $(NAME) $(OBJ)/*.o *~ core $(INCDIR)/*~
Your main, high-level problem is that you are not testing the makefile as you develop it, so the bugs pile up before you know they're there. The first concrete problem is that your assignment to OBJECTS is incorrect, and doesn't work the way you think it does. The patsubst function uses %, not *, so it ought to be: OBJECTS := $(patsubst $(SRC)%.cpp,$(OBJ)%.o,$(SOURCES)) The second is that you have not decided whether OBJ should contain a trialing slash. It shouldn't, but that's not the point; the point is that you must be consistent. Look here: OBJ := bin/ ... $(OBJ)/%.o: %.cpp $(DEPS) ... See the problem? You have written a rule that will match bin//foo.o but not bin/foo.o, so Make will never invoke it. We must pick one convention or the other; for purposes of this Answer I will pick this one: OBJ := bin Third, when you wrote that rule you appear to have overlooked the fact that you put the source files in their own directory, so we must modify it: $(OBJ)/%.o: $(SRC)%.cpp $(DEPS) There is still some room for improvement, but this will work.
73,993,979
74,128,070
C++ function somehow prevents main from being invoked
I encountered a strange issue in C++ and OpenCV2. The following code does not print "I ran!": #include <iostream> #include <opencv2/opencv.hpp> // Opens image as grayscale and saves it to save_dir int grayscale_file(const cv::String &file_dir, const std::string &save_dir){ cv::Mat fi = cv::imread(file_dir, cv::ImreadModes::IMREAD_GRAYSCALE);// Loads image as grayscale return cv::imwrite(save_dir, fi); } int main(int argc, char* argv[]){ std::cout << "I ran!" << std::endl; return 0; } However when I remove the code inside grayscale_file, it prints "I ran!": #include <iostream> #include <opencv2/opencv.hpp> // Opens image as grayscale and saves it to save_dir int grayscale_file(const cv::String &file_dir, const std::string &save_dir){ return 0; } int main(int argc, char* argv[]){ std::cout << "I ran!" << std::endl; return 0; } Why does the first piece of code prevent "I ran!" from being printed to the terminal, whereas the second piece of code doesnt? Edit: Commenting some things out lead me to the issue of the cv::imread function. Removing the line that uses this lets the program run. I found a post here that explains it pretty well. I'll find a debug library instead of the release that I think I was using.
After weeks of head-scratching and research, I eventually figured out that my debugger was throwing an error at me (as pointed out in the comments). I was able to find info on fixing it from this question, which lead me to believe that my libraries were still not properly linked. I am not 100% sure on why or how the error came to be, or how I fixed it, but I essentially used MSYS2's library installer to install OpenCV via this page. Information on the pacman command and installing the libraries was originally found on this question. My final code and *.json files are as follows: tasks.json { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe build active file", "command": "C:/msys64/mingw64/bin/g++.exe", "args": [ "-g", "${file}", "-fdiagnostics-color=always", "-I\"C:\\msys64\\mingw64\\include\\opencv4\"", "-L\"C:\\msys64\\mingw64\\bin\"", "-lopencv_imgcodecs460", "-lopencv_highgui460", "-lopencv_core460", "-o", "${fileDirname}/corrscii.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } c_pp_properties.json { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "C:/Program Files/Cpp_Libs/OpenCV-MinGW-Build-OpenCV-4.5.5-x64/include" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "compilerPath": "C:\\msys64\\mingw64\\bin\\gcc.exe", "cStandard": "gnu17", "intelliSenseMode": "windows-gcc-x64", "cppStandard": "c++23" } ], "version": 4 } main.cpp #include <iostream> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <opencv2/core.hpp> int main(int argc, char* argv[]){ cv::String img_path = "C:\\path\\to\\a_photo.png"; cv::Mat img = cv::imread(img_path); if (img.empty()){ std::cout << "Error: inputted file cannot be read" << std::endl; return 1; }; return 0; } I hope this helps anybody who may come across it.
73,994,094
73,994,126
I am trying to loop inserting elements into a set if they intersect, but it isn't giving me what im looking for
all and all2 are both string sets. all is filled with actors in movie1, and all2 is empty. my loop is supposed to check if an actor in movie2 is also in movie1, and if they are then to insert that actor in all2. However my code is just outputting all the actors in movie2. all = imdb.find_actors_in_a_movie(matchedMovie1); for (auto i = actors_in_movie2.begin(); i != actors_in_movie2.end(); i++) { if (all.count(*m) > 0) { all2.insert(*m); } } all holds Christopher Walken, Leonardo DiCaprio, Martin Sheen, Tom Hanks actors_in_movie2 holds Greg Kinnear, Meg Ryan, Parker Posey, Tom Hanks The output I receive is Greg Kinnear, Meg Ryan, Parker Posey, Tom Hanks. It should only be outputting Tom Hanks.
Instead of writing a loop, use std::set_intersection. #include <string> #include <set> #include <algorithm> #include <iterator> #include <iostream> int main() { std::set<std::string> all = {"Joe", "Jack", "Mary", "Frank"}; std::set<std::string> actors_in_movie2 = {"James", "Jack", "Philip", "Frank"}; std::set<std::string> all2; std::set_intersection(actors_in_movie2.begin(), actors_in_movie2.end(), all.begin(), all.end(), std::inserter(all2, all2.end())); for (auto& n : all2) std::cout << n << "\n"; } Output: Frank Jack Since a std::set stores the names sorted, and std::set_intersection requires a sorted sequence to work correctly, using std::set_intersection is a ready-made solution. Live Example using your input
73,994,270
73,994,302
Are temporaries created as arguments in a call guaranteed to hold their lifetimes until the function call returns?
I need to return char arrays from a method what() to be used in printf() and variants. The obvious solution of printing to a (thread local) static internal buffer obviously does not work because of the multiple calls problem. #include <cstdio> unsigned int counter = 1; const char* what() { static char buf[8]; buf[0] = counter % 10 + '0'; buf[1] = '\0'; counter += 1; return buf; } int main( int argc, char* argv[] ) { printf( "%s %s\n", what(), what() ); } Prints "2 2" instead of "1 2". $ g++ test.cpp -o test $ ./test 2 2 So I thought of creating a fixed size temporary buffer as in template <std::size_t N> struct TinyString { char buf[N]; }; and implement the what() routine in a way that it returns a TinyString that will outlive the call. unsigned counter = 1; TinyString<4> what() { TinyString<4> s; s.buf[0] = counter % 10 + '0'; s.buf[1] = '\0'; counter += 1; return s; } The call is similar int main() { printf( "%s %s\n", what().buf, what().buf ); } When I run this code it produces the right results 1 2 $ g++ test2.cpp -o test2 $ ./test2 1 2 Now the question is if the two temporaries are guaranteed by the C++ standard to outlive the printf() call or it's UB in any way.
Yes it's well-formed. [class.temporary]/4 Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created. That means the two temporaries will be destroyed after the invocation of printf (immediately).
73,994,546
74,154,670
Node-addon-api - construct ObjectWrap from C++
I'm new to NAPI, and I'm trying to convert and old Nan code to NAPI. What happens is that I have a structure like this: class PointWrapper : public Napi::ObjectWrap<PointWrapper> { public: static void init(Napi::Env env, Napi::Object exports); PointWrapper(const Napi::CallbackInfo& info); private: Point point; } And I wrapped everything in the right way, so if I call on JS new Pointer(1, 2) it'll instantiate a PointerWrapper and set the right fields to Point. So far, so good. Now, the problem is that somewhere later I have a C++ code that wraps a Range - a Range is basically start and end, each containing a Point. I also have RangeWrapper that does the same thing as PointWrapper, but for range. This RangeWrapper have a getStart that basically needs to return a PointWrapper. Now, how do I instantiate a PointWrapper from RangeWrapper? Basically, I want a constructor on PointWrapper that, giving a Point, I can get a PointWrapper, all this in C++ and not on JS. Is it possible? Every code I saw tried to instantiate from inside PointWrapper, never outside
Ok, so I found a solution - it's clumsy, but at least it works. The first thing I had to do was to make the "constructor" a variable that other places could use. So I changed my class to have a *constructor pointer: class PointWrapper : public Napi::ObjectWrap<PointWrapper> { public: static void init(Napi::Env env, Napi::Object exports); PointWrapper(const Napi::CallbackInfo& info); static Napi::FunctionReference *constructor; // <-- Added this private: Point point; }; Then on my init implementation (file point-wrapper.cpp), I am using this constructor to "construct" the Point: Napi::FunctionReference *PointWrapper::constructor; // <-- Added this void PointWrapper::init(Napi::Env env, Napi::Object exports) { Napi::Function func = DefineClass(env, "Point", { // methods, etc... }); constructor = new Napi::FunctionReference(); // <-- Used it here *constructor = Napi::Persistent(func); // <-- and here exports.Set("Point", func); } So, to instantiate the PointWrapper what I need is to call the constructor then unwrap things. Now, the class itself only have one possible constructor, that receives a Napi::CallbackInfo& info. To instantiate this class with something from C++ side, we need to "wrap" a C++ object into Napi::External: // Supposing you have a point already created: auto wrapped = Napi::External<Point>::New(env, &Point); Napi::Value pointWrapperAsVal = PointWrapper::constructor->New({ wrapped }); Finally, you make the controller understand that it can be called with a Napi::External object: PointWrapper::PointWrapper(const Napi::CallbackInfo& info) : Napi::ObjectWrap<PointWrapper>(info) { if(info[0].IsExternal()) { auto point = info[0].As<Napi::External<Point>>(); this->point = *point.Data(); } else { // normal code } } Remember that pointWrapperAsVal is a Napi::Value. You may need to convert to the right "type" if you need to use it from CPP - for example, with PointWrapper::Unwrap(pointWrapperAsVal)
73,995,409
73,995,457
C++ How can i remove the last comma?
#include <iostream> using namespace std; int main() { string x; cin >> x; char ch; /* how can i remove the last comma? */ int l = x.length(); for (int i = 0; i < l; i++) { ch = x.at(i); cout << ch << ",";} return 0; } I expect: input: 1234 output: 1,2,3,4 but now: input: 1234 output: 1,2,3,4,
Do this(Basically you print the comma separately between that you check if it is the last iteration and works for any numbers): #include <iostream> using namespace std; int main() { string x; cin >> x; char ch; /* how can i remove the last comma? */ int l = x.length(); for (int i = 0; i < l; i++) { ch = x.at(i); cout << ch ; if (i==l-1) {break;} cout << ",";} return 0; }
73,996,053
73,996,070
C++ linking error: duplicate symbol for different source file
If two variables as same type and name in different source files, the linker command failed with duplicate symbol error, although two source files are not related. This is my project structure. CMakeLists.txt cmake_minimum_required(VERSION 3.0.0) project(duplicate-symbol-test VERSION 0.1.0) add_executable(duplicate-symbol-test main.cpp a.hpp a.cpp b.hpp b.cpp) target_compile_features(duplicate-symbol-test PUBLIC cxx_std_17) a.hpp #pragma once struct A{ int getRandomNumber() const; }; a.cpp #include "a.hpp" #include <random> std::random_device rd; std::mt19937 gen { rd() }; std::uniform_int_distribution<int> dis { 0, 100 }; int A::getRandomNumber() const{ return dis(gen); } b.hpp #pragma once struct B{ int getRandomNumber() const; }; b.cpp #include "b.hpp" #include <random> std::random_device rd; std::mt19937 gen { rd() }; std::uniform_int_distribution<int> dis { 0, 100 }; int B::getRandomNumber() const{ return dis(gen); } main.cpp #include <iostream> #include "a.hpp" #include "b.hpp" int main(int, char**) { A a; std::cout << a.getRandomNumber() << std::endl; B b; std::cout << b.getRandomNumber() << std::endl; return 0; } When build, the cmake build system shows, [main] Building folder: duplicate-symbol-test [build] Starting build [proc] Executing command: /opt/homebrew/bin/cmake --build /Users/admin/Desktop/duplicate-symbol-test/build --config Debug --target all -- [build] [1/2 50% :: 0.661] Building CXX object CMakeFiles/duplicate-symbol-test.dir/b.cpp.o [build] [2/2 100% :: 0.742] Linking CXX executable duplicate-symbol-test [build] FAILED: duplicate-symbol-test [build] : && /opt/homebrew/opt/llvm/bin/clang++ -g -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/duplicate-symbol-test.dir/main.cpp.o CMakeFiles/duplicate-symbol-test.dir/a.cpp.o CMakeFiles/duplicate-symbol-test.dir/b.cpp.o -o duplicate-symbol-test && : [build] duplicate symbol '_dis' in: [build] CMakeFiles/duplicate-symbol-test.dir/a.cpp.o [build] CMakeFiles/duplicate-symbol-test.dir/b.cpp.o [build] duplicate symbol '_gen' in: [build] CMakeFiles/duplicate-symbol-test.dir/a.cpp.o [build] CMakeFiles/duplicate-symbol-test.dir/b.cpp.o [build] duplicate symbol '_rd' in: [build] CMakeFiles/duplicate-symbol-test.dir/a.cpp.o [build] CMakeFiles/duplicate-symbol-test.dir/b.cpp.o [build] ld: 3 duplicate symbols for architecture arm64 [build] clang-14: error: linker command failed with exit code 1 (use -v to see invocation) [build] ninja: build stopped: subcommand failed. [proc] The command: /opt/homebrew/bin/cmake --build /Users/admin/Desktop/duplicate-symbol-test/build --config Debug --target all -- exited with code: 1 and signal: null [build] Build finished with exit code 1 How should I solve it?
How should I solve it? By making all symbols local to their translation unit. Global non-const variables have by default external linkage, thus two variables with the same qualified name clash during linking. This can be fixed by either: declaring them static - forcing internal linkage. putting them into an anonymous namespace - ensure unique qualified name. I recommend the second option as it works for types too: namespace{ std::random_device rd; std::mt19937 gen { rd() }; std::uniform_int_distribution<int> dis { 0, 100 }; } int B::getRandomNumber() const{ return dis(gen); } Unrelated to the issue but there is usually no reason to keep rd around, std::mt19937 gen { std::random_device{}() }; works too. Just be warned that random_device can be deterministic and produce the same sequence each time, check with your implementation.
73,996,114
73,996,275
Get all input of int from cin separated with space in c++
N = Input How much attempt (First Line). s = Input How much value can be added (Second, fourth and sixth lines). P = Input of numbers separated with space. Example : 3 ( Input N ) 2 ( s 1 ) 2 3 3 ( s 2 ) 1 2 3 1 ( s 3 ) 12 Example : Read #1: 5 (Output s1 = 2 + 3) Read #2: 6 (Output s2 = 1+2+3) Read #3: 12 (Output s3 = 12) I've been searching and trying for very long but couldn't figure out such basic as how to cin based on given numbers, with spaces and add all values into a variable. For example: #include <iostream> using namespace std; int main() { int l, o[l], r, p[r], i; cin >> l; for(i = 0; i < l; i++) { cin>>o[l]; r = o[l]; // for every o[0] to o[l] } while (cin>>o[l]) { for (i = 0; i < l; i++){ cin>>p[o]; // for every o[0] to o[l] // i.e o[l] = 1 then 2 values can be added (because it starts from zero) // input 1 2 // o[1] = {1, 2} int example += o[1]; cout<< "Read#2: " << example; } } } And it doesn't work. Then i found getline(), ignoring the s and just input anything that will finally be added to a number, turned out it is only usable for char string. I tried scanf, but I'm not sure how it works. So im wondering if it's all about s(values) × 1(column) matrix from a looping but sill not sure how to make it. Any easy solutions to this without additional libraries or something like that? Thanks in advance.
#include <iostream> using namespace std; int main() { int t; //number of attempts cin >> t; while(t--) { // for t attempts int n, s = 0; //number of values and initial sum cin >> n; while (n--) { //for n values int k; //value to be added cin >> k; s += k; //add k to sum } cout << s << "\n"; //print the sum and a newline } return 0; } If you want to add more details, (i.e. print Read#n on the nth attempt), you can always use for (int i = 1; i <= n; i++) to replace while(t--) and at the end of the attempt just print cout << "Read#" << i << ": " << s << "\n";
73,996,577
73,996,740
How can I get the object of specific type from vector that contains multiple type of objects
I've got a question, if we have a class A and other classes from class B : class A to class Z : class A are inherited from class A, and we have a vectorstd::vector<A> that contains objects of all types from class A to class Z, how can we get an object of specific type from that vector, for example we want to get object which is type of E how to get that object. class A {}; class B : A {}; class C : A {}; ... class Z : A {}; std::vector<A> vec; // lets say it contains objects of type A to Z template<typename T> T GetObject() { for (int i = 0; i < vec.size(); i++) { //if type of vec[i] == type of T return vec[i] } } E obj = GetObject<E>(); I've used something like this if (typeid(vec[i]) == typeid(T)) { return vec[i]; } but it doesn't work.
You cannot store subtypes of A in a std::vector<A>. Any objects of a subtype you put in there are sliced and every element in the vector is simply an object of type A. You could use a std::vector<std::variant<A, ..., Z>> instead. You should probably think about a different design though: #define TYPES(x) \ x(B) \ x(C) \ x(D) \ x(E) \ x(F) \ x(G) \ x(H) \ x(I) \ x(J) \ x(K) \ x(L) \ x(M) \ x(N) \ x(O) \ x(P) \ x(Q) \ x(R) \ x(S) \ x(T) \ x(U) \ x(V) \ x(W) \ x(X) \ x(Y) \ x(Z) #define DECLARE(x) struct x { void operator()() {std::cout << #x << '\n'; } }; #define EMPLACE(x) data.emplace_back(x{}); #define TYPE_PARAMS(x) ,x DECLARE(A); TYPES(DECLARE); using Variant = std::variant<A TYPES(TYPE_PARAMS)>; int main() { std::vector<Variant> data; EMPLACE(A); TYPES(EMPLACE); using SearchedType = E; auto pos = std::find_if(data.begin(), data.end(), [](Variant const& v) { return std::holds_alternative<SearchedType>(v); }); if (pos != data.end()) { std::visit([](auto& v) { v(); }, *pos); } } An alternative would be to declare a template variable: template<class T> T object{}; int main() { using SearchedType = E; object<SearchedType>(); } Another option would be to add a virtual destructor to A and use a std::vector<std::unique_ptr<A>> combined with dynamic_cast...
73,997,093
74,067,666
What is the correct exception to throw when a method is called at an inappropriate time?
I have a class which exposes a method which should be called a certain number of times by the user of the class. The amount of times the method is to be called is agreed upon via an int parameter during object construction. Thus, while calling it too few times could be due to the caller deciding to cancel the operation for whatever reason, calling it too often clearly qualifies as a programming error, i.e. std::logic_error. I was wondering whether there is a more concrete exception to be thrown in this situation, such as std::domain_error. This page on cppreference.com says std::domain_error is thrown in: [...] situations where the inputs are outside of the domain on which an operation is defined , which appears to match the use-case. However, I am asking because I am unsure whether a method call qualifies as "input" in this context. What exception should be thrown in this situation?
What is the correct exception to throw when a method is called at an inappropriate time? std::logic_error, preferably a struct/class deriving therefrom. struct PixelOverflowException : public std::logic_error { PixelOverflowException() : std::logic_error("Cannot accept further pixels: resampled image is already complete.") {} }; Deriving can be useful even for runtime exceptions (programming errors) because: it will be easier to write tests checking the code's behavior in misuse scenarios. if the caller wants to check for a specific exception for whatever reason, they'll be able to do so as well. doing so has no cost. See https://stackoverflow.com/a/44901257/593146 std::domain_error std::domain_error is a specific kind of std::logic_error that applies to situations where an operation is possible in theory, but not in practice. For example, a file format for photos might encode width and height as a 32-bit unsigned integer, meaning up to 4294967296 (if the encoded value is -1-biased) times 4294967296 = ‭18446744073709551616‬ pixels. A naive implementation of a decoder for such image format might be constrained to certain widths and heights, for example due to performing calculations involving width and height that will overflow long before the maximum width and height values occur. uint32_t numPixels = width * height; // will overflow for width and height = 65536. In such cases, the decoder should throw an exception deriving from std::domain_error instead of blindly engaging in undefined behavior: the file can theoretically be decoded, but the specific implementation is unable to do so. std::domain_error is different from std::logic_error in that an implementation which does not need to throw it is without a doubt conceivable, if only in theory if need be. To emphasize, both exceptions hint at an error on the caller's side, and std::domain_error does not necessarily indicate that an implementation is of poor quality or incomplete: the set of accepted inputs might be constrained on purpose for reasons of performance, usability or scope.
73,997,779
73,998,138
Generate a sequence of null values follwed by one at compiletime
I have a problem similar to Generating a sequence of zeros at compile time However, in my case I have no pack to expand. The situation is like this: template<size_t N> void foo() { bar(T{}, ..., static_cast<T>(1)); } There are N - 1 T{}:s followed by a one. It may happen that T is not usable as a non-type template parameter. There are two differences compared to the linked post In the linked post, there is already a parameter pack to rely on In the linked post, it is assumed that all arguments are integers I may use a solution that require C++20
you generate the sequence yourself #include <utility> template<std::size_t N> void foo(){ [&]<std::size_t...I>(std::index_sequence<I...>){ bar((I,T{}) ... , static_cast<T>(1)); }(std::make_index_sequence<N-1>()); }
73,997,839
73,998,111
Why can't C++20 compliant compilers detect memory leaks?
In C++20 we can allocate memory in constexpr contexts as long as the memory is freed within the context — i.e this is valid: constexpr int* g(){ int* p = new int(100); return p; } constexpr int f(){ int* ret = g(); int i = *ret; delete ret; return i; } static_assert(f() == 100); Whereas this won't compile: constexpr int* g(){ int* p = new int(100); return p; } constexpr int f(){ int* ret = g(); int i = *ret; return i; } static_assert(f() == 100); with the error: error: '(f() == 100)' is not a constant expression because allocated storage has not been deallocated Now this obviously means that the compiler is able to keep track of allocations and deallocations — at least in a constexpr context. I can see how the compiler, being in control of allocations at compile-time, is better able to keep track of memory leaks, and of course, this says nothing of out-of-bounds accesses, use after frees, double frees etc, but surely the functionality that allows compile-time constexpr leak detection could be extended to some degree of general compile-time leak detection too? Hence my question: Is there some fundamental limitation that prevents the compiler from performing leak-detection in non-constexpr contexts at compile time, or was the feature simply deemed unnecessary?
surely the functionality that allows compile-time constexpr leak detection could be extended to some degree of general compile-time leak detection too? No, it can't. Compile-time code execution means that the compiler is executing the code. That is the "functionality that allows compile-time constexpr leak detection": the fact that the compiler is doing it. Non-compile-time execution is governed by the machine code generated by the compiler. By the time the code is executed, the compiler is long-since out of the picture. In order to have leak detection, the compiler would have to generate a bunch of extra code into this machine code to do the checking. Which would be slow. Furthermore, compile-time code is necessarily limited. Most of the tricks that make this hard are expressly forbidden. Chucking reinterpret_cast and its equivalents alone removes an entire layer of complexity from the problem. You can't throw exceptions either, so that's another source of leak-detection difficulties you don't have to consider. Most of the things that make leak detection hard simply cannot be done in constexpr code.
73,998,574
73,999,058
Call boosts dijkstra shortest paths algorithm using a external weight map
I want to create a graph and call Dijkstra multiple times using different weight maps. I read that I can use an associative_property_map to map edges to weights but I don't know how to call Dijkstra using this custom map as a weight map. #include <iostream> #include <vector> #include <map> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/kruskal_min_spanning_tree.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> graph; typedef boost::graph_traits<graph>::edge_descriptor edge_desc; typedef boost::graph_traits<graph>::vertex_descriptor vertex_desc; typedef std::map<edge_desc, boost::edge_weight_t> edge_weight_map; typedef boost::associative_property_map<edge_weight_map> weight_map; void dijkstra_path(const graph &G, const weight_map &w_map, int s, int t, std::vector<vertex_desc> &pred_map) { int n = boost::num_vertices(G); std::vector<int> dist_map(n); boost::dijkstra_shortest_paths(G, s, boost::distance_map( boost::make_iterator_property_map(dist_map.begin(), boost::get(boost::vertex_index, G))) .predecessor_map(boost::make_iterator_property_map(pred_map.begin(), boost::get(boost::vertex_index, G))), w_map); } This is how I imagined it to work, can anybody tell me how to actually do this?
You are mixing positional parameters with named parameters. The overload with named parameters doesn't take a weightmap positional: https://www.boost.org/doc/libs/1_80_0/libs/graph/doc/dijkstra_shortest_paths.html So, add the weight map to the name parameters: using graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>; using edge_desc = boost::graph_traits<graph>::edge_descriptor; using vertex_desc = boost::graph_traits<graph>::vertex_descriptor; using edge_weight_map = std::map<edge_desc, boost::edge_weight_t>; using weight_map = boost::associative_property_map<edge_weight_map>; void dijkstra_path(const graph& G, weight_map w_map, int s, int /*t*/, std::vector<vertex_desc>& pred_map) // { int n = boost::num_vertices(G); std::vector<int> dist_map(n); auto id = get(boost::vertex_index, G); auto dm = make_iterator_property_map(dist_map.begin(), id); auto pm = make_iterator_property_map(pred_map.begin(), id); boost::dijkstra_shortest_paths( // G, s, // boost::distance_map(dm) // .predecessor_map(pm) // .weight_map(w_map)); } As a general tip, pass property maps by value. They're lightweight "reference" types designed to be very cheap to copy.
73,999,066
73,999,503
Converting lambda (cpp) to function pointer (for c)
I am trying to implement a parallel runtime using argobots api. In the main.cpp I am using a lambda function which is argument to the "kernel" function in lib.cpp. I need to convert the lambda received in lib.hpp to a function pointer and call "lib_kernel" in lib.c. I have read many answers and came to know that converting lambdas (capture by reference) to function pointer is not possible. Is there any alternative?. I also don't have any idea how deal with the template parameter T in the "kernel" function. Please help. // main.cpp #include "lib.hpp" int main(int argc, char **argv) { int result; lib::kernel([&]() { result = fib(10); }); cout << "Fib(10) = " << result << "\n"; // fib is parallel implementation of fibonacci // similar to passing function pointers to threads } // lib.hpp namespace lib { void kernel(T &&lambda) { // T is template argument // Need to convert lambda to function pointer // ie. lib_kernel(fptr, args) // Here fptr and args are received from lambda // ie. fptr will be fib function // args is value 10. } } // lib.c typedef void (*fork_t)(void* args); void lib_kernel(fork_t fptr, void* args) { fptr(args); }
You can convert a lambda to a function pointer with +, i.e.: typedef void (*func)(void* args); void kernel(func fn, void* args){ fn(args); } void CallKernelWithLambda() { func f = +[](void*) { }; kernel(f, nullptr); } However, lambdas that capture cannot be converted to a function pointer -- the following fails to compile: typedef void (*func)(void* args); void kernel(func fn, void* args){ fn(args); } void CallKernelWithLambda() { int value = 0; func f = +[&](void*) { ++value; }; kernel(f, nullptr); } You need to put the value that you want to capture in static storage or global scope, e.g.: typedef void (*func)(void* args); void kernel(func fn, void* args){ fn(args); } int value = 0; void CallKernelWithLambda() { func f = +[](void*) { ++value; }; kernel(f, nullptr); } Putting the call to kernel inside of a templated function doesn't make any difference, i.e.: typedef void (*func)(void* args); void kernel(func fn, void* args){ fn(args); } template <typename T> void CallKernelWithTemplateArgumentLambda(T&& lambda) { kernel(+lambda, nullptr); } int value = 0; void CallKernelWithLambda() { CallKernelWithTemplateArgumentLambda([](void*) { ++value; }); } behaves the same way as the previous snippet.
73,999,161
73,999,605
Score average (Cambodian Idol Practice)
I'm having a bit of trouble with a coding project the question is as follows. A particular talent competition has five judges, each of whom awards a score between 0 and 10 to each performer. Fractional scores, such as 8.3, are allowed. A performer’s final score is determined by dropping the highest and lowest score received, then averaging the three remaining scores. Write the program that uses this method to calculate a contestant’s score. I have to use the following, void getJudgeData(), void calcScore(), double findLowest(), double findHighest() My code is as follows #include <iostream> using namespace std; double inputValidation(double); void getJudgeData(double&); void calcScore(double, double, double, double, double); double ifLowest(double, double, double, double, double); double findLowest(double, double, double, double, double); double ifHighest(double, double, double, double, double); double findHighest(double, double, double, double, double); int main() { double score1, score2, score3, score4, score5; getJudgeData(score1); getJudgeData(score2); getJudgeData(score3); getJudgeData(score4); getJudgeData(score5); calcScore(score1, score2, score3, score4, score5); return 0; } double inputValidation(double num) { while (!(cin >> num) || (num < 0 || num > 10)) { cout << "Incorrect Score parameters" << endl; exit(0); return 0; } return num; } void getJudgeData(double& num) { cout << "Enter Score: "; num = inputValidation(num); } void calcScore(double num1, double num2, double num3, double num4, double num5) { double average, lowest = findLowest(num1, num2, num3, num4, num5), highest = findHighest(num1, num2, num3, num4, num5); if ((num1 == lowest)||(num5 == highest)) average = (num2 + num3 + num4) / 3; else if ((num2 == lowest)||(num4 == highest)) average = (num1 + num3 + num5) / 3; else if ((num3 == lowest)||(num3 == highest)) average = (num1 + num2 + num4 + num5) / 3; else if ((num4 == lowest)||(num2 == highest)) average = (num1 + num3 + num5) / 3; else if ((num5 == lowest)||(num1 == highest)) average = (num2 + num3 + num4) / 3; cout << "The average is: "; cout << average << endl; } double ifLowest(double num1, double num2, double num3, double num4, double num5) { double lowest{}; if (num1 <= num2) { if (num1 <= num3) { if (num1 <= num4) { if (num1 <= num5) { lowest = num1; } } } } return lowest; } double findLowest(double num1, double num2, double num3, double num4, double num5) { double smallest; smallest = ifLowest(num1, num2, num3, num4, num5); smallest = ifLowest(num2, num3, num4, num5, num1); smallest = ifLowest(num3, num4, num5, num1, num2); smallest = ifLowest(num4, num5, num1, num2, num3); smallest = ifLowest(num5, num1, num2, num3, num4); return smallest; } double ifHighest(double num1, double num2, double num3, double num4, double num5) { double highest{}; if (num5 >= num2) { if (num5 >= num3) { if (num5 >= num4) { if (num5 >= num1) { highest = num5; } } } } return highest; } double findHighest(double num1, double num2, double num3, double num4, double num5) { double largest; largest = ifHighest(num1, num2, num3, num4, num5); largest = ifHighest(num2, num3, num4, num5, num1); largest = ifHighest(num3, num4, num5, num1, num2); largest = ifHighest(num4, num5, num1, num2, num3); largest = ifHighest(num5, num1, num2, num3, num4); return largest; } In the void calcScore, average gives me an error but only when i attempt to drop the highest score then average
For solving this problem, you don't need to define isLowest() and isHighest() function. You can directly find the highest and lowest number by just comparing all numbers and also in your calcScore() function, you have not covered all cases. For example if num1 is lowest and num2 is highest. Here is the correct code - #include <iostream> using namespace std; double inputValidation(double); void getJudgeData(double &); void calcScore(double, double, double, double, double); double findLowest(double, double, double, double, double); double findHighest(double, double, double, double, double); int main() { double score1, score2, score3, score4, score5; getJudgeData(score1); getJudgeData(score2); getJudgeData(score3); getJudgeData(score4); getJudgeData(score5); calcScore(score1, score2, score3, score4, score5); return 0; } double inputValidation(double num) { while (!(cin >> num) || (num < 0 || num > 10)) { cout << "Incorrect Score parameters" << endl; exit(0); return 0; } return num; } void getJudgeData(double &num) { cout << "Enter Score: "; num = inputValidation(num); } void calcScore(double num1, double num2, double num3, double num4, double num5) { double average, lowest = findLowest(num1, num2, num3, num4, num5), highest = findHighest(num1, num2, num3, num4, num5); average = (num1 + num2 + num3 + num4 + num5 - lowest - highest) / 3; cout << "The average is: "; cout << average << endl; } double findLowest(double num1, double num2, double num3, double num4, double num5) { double temp[] = {num1, num2, num3, num4, num5}; double smallest = num1; for (int i = 0; i < 5; i++) { if (temp[i] < smallest) { smallest = temp[i]; } } return smallest; } double findHighest(double num1, double num2, double num3, double num4, double num5) { double temp[] = {num1, num2, num3, num4, num5}; double largest = num1; for (int i = 0; i < 5; i++) { if (temp[i] > largest) { largest = temp[i]; } } return largest; }
73,999,191
73,999,201
Variadic arguments template method specialization
I'm in a process of implementing loadAsset method in my asset manager implementation. I've tried using variadic arguments template method with following signature: class AssetManager { public: template <typename AssetType, typename... Args> void loadAsset(std::string_view name, const Args &...args); ... }; And following specialization in .cpp file: template <> void AssetManager::loadAsset<Texture, std::string>(std::string_view name, const std::string &path) {...} template void AssetManager::loadAsset<Texture, std::string>(std::string_view, const std::string &path); //explicit instantiation However when trying to invoke loadAsset method like so: m_assetManager->loadAsset<NOX::Texture>("texture", "assets/textures/texture.jpg"); I get the following error: error LNK2019: unresolved external symbol "public: void __cdecl NOX::AssetManager::loadAsset<class NOX::Texture,char [28]>(class std::basic_string_view<char,struct std::char_traits<char> >,char const (&)[28])" (??$loadAsset@VTexture@NOX@@$$BY0BM@D@AssetManager@NOX@@QEAAXV?$basic_string_view@DU?$char_traits@D@std@@@std@@AEAY0BM@$$CBD@Z) referenced in function "public: __cdecl ExampleApplication::ExampleApplication(struct NOX::ApplicationSpecification const &)" (??0ExampleApplication@@QEAA@AEBUApplicationSpecification@NOX@@@Z) How can I prevent that from happening? I'm using C++17 and can't use C++20.
If you specialize a template in a cpp file, that'll be available in the given file, but not externally (unless, of course, if you instantiate it manually). Best way to do it is to move all template definitions to header.
73,999,513
73,999,568
How to overload variadic template function based on size of parameter pack in C++
I'm sorry if this question is basic. Let's say I have a function template that took in a parameter pack of arguments. How would I overload it so that there might be a specialization for 2 arguments getting passed in, 3 arguments passed in, etc.
For small parameter packs, I'd use non-variadic overloads: template <typename A, typename B> void foo(A a, B b); template <typename A, typename B, typename C> void foo(A a, B b, C c); If you prefer to have a pack, you can constrain the size with requires or std::enable_if_t: template <typename ...P> requires(sizeof...(P) == 2) void foo(P ...p); template <typename ...P> requires(sizeof...(P) == 3) void foo(P ...p); Another option is to have a single variadic function, and select the behavior with if constexpr (sizeof...(P) == N).
74,000,137
74,000,510
Practical difference between implicit and defaulted constructor in C++
As far as I know, in C++ default constructors are declared (and defined if needed) implicitly if there is no user-defined default constructors. However, a user can declare a default constructor explicitly with the default keyword. In this post the answers are mainly about the difference between the implicit and default terms, but I didn't see an explanation about whether there is some difference between declaring a constructor as default and not declaring it at all. As an example: class Entity_default { int x; public: Entity_default() = default; } class Entity_implicit { int x; } In the example above, I declare a constructor for Entity_default as default and let the compiler declare a default constructor implicitly for Entity_implicit. I assume I do call these constructors later on. Is there any difference between these constructors in practice?
To the best of my knowledge, there is no functional or theoretical difference, both are still "trivial." Uses of an explicit default constructors: To ensure it exists when it would not otherwise be created, i.e. if a different constructor exists You can default it in a different compilation unit: Header file: struct Foo { std::string bar; Foo() noexcept; ~Foo(); }; Source file: Foo::Foo() noexcept = default; Foo::~Foo() = default; Useful if you don't want an inline constructor to save code size or ensure ABI compatibility. Note that at this point, it is no longer a trivial object.
74,000,262
74,000,462
Move semantics and overload
I think my understanding of rvalue references and move semantics has some holes in it. As far as I've rvalue references understood now, I could implement a function f in two ways such that it profits from move semantics. The first version: implement both void f(const T& t); void f(T&& t); This would result in quite some redundancy, as both versions are likely to have (almost) identical implementation. second version: implement only void f(T t); Calling f would result in calling either the copy or the move constructor of T. Question. How do the two versions compare to each other? My suspicion: In the second version, (ownership of) dynamically allocated data may be moved by the move constructor, while non-dynamically allocated data in t and its members needs to be copied. In the first version, neither version allocates any additional memory (except the pointer behind the reference). If this is correct, can I avoid writing the implementation of f basically twice without the drawback of the second version?
If you need to take a T&& parameter, it usually means you want to move the object somewhere and keep it. This kind of function is typically paired up with a const T& overload so it can accept both rvalues and lvalues. In this situation, the second version (only one overload with T as a parameter) is always less efficient, but most likely not by much. With the first version, if you pass an lvalue, the function takes a reference and then makes a copy to store it somewhere. That's one copy construction or assignment. If you pass an rvalue, the function again takes a reference and then moves the object to store it. That's one move construction or assignment. With the second version, if you pass an lvalue, it gets copied into the parameter, and then the function can move that. If you pass an rvalue, if gets moved (assuming the type has a move constructor) into the parameter, and then the function can also move that. In both cases, that's one more move construction or assignment than with the first version. Also note that copy elision can happen in some cases. The benefit of the second version is that you don't need multiple overloads. With the first version, you need 2^n overloads for n parameters that you need copied or moved. In the simple case of just one parameter, I sometimes do something like this to avoid repeating code: void f(const T& t) { f_impl(t); } void f(T&& t) { f_impl(std::move(t)); } // this function is private or just inaccessible to the user template<typename U> void f_impl(U&& t) { // use std::forward<U>(t) }
74,000,296
74,000,321
Cannot add constant to vector
I tried to add path to my vector but it's defined by constant. What do I need to do to fit the data from entry.path() to my vector. #include <iostream> #include <string> #include <vector> #include <filesystem> namespace fs = std::filesystem; int main () { std::vector<std::string> sourceContent; std::string replica = "replica"; std::string source = "source"; for (auto & entry : fs::recursive_directory_iterator(source)) { sourceContent.push_back(entry.path()); std::cout << entry.path() << std::endl; } }
Yout need you to use the string() member function: sourceContent.push_back(entry.path().string()); Another option would be to store actual paths in the vector instead: std::vector<std::filesystem::path> sourceContent;
74,000,607
74,000,709
Can I compile and dlopen a dynamic library in Compiler Explorer?
Just for the purpose of learning, I've made a small example of a main program tentatively loeading a shared library via dlopen (and then a symbol from it via dlsym) and using a default one if the former is not avalable. On my machine, to make the non-default library available to the main program, I need to compile the former via g++ -fPIC -shared MyLib.cpp -o libMyLib.so, whereas both main.cpp and DefaultLib.cpp are compiled simply by g++ -c main.cpp -o main.o and g++ -c DefaultLib.cpp -o DefaultLib.o. How can I provide the options -fPIC -shared to the compilation of MyLib.cpp in Compiler Explorer? The current attempt is here, where, I believe, MyLib.cpp is compiled just like the other two cpp files, i.e. without providing options -fPIC and -shared, and maybe most importantly without generating a file with the name libMyLib.so, thus resulting dlopen failing to load; indeed, the foo from the other, default library DefaultLib is called.
Can I compile and dlopen a dynamic library in Compiler Explorer? Yes, it's certainly possible. In CMakeLists.txt: add_library(MyLib SHARED MyLib.cpp) ...and remove MyLib.cpp from add_executable. Then in main.cpp: void * lib = dlopen("build/libMyLib.so", RTLD_LAZY); Because the library is placed in the build subdirectory. Demo
74,000,681
74,008,810
Deserialize Json object from mqtt payload using ArduinoJson library
I'm trying to deserialize a Json object using the ArduinoJson 6 library. The object is passing through a mqtt callback using the PubSubClient library. The payload contains the following example: "{\"action\":\"message\",\"amount\":503}" but I am unable to retrieve the amount value. Only zeros are returned when using the following: void messageReceived(char *topic, byte *payload, unsigned int length) { DynamicJsonDocument doc(1024); deserializeJson(doc, payload, length); const int results = doc["amount"]; Serial.print(results); } This works and returns 503 as needed: DynamicJsonDocument doc(1024); char json[] = "{\"action\":\"message\",\"amount\":503}"; deserializeJson(doc, json); const int results = doc["amount"]; Serial.print(results); I see the results of the payload when I use the following method: void messageReceived(char *topic, byte *payload, unsigned int length) { for (unsigned int i = 0; i < length; i++) { Serial.print((char)payload[i]); } } What is preventing me from being able to parse out the amount value from the first method?
Update & resolution: The first method in my original post worked fine once I fixed the data that was being sent from the Lambda function to the IOT side. (Something I didn't include in my original question and didn't think it was relevant. Turns out it was.) Here is a snippet from the Lambda function that is receiving the data. The issue was that the data was being sent as a string and not parsed. Once I stringified the response and then parsed the output, it worked. Thank you @hcheung for the assistance and helpful info. Your suggestion works as well but only after I fixed the Lambda function. async function sendToIOT(response) { const data = JSON.stringify(response); const iotResponseParams = { topic: 'mythingname/subscribe', payload: JSON.parse(data) }; return iotdata.publish(iotResponseParams).promise() }
74,000,804
74,000,824
STL function to get all dimensions of a vector in c++
I wish to know if there is any STL function in c++, to get the dimensions of a vector. For example, vec = [[1, 2, 3], [4, 5, 6]] The dimensions are (2, 3) I am aware of size() function. But the function does not return dimensions. In the above example, vec.size() would have returned 2. To get second dimension, I would have to use vec[0].size(), which would be 3
In C++, a(n std::)vector is, by definition, 1D-vector of size() elements, which can be changed in runtime. You can define a vector of vectors (e.g., std::vector<std::vector<int>>), but that doesn't have a constraint that the 'inner' dimensions are the same. E.g., {{1, 2, 3}, {1, 2}} is valid. Therefore, inner dimensions are ambiguous. What you can do, if you maintain it to be the same and if you're sure that you've got elements, is to query v[0].size() as well, and so on.
74,000,936
74,000,987
C++ std::string bug when adding size as string in map
I found Some thing on visual studio v143 tools std:c++ lastest is it bug or something std::unordered_map<std::string, std::string> map; std::string test_str = "1234567890123456789012345678901234567890123456789012345";//55 LEN String map["test_len"] = test_str.length(); std::cout << map["test_len"]; // 7 on 55 len string EDIT:it's same in all numbers Chrome will work even Content-Lenght is not valid
In statement map["test_len"] = test_str.length(); std::unordered_map::operator[] default-constructs a new std::string and returns a reference to it which is then assigned to a value of type size_type. This assignment invokes std::string::operator=(char) which interprets integer value 55 as ascii character 7. This is a long standing usability bug in std::string interface. Examples of the bug: std::string s = test_str.length(); // Compiler error. std::string s2; s2 = test_str.length(); // Compiles successfully, std::string interface bug. s2 = true; // Compiles successfully, std::string interface bug. s2 = std::ios_base::failbit; // Compiles successfully, std::string and std::ios_base interface bugs. std::string s3{std::ios_base::failbit, 55, true, 'a'}; // Compiles successfully, std::string interface bug. std::string s3 = {std::ios_base::failbit, 55, true, 'a'}; // Compiles successfully, std::string interface bug. C++17 type-safe way to insert or assign a value into an associative container is: map.insert_or_assign("test_len", test_str.length()); // Compiler error. map.insert_or_assign("test_len", {std::ios_base::failbit, 55, true, 'a'}); // Compiler error. map.insert_or_assign("test_len", std::to_string(test_str.length())); // Success. std::unordered_map::insert_or_assign always uses direct-initialization of mapped value to avoid precisely this kind of silent unanticipated type conversion bugs when value type assignment operator has different semantics from its constructor, which breaks the engineering principle of least surprise.
74,001,426
74,002,222
Cannot have separate declaration and implementation of class with custom variadic non-template parameters
Is this a bug in Clang (the default version used by Xcode 14)? The following code does not compile: struct TestValue { }; template<TestValue... Values> struct TestCompiler { TestCompiler(); }; template<TestValue... Values> TestCompiler<Values...>::TestCompiler() { } The error message is: nested name specifier 'TestCompiler<Values...>::' for declaration does not refer into a class, class template or class template partial specialization To reproduce this, it's necessary to have the template parameters of TestCompiler be non-template types, variadic, and custom (not built in) types. Defining the class inline compiles, it's only trying to declare and implement the class separately that fails.
This is a clang bug since the program is well-formed as this is the correct way of providing an out of class definition for a nontemplate ctor of a class template. Here is the clang bug report: Clang rejects valid out of class definition of a nontemplate constructor of a class template
74,001,933
74,002,020
G++ responds differently to const int** and const int* as function parameters
I was writing a C++ function that takes int** as input and the function itself does not modify the data (i.e. matrix elements). So I decided to make the argument a const int** type (Is that an acceptable practice?). A sample code is like this: void func1(const int* k) { std::cout << *k << '\n'; } void func2(const int** k) { std::cout << **k << '\n'; } int main() { int m = 0; int* p1 = &m; func1(p1); int** p2 = &p1; func2((const int**)p2); // compilation error unless explicit type conversion // func2(p2); /* [*] compilation error */ (**p2) += 1; func1(p1); func2((const int**)p2); return 0; } My question is, when calling func2, I have to explicitly convert the double-pointer p2 to const int**, otherwise it gives the following error: error: invalid conversion from ‘int**’ to ‘const int**’ [-fpermissive] Whereas func1 has no such issue. I tested this with both g++ (10.2.0) on Cygwin and Intel's icpc. Could someone explain why the compiler behaves this way and what is a good practice in this situation?
With multiple levels of pointers, a type is only more const-qualified if every level of pointer from the right has const added. This is for const-correctness reasons so that when you assign to the pointer, you can't accidentally assign a more const-qualified pointer at the "lower" levels of pointers when you have multiple pointers. For example: int *** * * * i; int ***const*const*const* j = i; // ^ All levels after this have to be const-qualified This includes the left-most type, const int. So, if your data is not modified, you should have int const* const* k. This is the case in C++ (as a qualification conversion), but this is still allowed implicitly in C because all pointers can be implicitly converted.
74,002,217
74,002,470
Is there a way to access variable declared in for loop outside of for loop?
For example, there is a char named 'character' defined in a for loop. Can I possibly use the char outside of the for loop? Code: #include <iostream> int main() { for(int i = 0; i < 5; i++) { char character = 'a'; // Char defined in for loop } std::cout<<character; // Can this be made valid? return 0; }
Yes, you can do this indirectly in C++11 and later, with a lambda: #include <iostream> #include <functional> int main() { std::function<char()> fun; for(int i = 0; i < 5; i++) { char character = 'a'; // Char defined in for loop fun = [=](){ return character; }; } std::cout << fun() << std::endl; return 0; } The outside scope cannot access character, but a lambda which was captured in that scope can be called, and the body of that lambda has character in scope, and can return it for us. In a language with real lambdas, the lambda would access the actual character variable; the original one created in that scope. In C++, the = in [=] tells the lambda to capture the local variables it is referencing by making copies of them. Thus return character is not actually accessing the original character (which no longer exists, since the block terminated), but a copy which the lambda object carries.
74,002,327
74,047,435
Cannot compile with buildroot 2022.08.1
I'm having issues compiling with buildroot 2022.08.1. There seems to be nothing on the internet (that I can find anyway) that can help me so I'm turning to the legends of the internet. Currently on linux mint 20.3, Kernel 5.19-surface Normally I wouldn't ask but I can't really find much of a specific error message here that I can understand. I have compiled with buildroot on this computer before with just the default defconfig for the raspberry pi 3 but obviously having more configuration on that profile has opened it up to issues. The build nearly finishes and then does the following: [ 26%] Building CXX object Source/JavaScriptCore/CMakeFiles/JavaScriptCore.dir/__/__/JavaScriptCore/DerivedSources/unified-sources/UnifiedSource-f0a787a9-7.cpp.o aarch64-buildroot-linux-gnu-g++.br_real: fatal error: Killed signal terminated program cc1plus compilation terminated. make[4]: *** [Source/JavaScriptCore/CMakeFiles/JavaScriptCore.dir/build.make:1175: Source/JavaScriptCore/CMakeFiles/JavaScriptCore.dir/__/__/JavaScriptCore/DerivedSources/unified-sources/UnifiedSource-23a5fd0e-6.cpp.o] Error 1 make[4]: *** Deleting file 'Source/JavaScriptCore/CMakeFiles/JavaScriptCore.dir/__/__/JavaScriptCore/DerivedSources/unified-sources/UnifiedSource-23a5fd0e-6.cpp.o' make[4]: *** Waiting for unfinished jobs.... In file included from assembler/MacroAssembler.h:46, from jit/Reg.h:30, from jit/RegisterAtOffset.h:30, from jit/RegisterAtOffsetList.h:30, from jit/JITCode.h:33, from runtime/ExecutableBase.h:32, from runtime/ScriptExecutable.h:28, from runtime/FunctionExecutable.h:30, from runtime/JSFunctionInlines.h:28, from ./bytecode/AccessCase.h:33, from ./bytecode/AccessCase.cpp:27, from ../../JavaScriptCore/DerivedSources/unified-sources/UnifiedSource-f0a787a9-1.cpp:1: assembler/MacroAssemblerARM64.h: In member function ‘JSC::ARM64Assembler::ExtendType JSC::MacroAssemblerARM64::indexExtendType(JSC::AbstractMacroAssembler<JSC::ARM64Assembler>::BaseIndex)’: assembler/MacroAssemblerARM64.h:1523:5: warning: control reaches end of non-void function [-Wreturn-type] 1523 | } | ^ make[3]: *** [CMakeFiles/Makefile2:769: Source/JavaScriptCore/CMakeFiles/JavaScriptCore.dir/all] Error 2 make[2]: *** [Makefile:156: all] Error 2 make[1]: *** [package/pkg-generic.mk:293: /home/aussietanz/buildroot-2022.08.1/output/build/webkitgtk-2.36.7/.stamp_built] Error 2 make: *** [Makefile:84: _all] Error 2 Thought it may have been something to do with not enough storage allocated for the .img file (originally 300M because it's a very bare bones raspi3 image with only bash, graphics utilities and python), but i've added a bit more(an extra 200M) and it still has the same issue. Help appreciated.
aarch64-buildroot-linux-gnu-g++.br_real: fatal error: Killed signal terminated program cc1plus This is a typical symptom of an OOM (Out-Of-Memory) - the v8 javascript engine takes a lot of memory. Check the kernel logs on your build machine (journalctl -ke or dmesg | less) just after this error happens. If it is indeed an OOM, it is sometimes possible to work around it by reducing parallelism. You can do this by setting BR2_JLEVEL to a lower value in the Buildroot configuration.
74,002,699
74,002,766
On Linux, what's the use of installing clang++ if it uses g++ libs only?
For C++ development on Linux, if I install clang and use it; it actually uses libstdc++(the g++ lib). What's the use of installing the frontend compiler clang on linux then? I should be good with gcc/g++ only on a linux machine as that's a complete toolchain! Note: I'm not an expert in C++.
libstdc++ is a default runtime on your Linux. libc++ is not installed by default. If you link your app to libc++, you have to add it as a runtime dependency. You are right, gcc/g++ is good for Linux, moreover its diagnostic messages are more clear, thus the compiler is better for beginners. By using clang++, you need to know the C++ standard deeper, otherwise it's difficult to get an error reason.
74,002,759
74,002,932
C++ Constexpr Template Structs with String Literals
Currently using C++20, GCC 11.1.0. I'm trying to create types in a namespace with a unique value and name. I came up with this structure specifically to be able to access the variables with the scope resolution operator like so: foo::bar::name. However, I have no idea how to initialize the name variable. I tried adding a second non-type parameter const char* barName, but it wouldn't let me use string literals as template arguments. Code: namespace foo { template<uint32_t id> struct bar { static constexpr uint32_t value {id}; static constexpr std::string_view name {}; }; using a = bar<0>; using b = bar<1>; } Error Code: namespace foo { template<uint32_t id, const char* barName> struct bar { static constexpr uint32_t value {id}; static constexpr std::string_view name {barName}; }; using a = bar<0, "a">; using b = bar<1, "b">; }
Since we can't pass string literals as template arguments, we have to use some other way. In particular, we can have a static const char array variable as shown below: static constexpr char ch1[] = "somestrnig"; static constexpr char ch2[] = "anotherstring"; namespace foo { //--------------------vvvvvvvvvvvvvvvv--->added this 2nd template parameter template<uint32_t id, const char* ptr> struct bar { static constexpr uint32_t value {id}; //--------------------------------------vvvv-->added this static constexpr std::string_view name {ptr}; }; //---------------vvv----->added this using a = bar<0, ch1>; using b = bar<1, ch2>; }
74,003,709
74,003,751
how to get a class to take in another classes parameters?
I want to have my grid class constructor to take in drivers_location parameters , but it keeps giving me these errors. https://imgur.com/a/y4MZqso #include <iostream> #include <string> using namespace std; class drivers_location { public: drivers_location() = default; drivers_location(string name, float xx, float yy){ x = xx; y = yy; name = driver_name; } private: float x{}; float y{}; string driver_name; }; class grid { public: grid() = default; grid(drivers_location(string name, float xx, float yy)); private: }; int main() { drivers_location p; float pointx{ 2.0 }; float pointy{ 3.0 }; grid m[5]; m[0] = { {"abdul" , pointx, pointy }}; } I want the grid to take in parameters of drivers_location without using inheritance if that's possible
The correct syntax for declaring a constructor takes argument of type driver_location is as shown below. Note that you don't have to specify the 2 parameters of driver_location when defining the constructor for grid that has a parameter of type driver_location. class grid { public: grid() = default; //---vvvvvvvvvvvvvvvv---->this is how we specify that this ctor has a parameter of type drivers_location grid(drivers_location){ //add your code here } private: }; I would also recommend using a good c++ book.
74,003,817
74,004,091
C++ Reference being duplicated when generated in loop at runtime
I have recently switched from C# to C++ trying to learn SFML for graphical animation. I am trying to generate multiple CircleShape with random radius at runtime whose reference is saved as an object class, whose reference is then saved in a vector array. However, after generating the shapes and iterating through the array to draw the shapes from the vector array, it seems that all of them are references to the same shape. My Code: #include <SFML/Graphics.hpp> #include <iostream> #include <random> #include <ctime> template <class T> class Entity { T* m_shape; public: Entity(T* shape) { m_shape = shape; } T* getShape() { return m_shape; } }; class ShapesManager { std::vector<Entity<sf::CircleShape*>*>* circleShape; public: ShapesManager() { circleShape = new std::vector<Entity<sf::CircleShape*>*>(); } std::vector<Entity<sf::CircleShape*>*>* getCircleShapes() { return circleShape; } void addCircleShape(Entity<sf::CircleShape*>* EntityToAdd) { circleShape->push_back(EntityToAdd); } }; int main() { const int windowWidth = 800; const int windowHeight = 600; sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML works!"); //window.setVerticalSyncEnabled(true); window.setFramerateLimit(60); ShapesManager m_entityManager; int lowSize = 25; int highSize = 80; for (int i = 0; i < 2; i++) { srand(i + 5732 + (i * 524)); float circleRadius = lowSize + static_cast<float>(rand()) * static_cast<float>(highSize - lowSize) / RAND_MAX; sf::CircleShape* someValue = new sf::CircleShape(circleRadius); (*someValue).setPosition((circleRadius * 2), (circleRadius * 2)); Entity<sf::CircleShape*>* myObj = new Entity<sf::CircleShape*>(&someValue); m_entityManager.addCircleShape(myObj); } while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); for (Entity<sf::CircleShape*>* cE : ((std::vector<Entity<sf::CircleShape*>*>)* m_entityManager.getCircleShapes())) { Entity<sf::CircleShape*> myCircleEntity = *cE; sf::CircleShape* cS = *myCircleEntity.getShape(); window.draw((*cS)); } window.display(); } return 0; } I have gone through my code multiple times to make sure I am not referencing a single shape for all other shapes. *I have come across "Shared Pointers/Unique Pointers" while trying to search for a solution, though I have yet to get the grasp of it, but if that is what I should be using to help overcome my issue, make sure to mention it in comments as I am looking more for knowledge than a direct solution.
I think @AlanBirtles is right. On each iteration new sf::CircleShape(circleRadius); allocates new memory, so the pointer someValue will point to the different memory addresses each time. You can't say the same about the memory address of the someValue itself, in your case it seems that the pointer someValue is created in the same memory address on each iteration, that's why taking a reference to this pointer returns the same value on each iteration. The solutions @AlanBirtles suggested should be enough.
74,003,911
74,012,702
c++ JSON serialize using reflection
Can someone modify given code so my commented code works. Actully I don't understand how reflect macro is working at first place. #include <vector> #include <string> #include <iostream> using namespace std; #define REFLECT(x) template<class R> void reflect(R& r) { r x; } typedef struct _Employee { string emp_id; int salary; REFLECT( ("Emp_id", emp_id) ("Salary", salary) ) } Employee; class Demo { std::ostream& output; bool flag = false; public: Demo(std::ostream& output) : output(output) {} template<class T> auto write(T& myobj) -> decltype(myobj.reflect(*this), void()) { output << "{"; flag = false; myobj.reflect(*this); output << "}\n"; } void write(int val) { output << val; } void write(std::string& val) { output << '"' << val << '"'; } template<class T> Demo& operator()(const char* emp_id, T& myfield) { if (flag) { output << ","; } flag = true; output << "\"" << emp_id << "\":"; write(myfield); return *this; } }; int main() { Demo myObj(std::cout); //Demo myObj(); Employee emp1 = { "2324354", 90000 }; myObj.write(emp1); //std::cout << myObj.write(emp1); } I am not good at latest c++ coding styles and standards. I got this snippet code from internet and want to use for json serializatzion. Regards. SM
@TRT thanks for your explanation. I got following solution. #include <vector> #include <string> #include <iostream> #include <sstream> using namespace std; #define REFLECT(x) template<class R> void reflect(R& r) { r x; } typedef struct _Employee { string emp_id; int salary; REFLECT( ("Emp_id", emp_id) ("Salary", salary) ) } Employee; typedef struct _Demo { bool flag = false; template<class T> auto write(T& myobj) -> decltype(myobj.reflect(*this), string()){ std::stringstream ss; //cout << "{"; output.push_back("{"); flag = false; myobj.reflect(*this); //cout << "}\n"; output.push_back("}\n"); for (auto& s : output) { ss << s; } return ss.str(); } void write(int& n) { //cout << n; output.push_back(to_string(n)); } void write(string& s) { //cout << '"'<<s<<'"'; output.push_back(string("\"") + s + "\":"); } template<class T> struct _Demo& operator()(const char* emp_id, T& myfield) { std::stringstream ss; if (flag) { //cout << ","; output.push_back(","); } flag = true; //cout << "\"" << emp_id << "\":"; output.push_back(string("\"") + emp_id + "\":"); write(myfield); return *this; } private: vector<string> output; } Demo; int main() { Demo demo; Employee emp = { "2324354", 90000 }; cout << demo.write(emp) << endl; cin.get(); return 0; }
74,004,012
74,004,719
Inlined function to return nested array value not performing as expected
I want to inline the function MyClass:at(), but performance isn't as I expect. MyClass.cpp #include <algorithm> #include <chrono> #include <iostream> #include <vector> #include <string> // Making this a lot shorter than in my actual program std::vector<std::vector<int>> arrarr = { { 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}, {24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50}, {32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70}, {67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21}, {24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72}, {21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95}, {78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92}, {16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57}, {86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58}, {19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40}, { 4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66}, {88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69}, { 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36}, {20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16}, {20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54}, { 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48}, }; class MyClass { public: MyClass(std::vector<std::vector<int>> arr) : arr(arr) { rows = arr.size(); cols = arr.at(0).size(); } inline auto at(int row, int col) const { return arr[row][col]; } void arithmetic(int n) const; private: std::vector<std::vector<int>> arr; int rows; int cols; }; MyClass.cpp: void MyClass::arithmetic(int n) const { using std::chrono::high_resolution_clock; using std::chrono::duration_cast; using std::chrono::duration; using std::chrono::milliseconds; auto t1 = high_resolution_clock::now(); int highest_product = 0; for (auto y = 0; y < rows; ++y) { for (auto x = 0; x < cols; ++x) { // Horizontal product if (x + n < cols) { auto product = 1; for (auto i = 0; i < n; ++i) { product *= at(y, x + i); } highest_product = std::max(highest_product, product); } } } auto t2 = high_resolution_clock::now(); duration<double, std::milli> ms_double = t2 - t1; std::cout << ms_double.count() << "ms\n"; return highestProduct; }; Now what I want know is why do I get better performance when I replace product *= at(y, x + i); with product *= arr[y][x+i];? When I test it with the first case, the timing on my large array takes roughly 6.7ms, and the second case takes 5.3ms. I thought when I inlined the function, it should be the same implementation as the second case.
Member function directly defined in the class definition (typically in header files) are implicitly inlined so using inline is useless in this case. inline do not guarantee the function is inlined. It is just an hint for the compiler. The keyword is also an important during the link to avoid the multiple-definition issue. Function that are not make inline can still be inlined if the compiler can see the code of the target function (ie. it is in the same translation unit or link time optimization are applied). For more information about this, please read Why are class member functions inlined? Note that the inlining is typically performed in the optimization step of compilers (eg. -O1//O1). Thus without optimizations, most compilers will not inline the function. Using std::vector<std::vector<int>> is not efficient since it is not a contiguous data structure and it require 2 indirection to access an item. Two sub-vectors next to each other can be stored far away in memory likely causing more cache misses (and/or thrashing due to the alignment). Please consider using one big flatten array and access items using y*cols+x where cols is the size of the sub-vectors (20 here). Alternatively a int[16][20] data type should do the job well if the size if fixed at compile-time. MyClass(std::vector<std::vector<int>> arr) cause the input parameter to be copied (and so all the sub-vectors). Please consider using a const std::vector<std::vector<int>>& type. While at is convenient for checking bounds at runtime, this feature can strongly decrease performance. Consider using the operator [] if you do not need that. You can use assertions combined with flatten arrays so to get a fast code in release and a safe code in debug (you can enable/disable them by defining the NDEBUG macro).
74,004,197
74,004,381
Fedora: 'GLFW/glfw3.h: No such file or directory'
I am very new to C when trying to make some example code I get the error basic.cc:18:10: fatal error: GLFW/glfw3.h: No such file or directory On further inspection the contents of the Makefile are # This Makefile assumes that you have GLFW libraries and headers installed on, # which is commonly available through your distro's package manager. # On Debian and Ubuntu, GLFW can be installed via `apt install libglfw3-dev`. COMMON=-O2 -I../include -L../lib -std=c++17 -pthread -Wl,-no-as-needed -Wl,-rpath,'$$ORIGIN'/../lib all: $(CXX) $(COMMON) testxml.cc -lmujoco -o ../bin/testxml $(CXX) $(COMMON) testspeed.cc -lmujoco -o ../bin/testspeed $(CXX) $(COMMON) compile.cc -lmujoco -o ../bin/compile $(CXX) $(COMMON) derivative.cc -lmujoco -fopenmp -o ../bin/derivative $(CXX) $(COMMON) basic.cc -lmujoco -lglfw -o ../bin/basic $(CXX) $(COMMON) record.cc -lmujoco -lglfw -o ../bin/record As I am on fedora I installed glfw through dnf sudo dnf install glfw but the its files are now in /usr/lib64/ where gcc does not see them (package information). How should I proceed?
The linked glfw package contains the compiled shared library only, but for development you also need glfw-devel package which contains the headers. but the its files are now in /usr/lib64/ where gcc does not see them It should see them, but that comes at play later during linking, the Makefile correctly adds -lglfw so it should work.
74,004,359
74,004,563
Pointers in C++ - value pointed by two pointers
I'm trying to understand an example provided in this tutorial. // more pointers #include <iostream> using namespace std; int main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed to by p1 = 10 *p2 = *p1; // value pointed to by p2 = value pointed to by p1 -> What is this line doing? p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed to by p1 = 20 cout << "firstvalue is " << firstvalue << '\n'; cout << "secondvalue is " << secondvalue << '\n'; return 0; } What is the line *p2 = *p1 doing? When I try to run the code without it, I do not see any difference.
*p2 = *p1; sets the value pointed to by p2 to the value pointed to by p1. So in effect sets secondvalue to 10. It doesn't appear to have any effect because the next two lines make p1 point to the same thing as p2 (secondvalue) and set the value there to 20. The effect of the line in the question is overwritten. Try this version that outputs everything at each step: #include <iostream> int main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue std::cout << "[1]\n"; std::cout << "p1 is " << p1 << " which holds " << *p1 << '\n'; std::cout << "p2 is " << p2 << " which holds " << *p2 << '\n'; std::cout << "firstvalue is " << firstvalue << '\n'; std::cout << "secondvalue is " << secondvalue << '\n'; *p1 = 10; // value pointed to by p1 = 10 std::cout << "[2]\n"; std::cout << "p1 is " << p1 << " which holds " << *p1 << '\n'; std::cout << "p2 is " << p2 << " which holds " << *p2 << '\n'; std::cout << "firstvalue is " << firstvalue << '\n'; std::cout << "secondvalue is " << secondvalue << '\n'; *p2 = *p1; // value pointed to by p2 = value pointed to by p1 std::cout << "[3]\n"; std::cout << "p1 is " << p1 << " which holds " << *p1 << '\n'; std::cout << "p2 is " << p2 << " which holds " << *p2 << '\n'; std::cout << "firstvalue is " << firstvalue << '\n'; std::cout << "secondvalue is " << secondvalue << '\n'; p1 = p2; // p1 = p2 (value of pointer is copied) std::cout << "[4]\n"; std::cout << "p1 is " << p1 << " which holds " << *p1 << '\n'; std::cout << "p2 is " << p2 << " which holds " << *p2 << '\n'; std::cout << "firstvalue is " << firstvalue << '\n'; std::cout << "secondvalue is " << secondvalue << '\n'; *p1 = 20; // value pointed to by p1 = 20 std::cout << "[5]\n"; std::cout << "p1 is " << p1 << " which holds " << *p1 << '\n'; std::cout << "p2 is " << p2 << " which holds " << *p2 << '\n'; std::cout << "firstvalue is " << firstvalue << '\n'; std::cout << "secondvalue is " << secondvalue << '\n'; return 0; } Typical output: [1] p1 is 0x7ffc5f63a940 which holds 5 p2 is 0x7ffc5f63a944 which holds 15 firstvalue is 5 secondvalue is 15 [2] p1 is 0x7ffc5f63a940 which holds 10 p2 is 0x7ffc5f63a944 which holds 15 firstvalue is 10 secondvalue is 15 [3] p1 is 0x7ffc5f63a940 which holds 10 p2 is 0x7ffc5f63a944 which holds 10 firstvalue is 10 secondvalue is 10 [4] p1 is 0x7ffc5f63a944 which holds 10 p2 is 0x7ffc5f63a944 which holds 10 firstvalue is 10 secondvalue is 10 [5] p1 is 0x7ffc5f63a944 which holds 20 p2 is 0x7ffc5f63a944 which holds 20 firstvalue is 10 secondvalue is 20 The format of pointer values in output may be different and the values will be different. But you can see at step [3] the value held at p1 is copied over the value pointed to by p2.
74,004,519
74,006,304
Creating two outputs for two, two dimentional arrays, using two nested for loops?
Completely new to programming, i come from only excel experience so any help appreciated. The expressions calculate the altitude and bearing of the sun given your latitude, the hour of the day t and day of the year day. The altitude calculation works fine, however the bearing calculation has sporadic nonsence negative values in the output. These values which are stored in their respective arrays will be later used for other claculations. Here's my block of code: #include <iostream> #include <cmath> using namespace std; float degrees(float radians) { // gets degrees return (radians * (180 / 3.14)); } float radians(float degrees) { //gets radians return (degrees * (3.14 / 180)); } int main() { float latitude = 54; // cout << "Enter latitude (in degrees): "; // cin >> latitude; float const sin_thi = sin(radians(latitude)); float const cos_thi = cos(radians(latitude)); // cout << "sin_thi: " << sin_thi << endl; // cout << "cos_thi: " << cos_thi << endl; float cos_omega[24]; // required for later calculation for (int t = 0; t <= 23; t++) { cos_omega[t] = cos(radians((15 * (t - 12)))); // cout << cos_omega[t] << endl; } // gathering sun altitude and bearing data, storing into heap multidimentional arrays "alt_sun[][]" and "bearing_sun[][]". auto alt_sun = new int [365][24]; auto bearing_sun = new int [365][24]; for (int day = 0; day <= 364; day++) { for (int t = 0; t <= 23; t++) { alt_sun[day][t] = degrees(asin(((0.4 * cos(radians(0.99 * (day - 173)))) * sin_thi) + ((sin(((0.4 * cos(radians(0.99 * (day - 173)))) - 1.57)))) * (cos_omega[t] * cos_thi))); if (cos_omega[t] > 0) bearing_sun[day][t] = 360 - degrees(acos((((0.4 * cos(radians(0.99 * (day - 173)))) * cos_thi) - ((sin(((0.4 * cos(radians(0.99 * (day - 173)))) - 1.57))) * (cos_omega[t] * sin_thi))) / (cos(radians(alt_sun[day][t]))))); else bearing_sun[day][t] = degrees(acos((((0.4 * cos(radians(0.99 * (day - 173)))) * cos_thi) - ((sin(((0.4 * cos(radians(0.99 * (day - 173)))) - 1.57))) * (cos_omega[t] * sin_thi))) / (cos(radians(alt_sun[day][t]))))); } } for (int day = 0; day <= 364; day++) // to test calculation { cout << "Day " << day << ": " << bearing_sun[day][12] << endl; } } Is there something fundamentally wrong with what im doing? Expected results for the printed bearing values are to range from about 350 - 360 (roughly due to rounding on my previously made excel calculation). For example the first value should be about 355. The code should run without user input and the problem should be explicit now. My first thought was that the bad results were only happening when the else statement was used in the loop. But my limited amateur testing, like just running the single expression outside of the for loop and if statement, produced the same results. Which in my mind leaves only the expression itself, or the array as a possible cause. An example screenshot of some of the output to the console, all the positive values are correct, all the negative values are wrong Thanks
When I run your program with UndefinedBehaviorSanitizer active, I get a run-time error message in line 48 and 51 that you are converting a NaN to an integer, which invokes undefined behavior. This means that your calculatings are producing a NaN. When I run your program line by line in a debugger, I notice that when line 51, which is bearing_sun[day][t] = degrees(acos((((0.4 * cos(radians(0.99 * (day - 173)))) * cos_thi) - ((sin(((0.4 * cos(radians(0.99 * (day - 173)))) - 1.57))) * (cos_omega[t] * sin_thi))) / (cos(radians(alt_sun[day][t]))))); is executed for the first time, it writes the value -2147483648 into bearing_sun[0][0], which does not seem to be the intended value. Since this line is a very long line, I modified it to several lines, so that I can examine the intermediate results more easily: else { auto intermediate_result_1 = (0.4 * cos(radians(0.99 * (day - 173)))) * cos_thi; auto intermediate_result_2 = sin(((0.4 * cos(radians(0.99 * (day - 173)))) - 1.57)); auto intermediate_result_3 = cos_omega[t] * sin_thi; auto intermediate_result_4 = cos(radians(alt_sun[day][t])); auto intermediate_result_5 = intermediate_result_2 * intermediate_result_3; auto intermediate_result_6 = intermediate_result_1 - intermediate_result_5; auto intermediate_result_7 = intermediate_result_6 / intermediate_result_4; auto intermediate_result_8 = acos( intermediate_result_7 ); auto intermediate_result_9 = degrees( intermediate_result_8 ); bearing_sun[day][t] = intermediate_result_9; } This code is much easier to inspect when running the code line by line in a debugger, because you can see the intermediate results. When I reach the line auto intermediate_result_8 = acos( intermediate_result_7 ); I can see in the debugger that intermediate_result_7 has the value -1.0009622545441585. Since this is invalid input for the function acos, it will correctly return NaN, so that the final result also is NaN, which is converted to an int, which invokes undefined behavior. This explains the "nonsense negative values" that you mentioned in the question. Therefore, there appears to be something wrong with the formula that you are using. In order to find the problem, you will have to run the program line by line in a debugger, checking the values of all of the intermediate results.
74,004,622
74,005,456
How to populate every row of two dimensional array C++
I'm starting to learn C++ and C in context of embedded devices, and recently I started to make my own libraries, to clean up my code a little bit. I have a problem with passing two dimensional array to my function. The problem is as follows: uint8_t cardSectors[8][16]; cardsClient.readDataBlocks(uid, uidLength, *cardSectors, 8, 16); As you can see I'm passing cardSectors as pointer to the array. Later in the function reading the card, I'm writing the card data onto the pointer by using: mifareclassic_ReadDataBlock(currentBlock, &cardSectors[currentBlock]); And it works! I can read the data by using: &cardSectors[currentBlock]. But here is the catch. What about reading the data from original variable uint8_t cardSectors[8][16] ? I cannot get into data that I want no matter what I did. I don't know if I'm not saving this data really or something else is wrong. Basically this is a call stack: uint8_t cardSectors[8][16]; cardsClient.readDataBlocks(uid, uidLength, *cardSectors, blocks, blockSize); Serial.println("Do something with this data!"); How one goes about accessing this data after readDataBlocks was executed?
In C++, it is probably easiest to #include <vector> template <class T> using Arr2D = std::vector<std::vector<T>>; and to pass this type around. Since C is just barely above the level of an assembly language, lacking templates and other convenient concepts, one way to approach 2D arrays is to have a linear chunk of memory and to calculate the index into the memory with some formula like ìndex = row * ncols + col. This saves you some work constructing and cleaning up of some arrays of pointers to something structure and it also gives better cache locality compared to allocating each row individually on the heap. typedef struct Arr2D_tag { void* data; size_t element_size; size_t nrows; size_t ncols; } Arr2D_t; void* arr2d_at(Arr2D_t *array, size_t row, size_t col) { if (NULL == array) return NULL; if (NULL == array->data) return NULL; if (row >= array->nrows) return NULL; if (col >= array->ncols) return NULL; size_t index = row * array->ncols + col; return (char*)array->data + array->element_size * index; } Along with the usual C style wild casting to the type you expect. You can pretty this up further, by having a per-type facade to the thing (a struct of function pointers for the operations on an array of a specific type, constructed with some preprocessor macros or something). It will still look ugly but may be a tad more convenient to use. If you only have fixed size matrices, like 3x3 or 4x4 as is so often in the context of computer graphics, you could alternatively to the first given C++ version use std::array instead, giving you the extra benefits of not having to use the heap and having the same cache locality as the C version: #include <array> template <size_t NROW, size_t NCOL> using Arr2D_f32 = std::array<std::array<float,NCOL>, NROW>; // ad lib for other types, e.g. template <size_t NROW, size_t NCOL> using Arr2D_f64 = std::array<std::array<double,NCOL>, NROW>; Once you have those types, populating them is easy: void populate_my_array2d(Arr2D_size_t<7,13>& a) { size_t value = 1; for (auto& row : a) { for (auto& col : row) { col = value++; } } } In the C-case, since the underlaying storage is just a 1d array, to just fill the matrix with a single value, you only need 1 loop, instead of 2 nested loops. Here the general case: #include <stdbool.h> bool populate_my_array( Arr2D_t * array, const void* value) { if (NULL == array) return false; for (size_t r = 0; r < array->nrows; r++) { for (size_t c = 0; c < array->ncols; c++) { void* cell = arr2d_at(array,r,c); if (NULL != cell) { memcpy(cell,value,array->element_size); } else { return false; } } } return true; }
74,005,197
74,005,253
How to get a compiler error for assignments in an if statement?
Is it possible in Visual Studio to get a compiler error for an assignment in an if statement? How? #include <iostream> int main() { int a = 2; if (a = 3) // Want a warning here std::cout << "Avoid this!\n"; } I know I can switch to Yoda conditions (if (3=a)), but I really don't want to. I tried: setting the warning level to /Wall but I still don't get a warning that I could then treat as an error. I am doing this in Visual Studio 2019 (16.11.19).: The build output is Rebuild started... 1>------ Rebuild All started: Project: Yoda2019, Configuration: Debug Win32 ------ 1>Yoda2019.cpp 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\limits.h(70,5): error C2220: the following warning is treated as an error 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\limits.h(70,5): warning C4668: '__STDC_WANT_SECURE_LIB__' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\xmemory(154,5): warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\xmemory(164,5): warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\atomic(284,9): warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\atomic(299,9): warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\atomic(315,9): warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\atomic(375,9): warning C4365: 'argument': conversion from 'long' to 'unsigned int', signed/unsigned mismatch 1>Done building project "Yoda2019.vcxproj" -- FAILED. ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ========== and Visual Studio 2022 (17.4.0) The build output is Rebuild started... 1>------ Rebuild All started: Project: YodaCheck, Configuration: Debug x64 ------ 1>YodaCheck.cpp 1>YodaCheck.vcxproj -> B:\Projekte\C++\Dynamic Linking\YodaCheck\x64\Debug\YodaCheck.exe ========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ========== ========== Elapsed 00:01,379 ========== so I see no warning which I could convert into an error.
You can turn any specific warning into an error, using the #pragma warning(error:nnnn) directive. In your case, the warning is: warning C4706: assignment within conditional expression So, adding the relevant #pragma directive to the code will generate a compiler error: #include <iostream> #pragma warning(error:4706) int main() { int a = 2; if (a = 3) // Want a warning here std::cout << "Avoid this!\n"; } This now gives: error C4706: assignment within conditional expression For a solution wide setting, change it here in the property pages:
74,005,282
74,005,487
C++ : unexpected behavior when incrementing a value from multiple threads
I'm currently learning about threads and my professor in class showed us this example attempting to demonstrate concurrency for threads #include <iostream> using namespace std; void* threadHandler(void * val) { long long* a = (long long *) val; for (long long i = 0; i<100000; i++) (*a)++; int id = pthread_self(); printf("thread : %d a = %d\n", id, *a); pthread_exit(nullptr); } int main() { long long a = 0; pthread_t t1, t2; pthread_setconcurrency(2); pthread_create(&t1, nullptr, threadHandler, &a); pthread_create(&t2, nullptr, threadHandler, &a); pthread_join(t1, nullptr); pthread_join(t2, nullptr); printf("main : a = %d\n", a); return 0; } Could anyone explain why the resulting value of a is not 200,000 as expected? The values are inconsistent, and always below 200,000. However, when the incrementing loop is reduced to 10,000 , the result is as expected : a = 20,000. Thanks.
pthread_t t1, t2; Your professor is showing you historical POSIX thread API, that was mostly used in ancient times, back when dinosaurs roamed the Earth mostly armed with C (C++ has not been invented yet). Modern C++ uses std::threads to implement multiple execution threads. However, whether it's POSIX threads, or modern C++'s std::thread, the underlying fundamental problem is the same: (*a)++; The object referenced here (a counter, in this case) is getting modified by multiple execution threads. In C++ when an object is accessed by multiple threads, and that access includes at least one execution thread modifying the object (not even all of them), every access to the object must be synchronized. You can't just modify an object, in multiple execution threads, just like that. Interthread synchronization in itself is a complex topic, with many rules, that involves mutexes and condition variables, that cannot be summarized in just one or two sentences except to mention that the term "synchronization" refers to changes to the shared object made by one execution thread getting "synchronized" to other execution threads. Hopefully your class uses a good C++ textbook that offers a full and thorough discussion of thread synchronization, where I'll refer you for complete information on this topic. Improper thread synchronization results in undefined behavior. The results you get are, therefore, completely nonsensical, and may actually vary every time you run your program.
74,005,470
74,005,594
ID3D11RenderTargetView gets removed on ID3D11DeviceContext::OMSetRenderTargets()
I built a very simple, okay nothing, program that just clears the render target. Eventually when I call ID3D11DeviceContext::OMSetRenderTargets() the ID3D11RenderTargetView gets removed and I can't see why. My thought is somewhere at the creating of the IDXGISwapChain1 I specified something wrong. Once: UINT deviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #ifdef _DEBUG deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif GFX_THROW_IF_FAILED(D3D11CreateDevice( nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, deviceFlags, nullptr, 0u, D3D11_SDK_VERSION, &m_pDevice, &m_featureLevel, &m_pContext )); if (m_featureLevel < D3D_FEATURE_LEVEL_11_0) throw ExceptionMessage(__FILE__, __LINE__, "Graphics device does not support feature level 11."); Microsoft::WRL::ComPtr<IDXGIFactory2> pFactory = {}; GFX_THROW_IF_FAILED(CreateDXGIFactory(IID_PPV_ARGS(&pFactory))); DXGI_SWAP_CHAIN_DESC1 scDesc = {}; scDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scDesc.SampleDesc.Count = 1u; scDesc.SampleDesc.Quality = 0u; scDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scDesc.BufferCount = sc_uBufferCount; scDesc.Scaling = DXGI_SCALING_NONE; scDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; scDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; scDesc.Flags = 0u; GFX_THROW_IF_FAILED(pFactory->CreateSwapChainForHwnd( m_pDevice.Get(), t_hWnd, &scDesc, nullptr, nullptr, &m_pSwapChain )); m_uWindowWidth = scDesc.Width; m_uWindowHeight = scDesc.Height; Microsoft::WRL::ComPtr<ID3D11Resource> pBackBuffer = {}; GFX_THROW_IF_FAILED(m_pSwapChain->GetBuffer(0u, IID_PPV_ARGS(&pBackBuffer))); GFX_THROW_IF_FAILED(m_pDevice->CreateRenderTargetView(pBackBuffer.Get(), nullptr, &m_pTarget)); and the update method: float color[] = { (252.0f / 255.0f), (186.0f / 255.0f), (3.0f / 255.0f), 1.0f }; m_pContext->ClearRenderTargetView(m_pTarget.Get(), color); m_pContext->OMSetRenderTargets(1u, &m_pTarget, nullptr); if (m_pTarget.Get() == nullptr) throw ExceptionMessage(__FILE__, __LINE__, "m_pTarget has been set to null"); GFX_THROW_IF_FAILED(m_pSwapChain->Present(1u, 0u));
I assume that you are using Microsoft::WRL::ComPtr to manage m_pTarget. So when invoking m_pContext->OMSetRenderTargets(1u, &m_pTarget, nullptr); an overloaded operator & is being used rather than just taking an address of pointer to pass it as a pointer to first element of array containing a single pointer. Overloaded operator & is intended to be used when passing a pointer to pointer value to some initialization function so it releases ownership of the stored pointer therefore you are getting nulls. You should use GetAddressOf method m_pContext->OMSetRenderTargets(1u, m_pTarget.GetAddressOf(), nullptr); or create a temporary array instead: ::std::array<::ID3D11RenderTargetView *> views{m_pTarget.Get()}; m_pContext->OMSetRenderTargets(views.size(), views.data(), nullptr);
74,006,203
74,006,245
Why is my value converted from int to char?
#include<iostream> #include<string> class Person_t{ private: uint8_t age; public: void introduce_myself(){ std::cout << "I am " << age << " yo" << std::endl; } Person_t() : age{99} { }; }; int main(){ Person_t person1{}; person1.introduce_myself(); } When the shown code is executed, the integer from the initializer list gets converted to a c. I have no explaination why, could someone please explain this to me?
<< age age is a uint8_t, which is an alias for an underlying native type of a unsigned char. Your C++ library implements std::ostream's << overload for an unsigned char as a formatting operation for a single, lonely, character. Simply cast it to an int. << static_cast<int>(age)
74,006,527
74,006,623
slice container with O(1) constructor from iterable begin and end
I have a forward iterator. I want a simple iterable container which wraps it and exposes begin() and end(). I.E. template <typename C> void use_container(C c) { std::cout << c.begin(); } int main() { std::vector<int> v {1,2,3,4,5,5}; auto begin_ = v.begin(); auto end_ = begin + 5; use_container(/*create a container using the `begin_` and `end_` variables*/); return 0; } Is there such a std wrapper?
C++20 added this with std::ranges::subrange. For example the following will call use_container with a range that is a view over part of v: use_container(std::ranges::subrange{begin_, end_}); Demo
74,007,398
74,008,100
After writing to a text file using c++ there are only some unreadable characters in that file
I wrote a program to write some integers to a text file using c++. But after running the code, there are only some unreadable characters inside the text file. How do I fix it? My code is as follows. #include <iostream> using namespace std; int main(){ FILE *fp; fp=fopen("my.txt","w"); for (int i =1; i<= 10; i++){ putw(i, fp); } fclose(fp); return 0; } This is how it shows the text file after running the code above. [1]: https://i.stack.imgur.com/uqOxs.jpg
after running the code, there are only some unreadable characters inside the text file. How do I fix it? ... This is how it shows the text file after running the code The problem is that you expect it to be a text file, but putw writes the ints to the file in binary format. In order to get readable characters in a text file, use the std::fprintf function instead of putw. #include <cstdio> // This is correct header for `fopen` int main(){ std::FILE* fp = std::fopen("my.txt", "w"); if (fp) { for (int i =1; i<= 10; i++){ std::fprintf(fp, "%d", i); } std::fclose(fp); } } The C++ way to do the same thing would be to use fstreams: #include <fstream> int main() { std::ofstream fs("my.txt"); if (fs) { for (int i = 1; i <= 10; i++) { fs << i; } } }
74,007,648
74,075,428
How to call worker thread function from main thread in Emscripten app?
I need to access local fonts of browser in WASM/Emscripten program. I am able to to that using queryLocalFonts API from here https://wicg.github.io/local-font-access/ Now accessing and processing local fonts is taking too long I need to do it in worker thread. Calling the API from worker thread is not supported yet so I am trying to call it from main thread then pass font data to worker thread for processing. The problem is I can't figure out how to create and use worker thread in Emscripten app. I can create a worker thread in C++ using emscripten_malloc_wasm_worker from here https://emscripten.org/docs/api_reference/wasm_workers.html#example-code but I don't know how to call it from Javascript where I get font results from API call. On the other hand when I try to create web worker in JavaScript using this call Module.LocalFontProcessingThread = new Worker("./ProcessLocalFonts.js") then I am not sure what should be the content of ProcessLocalFonts.js. If I put a placeholder like this self.onmessage = function handleMessageFromMain(msg) { console.log("77777777777777777 message from main received in worker:", msg); }; then I am getting error from Emscripten like self is not defined. Do you know how that can be done? An example of calling worker thread from main thread in Emscripten app would be helpful.
I have not used Emscripten's worker API. I can think of 2 other possibilities I can recommend. One is to load the wasm module in a worker OR use pthread and create a function to run in a separate worker internally through Emscripten's thread emulation. Let's start with pthread support. You'd need the flags USE_PTHREADS=1 and PTHREAD_POOL_SIZE=4. Change pool size to what you might need. With this threadpool library, you can instantiate threads and submit functions to threads. How you manage, track and propagate completion/fail of threads is upto you. I usually pass in a JS callback funtion as emscripten::val object. Keep in mind you can't call emscripten::val from threads so maybe track an internal variable that is passed to the threaded function so it can use it as an indicator that the function is complete. This is definitely more complicated than the alternative for simpler use-cases. Alternate way is to load WASM in a web worker. Make sure you have ENVIRONMENT=web,worker instead of web only. In that case, you can write you C++ function as a sequential implementation and it'll run within the context of the web worker that initialized it. It'll be same as loading the wasm in normal circumstances. You can load your font information in main thread, pass it to worker thread which in turn passes it to the function call to its own wasm module instance.
74,008,249
74,008,445
Does division operator ( / ) in C++ return the floor value in case of num with same sign and ceil value when both the numbers are of opposite sign?
In C++ , when both numerator and denominator are integers and of same sign , then division operator gives the floor value of the quotient . But when they are of opposite sign , then it gives ceil value . Is my understanding correct or is there more to it ?
You have it right. Some 20th-century hardware engineer decided to do it this way, and as far as I know this is how all microprocessors now natively do it. Mathematically, it's often a little inconvenient, which is why Python (for example) corrects in software always to round toward toward floor. For additional insight, besides p/q for an integer quotient, try p%q for the corresponding remainder. Your question is tagged C++ but this is really a computer hardware issue and, as such, it may be more helpful to consult the C17 standard, whose sect. 6.5.5(6) reads: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.... (I have a shred of a memory from 25 or 30 years ago, reading about a CPU that rounded toward floor. If my memory is not altogether imaginary, then that CPU apparently did not succeed in the marketplace, did it?)
74,008,493
74,008,751
Multithreaded concurrent file reading/writing, managing container of processes
Wholly new to multithreading. I am writing a program which takes as input a vector of objects and an integer for the number of threads to dedicate. The nature of the objects isn't important, only that each has several members that are file paths to large text files. Here's a simplified version: // Not very important. Reads file, writes new version omitting // some lines void proc_file(OBJ obj) { std::string inFileStr(obj.get_path().c_str()); std::string outFileStr(std::string(obj.get_path().replace_extension("new.txt").c_str())); std::ifstream inFile(inFileStr); std::ofstream outFile(outFileStr); std::string currLine; while (getline(inFile, currLine)) { if (currLine.size() == 1 || currLine.compare(currLine.length()-5, 5, "thing") != 0) { outFile << currLine << '\n'; } else { for (int i = 0; i < 3; i++) { getline(inFile, currLine); } } } inFile.close(); outFile.close(); } // Processes n file concurrently, working way through // all OBJ in objs void multi_file_proc(std::vector<OBJ> objs, int n) { std::vector<std::thread> procVec; for (int i = 0; i < objs.size(); i++) { /* Ensure that n files are always being processed. Upon completion of one, initiate another, until all OBJ in objs have had their text files changed. */ } } I want to loop through each OBJ and write altered versions of their text files in concurrence, the limitation on simultaneous file read/writes being the thread value (n). Ultimately, all the objects' text files must be changed, but in such a way that there are always n files being processed, to maximize efficiency in concurrence. Note the vector of threads, procVec. I originally approached this by managing a vector of threads, with a file being processed for each thread in procVec. From my reading, it seems a vector for managing these tasks is logical. But how do I always ensure there are n files open until all have been processed, without exiting with an open thread? Edit: Apologies, my intention was not to ask others to write code for me. I just didn't want my approach to bias anyone's answer if the approach was bad to begin with. These are some things I've tried (this code would go into the block comment in my function): 1. First approach. Idea is to add to procVec up until the thread limit n was reached, then join, remove a process from the front of the vector upon its completion. This is a summary of several similar iterations, none of which worked: if (i >= n) { procVec.front().join(); procVec.erase(procVec.begin()); } procVec.push_back(std::thread(proc_file, sra[i])); Problems with this: Incorrectly assumes front of vector will always finish first (Possibly?) Invalidates all iterators in procVec after first is erased 2. Using mutexes, I attempt writing a lambda function where the thread would be removed upon its completion. This is my current approach. Unsure why it isn't working, or if it even suits my needs: // remThread() and lamb() defined above main function, **procVec** and **threadMutex** //are global variables void remThread(std::thread::id id) { std::lock_guard<std::mutex lock(threadMutex); auto iter = std::find_if(procVec.begin(), procVec.end(), [=](std::thread &t) {return (t.get_id() == id); }); if (iter != procVec.end()) { iter->join(); procVec.erase(iter); } } void lamb(SRA sra, std::thread::id id) { proc_file(sra); remThread(id); } // This is the code contained in the main for loop. called lambda to process file // and then remove thread std::lock_guard<std::mutex> lock(threadMutex); procVec.push_back(std::thread([sras, i]() { std::thread(lamb, sras[i], std::this_thread::get_id()).detach(); })); Problems with this: Program terminates, likely a joinable thread is active, leaves scope
Given that the example you show is fairly simple, a for loop of fixed size, no strange dependencies, a very simple solution could be to use OpenMP which would allow you to do what you describe (providing I understood correctly) by adding a single line void multi_file_proc(std::vector<OBJ> objs, int n) { std::vector<std::thread> procVec; #pragma omp parallel for num_threads(n) schedule(dynamic, 1) for (int i = 0; i < objs.size(); i++) { /* ... */ } } in front of the for loop. Of course you then have to modify your compile command to add openmp support, the precise flag naturally being different from compiler to compiler i.e. -fopenmp for g++, -qopenmp for icpc, etc. The line above basically instructs the compiler to create code to execute the for loop below in parallel. The important bit here is the last one where we set the schedule. Dynamic simply means that the order is not predetermined, instead threads will get their next iteration when they finish with the last. The integer 1 there defines the number of steps they take at a time, given that each file is large we want something fine grained since we don't expect too much overhead from the scheduling. A word of caution, OpenMP, like most of C++, will not even try to stop you from shooting yourself in the foot. And with concurrency there are whole new ways to do just that. Finally, this is by no means guaranteed to be the absolute best solution outright. For instance if your files are of varying lengths then you would probably want to sort the objects from longest to shortest before the loop. This way once the last object is being processed (at some point only a single thread will be working on the final object) that won't take too long.
74,008,646
74,008,995
Is it a bad idea to acquire a lock in a destructor?
Say we have something along the lines of the following pseudocode, with the goal of achieving both concurrency and taking advantage of RAII: class Foo { public: vector<int> nums; mutex lock; }; class Bar { public: Bar(Foo &foo) : m_foo(foo) { lock_guard<mutex>(foo.lock); m_num = foo.nums.back(); foo.nums.pop_back(); } ~Bar() { lock_guard<mutex>(foo.lock); foo.nums.push_back(m_num); } private: Foo &m_foo; int m_num; }; Then, say we may have any number of instances of Bar, with the idea being that when they go out of scope, the destructor will return their held "resource" to the controller Foo class. However, we also need to ensure thread safety, hence the locks. I'm a little wary of this design, however, since taking a mutex in a destructor seems like a bad idea intuitively. Am I overthinking things, or if not, is there a better way to take advantage of RAII here?
There's nothing inherently wrong with locking a mutex in a destructor. For instance, shared resources might need to be made thread-safe. Releasing ownership of a shared resource, then, might require locking a mutex. If RAII just fell apart in multithreaded programming, it wouldn't be a very useful tool. Indeed, access to a std::shared_ptr's control block is thread safe, including when decrementing the reference counter during the shared pointer's destruction. Apparently this is usually implemented with atomic operations rather than a mutex lock (don't quote me on this), but the context is the same: you're releasing ownership of a shared resource during destruction, and that has to be recorded in a thread-safe way. However, keep in mind: locking a mutex can throw an exception, and you should (almost) always absorb exceptions in destructors with try/catch. Otherwise, if the stack is already unwinding due to another exception, the program will terminate immediately and irrecoverably, regardless of whether the calling code is equipped to absorb the original exception and / or the destructor's exception. But there might be a way to restructure your code to avoid the issue entirely: A Bar doesn't actually need a reference to a Foo; it only needs an int. In your code, the Bar requests an int from a given Foo. When the Bar is destroyed, it needs to give the int back to the Foo so that it can be recycled; this requires storing an internal reference to the Foo throughout its lifetime so that it can communicate with it during destruction. Instead, consider giving the int to the Bar directly upon construction, and taking the int away from it upon destruction. This is the driving principle behind dependency injection, which constitutes the 'D' in "SOILD". Consequently, it brings with it all of the typical advantages of dependency injection (e.g., improving testability of the Bar class). For instance, this logic could be tracked in a larger class which manages a Foo object along with all of its associated Bar objects. Here's some pseudocode, but the exact interface details will depend on your application: class BarPool: Foo foo; Map<int, Bar> bars; mutex m; BarPool(Foo foo) : foo(foo) {} int add_bar(): lock m; // Note: foo.pop() should probably be made thread-safe // by internally locking / unlocking foo's mutex int i = foo.pop() bars.add(i, new Bar(i)); unlock m; return i void remove_bar(int i): lock m; // foo.push() should also probably be made thread-safe bars.remove(i) foo.push(i) unlock m; ...
74,008,941
74,009,871
Conditionally passing ownership for members
Assume the following sketch: struct C { (either T or T&) m_t; C(T& t): (instantiate m_t as T& m_t(t)) {} C(T&& t): (instantiate m_t as T(t)) {} }; such that a C either has or has not ownership of t, depending on how the C was constructed. Is that possible, possibly without resorting to shared_ptr and thus having to move everything to heap? I'm trying around with std::variant, but without success so far.
Something along these lines perhaps: struct C { std::optional<T> t_holder; T& m_t; C(T& t) : m_t(t) {} C(T&& t) : t_holder(std::move(t)), m_t(*t_holder) {} }; Would also need a copy and/or move constructor (the implicit one won't do the right thing); and the copy/move assignment operators would have to be deleted as I don't think they could be implemented reasonably. One way to salvage assignment would be to replace T& with std::reference_wrapper<T>; it behaves almost like a reference, but can be rebound.
74,009,327
74,009,383
How to free member variable malloc memory in a destructor
//Constructor page_frames = (Page*) malloc(page_count*PAGE_SIZE); for (uint32_t i = 0 ; i < page_count; ++i) { page_frames = new Page[PAGE_SIZE]; page_frames++; } //Destructor free(page_frames) page_frames is a member variable of type Page*. Whether I try to deallocate the memory in the destructor, valgrind returns "Invalid free() / delete / delete[] / realloc()". I would like to free up the memory left by malloc() to prevent any leaks. Is there a way to free memory of a member variable in the class destructor?
I'm assuming page_frames is a member variable declared as Page* page_frames in your class declaration. And you are attempting to create an "array of Pages" This: page_frames = (Page*) malloc(page_count*PAGE_SIZE); for (uint32_t i = 0 ; i < page_count; ++i) { page_frames = new Page[PAGE_SIZE]; page_frames++; } Has several issues. The initial malloc'd page_frames gets overwritten on the first iteration of the loop by the new call. The other issue is that pages_frames itself is getting adjusted to something else each time you invoke page_frames++. Hence, your free(page_frames) statement doesn't pass the value that was returned from malloc. Option 1 This closer to what you want: page_frames = (Page*) malloc(page_count*PAGE_SIZE); for (uint32_t i = 0 ; i < page_count; ++i) { page_frames[i] = {}; // default construct a page } But that's using C allocation semantics instead of C++ style allocations for objets. We can do better. Option 2 Keep to using C++ allocation semantics. This is even simpler and doesn't require a for-loop page_frames = new Page[page_count]; And your corresponding destructor statement is this; delete [] page_frames; Option 3 No explicit allocation/deletion require. Let the C++ collection class library do the hard work for you. Declare page_frames as std::vector<Page>. And your constructor is just this: page_frames.resize(page_count); And no destructor work needed.
74,009,492
74,009,748
regular expression not evaluating string correctly
I'm trying to split a string based on space except when inside quotes. This is the regex I found online (\\w+|\".*?\"). However, when I try to use std::regex to split a string, I get only empty strings. This is the code I have to split: std::regex exp("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'"); std::sregex_token_iterator itr(s.begin(), s.end(), exp, -1); std::sregex_token_iterator end; for (; itr != end; itr++) std::cout << *itr << std::endl; This prints out only " " when I pass a string like "A "B C" 123". What could I be doing wrong?
From documentation for std::sregex_token_iterator: submatch - the index of the submatch that should be returned. "0" represents the entire match, and "-1" represents the parts that are not matched (e.g, the stuff between matches). Since you're passing -1, it means you're printing the parts that didn't match, not the parts that matched.
74,009,750
74,011,054
My pulse duration calculation is inaccurate. Why?
I'm studying arduino. I generated pulse waves using arduino analog PWM output. Mega pin No.4 -> 980Hz output => approximately 1000Hz => 1ms duration/pulse => 1000us I used 50% duty cycle, so 500us pulse output. I connected PWM output to digital input No.10 pin. And here is my code. (for HIGH pulse duration) int aoPin = 4; // analog output pin int diPin = 10; // digital input pin void setup() { Serial.begin(9600); pinMode(aoPin, OUTPUT); pinMode(diPin, INPUT); } void loop() { unsigned long highPulse = 0; // Pulse length unsigned long startMicros = micros(); analogWrite(aoPin, 128); // half duty cycle of 980Hz (arduino Mega pin No.4) while (digitalRead(diPin)) // calculation method 1 { } highPulse = micros() - startMicros; Serial.print("highPulse1 = "); Serial.print(highPulse); Serial.print(" / "); highPulse = pulseIn(diPin, HIGH); // calculation method 2 Serial.print("highPulse2 = "); Serial.println(highPulse); delay(1000); } The result was 180 / 510 repeatedly. The PulseIn function calculated accurate 500us, but my calculated duration was too short (180us). Even PulseIn function was executed after my calculation function. Why? Was My function start delayed?
Change where you call micros() the first time, so you know you do it at a rising edge: unsigned long startMicros = 0; analogWrite(aoPin, 128); // half duty cycle of 980Hz (arduino Mega pin No.4) while (digitalRead(diPin)); // wait while input is high while (!digitalRead(diPin)); // wait while input is low startMicros = micros(); // Rising edge detected! while (digitalRead(diPin)); // wait while input is high // Falling edge detected, get time difference! highPulse = micros() - startMicros;
74,010,128
74,010,201
C++: Console outputting weird numbers when printing array
I'm beginning to learn about C++. I've been putting it off for a long time and I decided to start learning it. Currently, I'm having trouble finding the issue with my program. My program is supposed to take integers from the input, insert it into an array, and then sort it. Everything is working correctly-- even the sorting... most of the time... Sometimes the sorting works as intended. Sometimes it spits the numbers out in random orders. Sometimes it output really weird negative and positive integers that are very close to the upper and minimum bounds that integers can go. After hours of trying to figure out something about this, I just can't figure it out. I've been thinking that it has something with the pointers for the array? But I'm unsure because I barely know how pointers work. I've tried setting the array to hard-coded values and sorting with different algorithms, none of which helped whatsoever. #include <iostream> /*Sorting program*/ using namespace std; int* sortArray(int* array, int size) { for (int i = 0; i < size; i++) { int lowest; for (int k = i; k < size; k++) { if (array[k] < array[i] && array[k] < array[lowest]) { cout << array[k] << " is less than " << array[i] << endl; lowest = k; } } int temp = array[lowest]; array[lowest] = array[i]; array[i] = temp; } return array; } int main() { int low, high, target, size; cout << "Enter size of array : "; cin >> size; int *array = new int[size]; for (int i = 0; i < size; i++) { cout << "Enter array[" << i << "] : " << endl; int entry; cin >> entry; array[i] = entry; } /* */ array = sortArray(array, size); for (int i = 0; i < size; i++) { cout << "array[" << i << "] = " << array[i] << endl; } return 1; } Output >>OutputFile.exe Enter size of array : 4 Enter array[0] : 3 Enter array[1] : 4 Enter array[2] : 7 Enter array[3] : 4 array[0] = 2059292487 array[1] = 3 array[2] = 4 array[3] = 7 Output (program ran again, nothing changed) >>OutputFile.exe Enter size of array : 8 Enter array[0] : 3 Enter array[1] : 4 Enter array[2] : 8 Enter array[3] : 1 Enter array[4] : 88 Enter array[5] : 4 Enter array[6] : 5 Enter array[7] : 6 array[0] = 1 array[1] = 3 array[2] = 4 array[3] = 4 array[4] = 5 array[5] = 6 array[6] = 8 array[7] = 88
I assume as selection sort algorithm. /*Sorting program*/ using namespace std; int *sortArray(int *array, int size) { for (int i = 0; i < size; i++) { int lowest = i; for (int k = i; k < size; k++) { if (array[k] < array[i] && array[k] < array[lowest]) { cout << array[k] << " is less than " << array[i] << endl; lowest = k; } } int temp = array[lowest]; array[lowest] = array[i]; array[i] = temp; } return array; } int main() { int low, high, target, size; cout << "Enter size of array : "; cin >> size; int *array = new int[size]; for (int i = 0; i < size; i++) { cout << "Enter array[" << i << "] : " << endl; int entry; cin >> entry; array[i] = entry; } /* */ array = sortArray(array, size); for (int i = 0; i < size; i++) { cout << "array[" << i << "] = " << array[i] << endl; } return 1; } int lowest = i;
74,010,238
74,010,587
Qt::nativeEvent doesnt get called
Why does the nativeEvent function never get called? // .h class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); bool nativeEvent(const QByteArray& eventType, void* message, long*); //private slots: // virtual bool nativeEvent(const QByteArray & eventType, void * message, long * result) override; private: Ui::MainWindowClass ui; //protected: // bool nativeEvent(const QByteArray& eventType, void* message, long* result); }; //.cpp bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, long* result) { //... } I found some similar question where people suggest to define it as override but when i try: bool nativeEvent(const QByteArray& eventType, void* message, long*) override; It doesn't compile with the error: member function declared with 'override' does not override a base class member. Commented lines was other ways I tried to define it, but I got the same error above.
The signature of QWidget::nativeEvent() is: bool QWidget::nativeEvent( const QByteArray &eventType, void *message, qintptr *result) Thereby, qintptr is an Integral type for representing pointers in a signed integer (useful for hashing, etc.). Typedef for either qint32 or qint64. This type is guaranteed to be the same size as a pointer on all platforms supported by Qt. On a system with 32-bit pointers, qintptr is a typedef for qint32; on a system with 64-bit pointers, qintptr is a typedef for qint64. (Emphasize mine.) According to the reported error, member function declared with 'override' does not override a base class member on OPs platform sizeof (long) != sizeof (qintptr). E.g. on my platform (Visual Studio 2019 with target x64) sizeof (long): 4 sizeof (qintptr): 8. If the signature of a virtual member function doesn't match the signature of the overridden virtual base class member function the latter is just not overridden. To make such cases detectable by the compiler, the override identifier was introduced to make the intention clear. Hence, without override it just doesn't work. (I would've expected a warning of the compiler but that might depend on the compiler settings.) However, with override the compiler is forced to emit an error in this case. The fix is obvious: OP should use qintptr* instead of long* for the last parameter result. If it's expected to be in fact a long in the specific case of OP, it can be explicitly converted in the body of the function. Please, note that sizeof (long) is platform dependent as well: Fundamental types and usually varies between 32 and 64 bit. Thereby, it's always 32 bit in Visual Studio (with x86 as well as with x64) but 64 bit in Linux with g++ and target x64. (I forgot how it is when g++ emits 32 bit code on Linux…)
74,010,936
74,012,598
How to convert R to C++ for Rcpp
The following R code chunk is very inefficient in terms of speed and I need it to be significantly faster as in the original problem the length(dt) is quite large. Can you help me convert the following R code chunk to C++ in order to utilize RCPP function in R? My knowledge of C++ is very close to 0 and can't figure out how to do the conversion. inity <- 0 cumy <- rep(0,length = length(dt)) dec.index <- 1 startingPoint <- 2 temp <- numeric() repFlag <- F for (i in 2:length(dt)){ cumy[i] <- inity + rgamma(n = 1, shape = a*timedt, scale = b) inity <- cumy[i] if (dt[i] %in% decPoints){ if (dt[i] %in% LTset){ repFlag <- ifelse(cumy[i] >= LP, T, F) } else if (dt[i] %in% MainMDset && repFlag == T){ genRanProb <- rbinom(1,1,(1-p1)) cumy[i] <- inity*genRanProb inity <- cumy[i] } else if (dt[i] %in% ProbMDset && repFlag == T){ genRanProb <- rbinom(1,1,pA) cumy[i] <- inity*genRanProb inity <- cumy[i] } } } If you want to run the code, you can use following values: a <- 0.2 b <- 1 ph <- 1000 timedt <- 1 oppInt <- 90 dt <- seq(0,ph,timedt) LT <- 30 MainMDset <- seq(oppInt, ph, oppInt) ProbMDset <- c(0,seq((oppInt + oppInt/2), ph, oppInt)) LTset <- sort(c(ProbMDset, MainMDset)) LTset <- LTset - LT decPoints <- sort(c(LTset, ProbMDset, MainMDset)) decPoints <- decPoints[-which(decPoints < 0)] decPoints[1] <- 1 p1 <- 0 pA <- 0.5 LP <- 40 Code for follow up question: Rcpp::cppFunction(" NumericVector cumyRes(double a, double b, double timedt, NumericVector dt, NumericVector ProbMDset, NumericVector MainMDset, NumericVector decPoints, double LP, double LT, double p1, double pA, int ii, double x1, double x2){ bool repFlag = false; int n = dt.size(); double inity = 0; NumericVector out(n); std::unordered_set<double> sampleSetMd(MainMDset.begin(), MainMDset.end()); std::unordered_set<double> sampleSetProb(ProbMDset.begin(), ProbMDset.end()); std::unordered_set<double> sampleSetDec(decPoints.begin(), decPoints.end()); for (int i = 1; i < n; ++i){ ii = ii + 1; double d = dt[ii]; out[ii] = inity + rgamma(1, a * timedt, b)[0]; inity = out[ii]; if (sampleSetDec.find(d) != sampleSetDec.end()) { if (sampleSetProb.find(d + LT) != sampleSetProb.end() || sampleSetMd.find(d + LT) != sampleSetMd.end()) { repFlag = inity >= LP; } else if (sampleSetMd.find(d) != sampleSetMd.end() && repFlag) { double genRanProb = rbinom(1, 1, (1 - p1))[0]; for (int j = ii; ii < (ii+10); ++j){ out[j] = inity * genRanProb; } inity = inity * genRanProb; ii = ii + x1 - 1; } else if (sampleSetProb.find(d) != sampleSetProb.end() && repFlag) { double genRanProb = rbinom(1, 1, pA)[0]; for (int j = ii; ii < (ii+5); ++j){ out[j] = inity * genRanProb; } inity = inity * genRanProb; ii = ii + x2 - 1; }}} return out; }")
There are several errors in your C++ code, probably too many to list in a concise answer. However, the following corrections seem to follow your logic, and compiles to give similar answers to your R loop in less time: Rcpp::cppFunction(" NumericVector cumyRes(double a, double b, double timedt, NumericVector dt, NumericVector ProbMDset, NumericVector MainMDset, NumericVector decPoints, double LP, double LT, double p1, double pA){ bool repFlag = false; int n = dt.size(); double inity = 0; NumericVector out(n); std::unordered_set<double> sampleSetMd(MainMDset.begin(), MainMDset.end()); std::unordered_set<double> sampleSetProb(ProbMDset.begin(), ProbMDset.end()); std::unordered_set<double> sampleSetDec(decPoints.begin(), decPoints.end()); for (int i = 1; i < n; ++i){ double d = dt[i]; out[i] = inity + rgamma(1, a * timedt, b)[0]; inity = out[i]; if (sampleSetDec.find(d) != sampleSetDec.end()) { if (sampleSetProb.find(d + LT) != sampleSetProb.end() || sampleSetMd.find(d + LT) != sampleSetMd.end()) { repFlag = inity >= LP; } else if (sampleSetMd.find(d) != sampleSetMd.end() && repFlag) { double genRanProb = rbinom(1, 1, (1 - p1))[0]; out[i] = inity * genRanProb; inity = out[i]; } else if (sampleSetProb.find(d) != sampleSetProb.end() && repFlag) { double genRanProb = rbinom(1, 1, pA)[0]; out[i] = inity * genRanProb; inity = out[i]; }}} return out; }") You could test it with: cumyRes(a, b, timedt, dt, ProbMDset, MainMDset, decPoints, LP, LT, p1, pA)
74,011,785
74,013,597
QCommandLineParser --help and --help-all options are not translated
I have got this result when using https://doc.qt.io/qt-5/qcommandlineparser.html#addHelpOption: Использование: ./build/Debug/client/myapp [параметры] Параметры: -h, --help Displays help on commandline options. --help-all Displays help including Qt specific options. -v, --version Отобразить информацию о версии. As one can see, the help entries are not traslated. I tried to find a more full qt_ru.qm file or a qt_ru.ts file, but failed. How can be this fixed? Any ideas, please? UPDATE (THE SOLUTION) For those who are interested. I was inspired by the answer of user HiFile.app - best file manager below. I have not found qt_ru.ts. Instead, in my OWN myapp_ru.ts file I added the text below, and suddenly it turned out to be enough to translate the --help and --help-all entries: <context> <name>QCommandLineParser</name> <message> <source>Displays help on commandline options.</source> <translation>Вывод справки по параметрам командной строки.</translation> </message> <message> <source>Displays help including Qt specific options.</source> <translation>Вывод справки с особыми параметрами Qt.</translation> </message> </context>
The translation files (*.ts) are in Qt sources, so you need to install Qt framework with source files. The text you are referring to can be found in Src/qttranslations/translations/qtbase_ru.ts. It depends on the Qt version which you are using, but AFAIK it seems to be translated in the latest Qt 6.4. If it is not translated in your Qt version, you can update the *.ts file yourself and convert it to *.qm using Qt Linguist application.