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
72,882,694
72,901,511
How to pass [[Int]] into MTLBuffer in Swift and receive it in Metal?
What I'm trying to do I have an [[Int]] in Swift and I'm trying to pass it into Metal through a buffer. Basically, I'm trying to use Metal to add two matrices multithreaded and give them back to Swift. So far, this is more difficult than expected. The problem Metal tells me that my graph isn't a pointer and I suspect I...
I don't know about the Swift implementation but your kernel function is wrong. If you want to write to and read from the same buffer you should use Device address space attribute. The device address space name refers to buffer memory objects allocated from the device memory pool that are both readable and writeable. ...
72,882,815
72,882,884
How to remove the end space in this for loop in c++/cpp?
int n; cin >> n; cin.ignore(); for(int i = 1; i < 11; i++){ cout << i * n << " ";// stop printing space at the end number } Desired output-> "1 2 3 4 5 6 7 8 9 10"
A simple approach is the following for( int i = 0; i < 10; i++){ if ( i ) cout << ' '; cout << ( i + 1 ) * n; } or for( int i = 1; i < 11; i++){ if ( i != 1 ) cout << ' '; cout << i * n; }
72,884,093
72,910,535
Fold expression: Replacing specific type but forwarding all others, how to correctly specialise `std::forward`?
I've trying to replace a specific type within a fold expression while simply forwarding all other types, but failed miserably. A simulation of std::forward; actually copied GCC's implementation of and just added a bit of output to see what's going on: namespace test { template<typename T> T&& fw(typename std::remove_r...
To be noted in advance: This attempt is entirely illegal since C++ 20 and illegal for the given use case (replacing std::string) as well as template specialisations for standard types have been illegal even before C++20 (thanks @Nimrod for the hint and reference to the standard). Note, too, that even for custom types (...
72,884,111
72,885,119
Fold expression: Replacing specific type but forwarding all others: How to achieve this?
I've trying to replace a specific type within a fold expression while simply forwarding all other types, but failed miserably. As std::forward requires explicit template specialisation I tried providing another set of templated overloads for, but these haven't been considered for overload resolution and would, if that ...
if constexpr within a wrapper is the key to the solution (thanks @user17732522 for the hint), however it needs to be combined with a second std::forward and for not receiving only r-value[s| references] decltype(auto) as well. Such a function can even be included within the Test class, additionally desired but optional...
72,884,815
72,889,919
How to stream frames from OpenCV C++ code to Video4Linux or ffmpeg?
I am experimenting with OpenCV to process frames from a video stream. The goal is to fetch a frame from a stream, process it and then put the processed frame to a new / fresh stream. I have been able to successfully read streams using OpenCV video capture functionality. But do not know how I can create an output stream...
We may use the same technique as in my following Python code sample. Execute FFmpeg as sub-process, open stdin pipe for writing FILE *pipeout = popen(ffmpeg_cmd.c_str(), "w") Write frame.data to stdin pipe of FFmpeg sub-process (in a loop) fwrite(frame.data, 1, width*height*3, pipeout); Close the pipe at the end...
72,885,072
72,885,790
How conversion of pointer-to-base to void is better than pointer-to-derived to void conversion
[over.ics.rank]/4: [..] (4.3) If class B is derived directly or indirectly from class A, conversion of B* to A* is better than conversion of B* to void*, and conversion of A* to void* is better than conversion of B* to void*. So if I have: struct A {}; struct M : A {}; struct B : M {}; void f(A*); void f(void*); ...
The situation where you have to compare different possible source types (A* vs B* in A* -> void* and B* -> void*) can only happen in the context of overload resolution for initialization by user-defined conversion, not in the context of overload resolution for a function call. See also the note at the end of [over.ics....
72,885,134
72,897,111
Pybind11 pointer reference
I'm trying to use a c++ function, that takes a pointer as an argument, in python. For the facade I'm using pybind11 and ctypes in python in order to create pointers. However the adress I'm getting in python isn't equal to the one in c++. I do need the adress of a variable later in the project and i cant get it by retur...
I was able to fix the Issue. It was just an error in my thinking process. Pybind now looks like this m.def("myFunc", [](double value) { void *pointer; otherValue = myFunc(&pointer, value); return std::make_tuple(pointer, otherValue); }, "funtion to test stuff out"); Note that th...
72,887,122
72,888,146
Can't send Message from Server( C++ Socket)
I'm new to C++ Socket and my Server can't send message to its client. The send() function return -1 always and it seems to have a problem with accpSocket. However Client can do that smoothly and I don't know what's wrong. Please help me thank you so much! Server #include<WinSock2.h> #include<WS2tcpip.h> #include<iostre...
int bytesend = send(acceptSocket, sendMess, 2000, 0); is not sending to a connected socket. acceptSocket was defined at the top of main and then ignored up until the call to send As a general rule of thumb, keep variable definition close to first use. In the server at SOCKET serverSocket, acceptSocket = INVALID_SOCKET...
72,887,333
72,987,279
Detect that a struct contains a flexible array member
Say that I have a struct like this struct foo { int n; int values[]; }; Is it possible to detect the flexible array member using SFINAE? At least, I can construct a class template that cannot be instantiated with such struct: template<class T> struct invalid_with_fam { T x; int unused; }; If I try to ...
There are no FAMs in C++. Any support given by the compilers to this non-standard feature is likely to be inconsistent and not integrate well with the rest of C++. Having said that, we can pretend that a FAM is normal C++ code and try to detect it using SFINAE. Unfortunately it doesn't work, because only errors in so-c...
72,887,465
72,901,012
SCons: ld cannot find standard libraries
I'm developing a game with raylib using SCons for building. I'm using Clang to cross compile from Ubuntu (in WSL) to Windows. My project directory contains a lib directory with the raylib binaries and an include directory with the raylib headers. When I run SCons I get this output: scons: Reading SConscript files ... s...
I found the answer to my problem. According the this by default SCons doesn't use the shell's PATH. The user needs to add it to the environment. My fixed SConstruct file: import os LIBS=['raylib', 'opengl32', 'gdi32', 'winmm'] LIBPATH='./lib' CCFLAGS='-static --target=x86_64-w64-windows-gnu' LINKFLAGS = '-mwindows --t...
72,887,668
72,887,857
Unable to find error in Leetcode 733.Flood Fill
I am getting the error below for this question in Leetcode, but I am unable to spot the error. Question: https://leetcode.com/problems/flood-fill/ class Solution { public: int visited[50][50]={0}; vector<vector<int>> helper(vector<vector<int>>& image, int sr, int sc, int color, int c) { int n = image...
In your code, sr represents the current row and sc represents the current column. Therefore, this line of code: image[sc][sr] = color; should instead be changed to: image[sr][sc] = color;
72,887,855
72,888,100
boost::typeindex::type_id<>().pretty_name() differences for different systems/compilter/boost-versions?
I am trying to run a project where boost::typeindex::type_id<>().pretty_name() is used to transform the classname to a string, to register it in a factory. For example class A should transform to "A", class B to "B", etc. This is working in a Linux gcc environment by using boost::typeindex::type_id<A>().pretty_name(). ...
Boost’s docs state this library is just a wrapper for std::type_info which is purely implementation-dependent, notice how the example on cppreference corresponds to your case.
72,888,319
72,888,353
Heap corruption on deleting a pointer twice stored in different classes
Two classes A and B share pointer to a third class C and when either A or B are deleted they call delete C as well. Issue is not observed when only either of A or B is deleted. An exception is getting thrown in this scenario. I have specifically tried to set the class C pointer to NULL and have put in a NULL check to a...
A and B have separate copies of the pointer to C. So setting one classes copy of that pointer to NULL has no effect on the other pointer and you still get a double delete. You have basically four options Decide that one class 'owns' the pointer, that class will delete it and the other will not. The danger here is that...
72,888,329
72,888,869
Idiomatic way of handling const template arguments in function templates
For a framework project I'm working on, I provide an interface for users to access objects through a handle-like interface--i.e. they do not own the objects themselves, but they need to use them. The class the user cares about looks something like: template <typename T> class handle { public: using value_type = std::...
You can just write a member comparison: template <class T> struct handle { using value_type = std::remove_const_t<T>; using const_pointer = value_type const*; template <class U> friend struct handle; template <class U> // this can be same_as<T const, U const>, etc. requires std::eq...
72,888,330
72,890,344
Start a thread with a member function should pass a object or pointer or a reference?
I'm confused about starting a thread with a member function. I know I need to pass a class object as the second parameter. But someone passed the object to the thread(), and someone passed an address, and I had tried to pass a reference. Both of them are compiling OK. So I am confused about which one is correct. class ...
The thread constructor begins executing the thread according to the rules of std::invoke. So all 3 of the lines of code you show will do something. The first two lines (ref and pointer) are fine if you expect the lifetime of the object to be longer than the lifetime of the thread. As you can see from the link to std:...
72,888,504
72,888,572
C++ how to declare bitwise operators for different types of flags?
First, my flags set is an enum like this: typedef enum { F0 = 0, F1 = 1, F2 = 2, F3 = 4 } Flags1; In C I can do any bitwise operations on them, but not in C++. So I have the macro: #define BIT_FLAG_OPERATORS(flags)\ inline flags operator ~(flags a) { return static_cast<flags>(~static_cast<int>(a)); }\ ...
So the answer is that what you have already works. It's debatable whether it's a good idea to convert back to an enum, but if that's what you want, then there's nothing wrong with the code you show and it was just another bug, so you might consider deleting the question. Here's a slightly cleaner working example: #inc...
72,888,511
72,888,538
How to log FVector in unreal engine
FVector ActorLocation = GetActorLocation(); UE_LOG(LogTemp, Log, TEXT("Actor location: %f"), ActorLocation);
You can't log an FVector directly. You need to convert it to an FString and then use %s (not %f) and finally operator* for dereferencing. This should work UE_LOG(LogTemp, Log, TEXT("Actor location: %s"), *ActorLocation.ToString());
72,888,552
72,890,280
How can I share variable values between different classes in C++?
I've created a minimal example to share a variable between classes. In C# normally I do this by creating a public static class with a public static variable... then I can just access it from everywhere. Main.cpp #include <iostream> #include "TestClass.h" #include "Shared.h" int main(int argc, char* argv[]) { std::...
Note that in C++ you can define public static variables in classes, and they will pretty much do what you want. That said, use of namespaces here is almost irrelevant. It essentially means that there's a :: in the name of your variable (MyNamespace::MESSAGE), but you could alternatively call your variable MyNamespace_...
72,888,784
72,945,217
Optimizations around atomic load stores in C++
I have read about std::memory_order in C++ and understood partially. But I still had some doubts around it. Explanation on std::memory_order_acquire says that, no reads or writes in the current thread can be reordered before this load. Does that mean compiler and cpu is not allowed to move any instruction present belo...
Q1 Generally, yes. Any load or store that follows (in program order) an acquire load, must not become visible before it. Here is an example where it matters: #include <atomic> #include <thread> #include <iostream> std::atomic<int> x{0}; std::atomic<bool> finished{false}; int xval; bool good; void reader() { xval...
72,890,391
72,890,525
std::find/std::find_if for custom container c++
I'm trying to find an object with some attribute value in a custom container that contains an array of objects of another class. MyIterator<WindowWithTitleButton> WindowList::FindTitle(string title_find) { auto iter = std::find(this->begin(), this->end(), title_find); return iter; } "Title" is an attribute ...
In this: auto i = std::find_if(iter = begin(), iter = end(), ContainsTitle((*iter).GetTitle(),title_find)); You've made a few mistakes: The iterators should be sent in by value: std::find_if(begin(),end(), ... The UnaryPredicate functor should have the signature bool(const YourWindowsClass&) - ...
72,891,033
72,893,137
Rewrite CListBox as a CCheckListBox
I am working on a Windows application using MFC and Visual Studio C++ 17. I have multiple tabs in the application, one of which is currently implemented using CListBox and needs to be reimplemented using CCheckListBox. CCheckListBox is a child class of CListBox. I have a vector of unique CString's I want to display in ...
There is no assertion in line 588 of the source file in your link. That github upload dates back to 2014. Why not search the winctrl3.cpp source file in your own Visual Studio installation instead? In my own installation, it is in function PreSubclassWindow() and there is indeed an assertion there: // CCheckListBox...
72,891,552
72,892,221
why I cant send and recv integers in a loop correctly
I have the following code in my server program: void sendAccounts(const Database& data, int socket, int32_t user) { std::vector<int32_t> accounts = data.getUsersAccounts(user); uint16_t number = accounts.size(); number = htons(number); send(socket, reinterpret_cast<char*>(&number), sizeof(number), 0); fo...
In the recv() loop, you are casting the value of account, which is always 0, thus producing a null pointer. This is the main reason why recv() is failing. You need to instead cast the address of account (just as you did with n_accounts above the loop). So, change this: reinterpret_cast<char*>(account) To this: reinterp...
72,891,751
72,905,747
How to create an asio socket with an existing fd and callback into custom code rather than read from it when data is available
I have a C++ application where I'm using a 3rd Party api. As part of that api they will handle the socket connections etc, however, they have a mode where I can select / poll on the fd and then call into the api read from the socket, decode the data and dispatch to the proper handlers; this way we can control the threa...
I found what I needed, asio::posix::stream_descriptor. I can assign it the socket handle (fd) and then call async_wait and asio will notify me when there is data to be read: descriptor_.assign(connection_.get_socket_handle()); descriptor_.async_wait(asio::posix::stream_descriptor::wait_read, [this] (const std::...
72,892,205
72,892,217
Error while finding the running sum of an array in C++ using vectors
Why am i getting this error, while finding the running sum of an array in c++? Line 1034: Char 34: runtime error: addition of unsigned offset to 0x6020000000b0 overflowed to 0x6020000000ac (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c...
nums[0]=temp[0] is incorrect, since temp[0] is 0 currently. It should be the other way around. Also, the lower bound for the for loop should be i=1. class Solution { public: vector<int> runningSum(vector<int>& nums) { vector<int> temp(nums.size()); temp[0] = nums[0]; for(int i=1;i<nums.size();...
72,892,740
72,893,063
How is the value of MediaDeviceInfo.deviceId calculated in Webrtc?
I am wondering how is the value of MediaDeviceInfo.deviceId calculated in Webrtc? MediaDeviceInfo.deviceId is a property used in web APIs of Webrtc. I have found a document MediaDeviceInfo, but still cannot get the answer. Is it directly from the uuid of the connected Media Devices? I guess there may be some calculatio...
You can find the Chrome implementation here: https://source.chromium.org/chromium/chromium/src/+/main:content/browser/renderer_host/media/media_stream_manager.cc;l=1653;drc=917850e016efe08e27c61eaa03e6fc27200e5be1 It is a hmac of the device id with a per-origin salt that has the same lifetime as cookies (for privacy re...
72,894,063
72,894,282
How to convert Hex in string format to Hex format
So i have a code that converts binary input to hex in string format: #include <cstring> #include <iostream> #include <string> using namespace std; int main() { string binary[16] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", ...
To parse the input, the standard std::stoul allows to set the base as parameter. For base 2: unsigned long input = std::stoul(str, nullptr, 2); Than you can print it as hex using either std::cout << std::hex << input << '\n'; or std::printf("%lx\n", input); See https://godbolt.org/z/5j45W9EG6.
72,895,618
72,895,949
incorrect function call on overload operator
In the code, why is (10 != i) calling == instead of !=? The other two call != #include <iostream> class Integer { int x; public: bool operator== (const Integer &i) { std::cout << "=="; return x == i.x; } bool operator!= (const Integer &i) { std::cout << "!="; return x != i.x; } Int...
There are two new additions to C++20 that made this possible (note that your code doesn't compile in earlier standard versions). Compiler will attempt to replace a != b with !(a == b) if there is no suitable != for these arguments. If there is no suitable a == b, compiler will attempt b == a as well. So, what happe...
72,896,537
72,896,677
c++ loop through a class private unique_ptr array from non-friend external utility function without using c-style for loop
I've got a class with: class vector_class { private: std::unique_ptr<int[]> my_vector; int size_; public: auto at(int) const -> int; // returns value at subscript auto at(int) -> int&; auto size() -> int; // returns vector size } I've been asked to construct an external function that takes 2 of th...
Iterators were designed to emulate much of the behavior of pointers, so much that all pointers can be used as iterators. So if you have an array, and the number of elements in the array, you can use a pointer to the first element of the array as the begin iterator. And a pointer to one element beyond the last element (...
72,896,672
72,897,768
Arduino: Why same library is included multiple times
I couldn't rationalize the reason that why (dependency) library is required when this very library has already been included in the required library itself. For example: If I want to use SD.h, in the example code, SPI.h is required: #include <SD.h> // SPI.h is already included in SD.h #include <SPI.h> // why inc...
Arduino doesn't have makefiles so the Arduino builder scans for #include directives to add the required libraries. Old version of the build system required to list all libraries in the main ino file. That is why the examples list all the main header files of the libraries used.
72,896,679
72,897,742
Does it risk if use c++ std::unordered_map like this?
Does it risk if use c++ std::unordered_map like this? std::unordered_map<std::string, std::unordered_set<std::shared_ptr<SomeType>>> _some_map; ... void init() { auto item = std::make_shared<SomeType>(); _some_map["circle"].insert(item); } _some_map is a member variable. init() function can ...
I'm not sure if I can use insert like this. Yes, you can, because operator[] Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist. Your value_type is std::unordered_set which is default constructible, so there is no problem. After in...
72,896,814
72,898,969
C++20 lambda capture variadic arguments with prvalue and non-copyable lvalue
I am trying to make a function that can stage arbitrary computation with lambda. This function takes in any function and parameter pack and stages the computation in a lambda function. A conflict occurs when Args contains both non-copyable lvalue reference and prvalue. The prvalue parameter will become dangling referen...
You can use a tuple to store args... and decide whether to store a value or a reference depending on whether the args... are lvalue or rvalue. Then use std::apply to forward parameters template <typename F, typename ... Args> auto f(F&& func, Args&& ... args) { // by value or by reference auto lamb = [func, args_tu...
72,896,973
72,899,963
Combinations of a variadic list of arbitrary types
I'd like to get a cartesian product of all the possible string-value pairs which are input in a variadic list of arguments and obtain a map M as, using M = std::unordered_map<std::string, boost::any>; template<typename ...Args> std::vector<M> combinations(const std::pair<std::string, std::vector<Args>> &...args) { // ....
I don't think it's necessary to use std::any/boost::any here since we can figure out the exact types. For example, m1 will be a: std::vector< std::tuple< std::pair<std::string, std::string>, std::pair<std::string, int> > >; Here's one way: In combinations I deduce the tuple type to store in t...
72,897,447
72,908,496
Crash on boost::posix_time::from_time_t when compile with -ftrapv
I use function ptime from_time_t(time_t t); and set t with big values like as UINT_MAX. When i use -ftrapv option - program crashes because happens signed overflow, without option - sometimes result is not correct(near 00:00, Jan 1 1970). I don't want to disable -ftrapv option. Question: Is it boost bug or from_time_t ...
I'm afraid there are undocumented "implicit" limits (preconditions) on the input to from_time_t: The input causes signed integer overflow: 9223372036854775807 * 1000000 cannot be represented in type 'long int' in boost/date_time/time_resolution_traits.hpp:153:47 (boost 1.79). In short if you need trapv you should proba...
72,898,090
72,908,088
float number to string converting implementation in STD
I faced with a curious issue. Look at this simple code: int main(int argc, char **argv) { char buf[1000]; snprintf_l(buf, sizeof(buf), _LIBCPP_GET_C_LOCALE, "%.17f", 0.123e30f); std::cout << "WTF?: " << buf << std::endl; } The output looks quire wired: 123000004117574256822262431744.00000000000000000 My q...
Finally I've found out what the difference between Java float -> decimal -> string convertation and c++ float -> string (decimal) convertation. I did not find the original source code, but I replicated the same code in Java to make it clear. I think the code explains everything: // the context size might be calcula...
72,898,205
72,902,694
clang-tidy-10 and compile_commands.json does not support relative paths
There are various posts about this - but I can't seem to find a definitive answer. Some people are saying it works and others not, and yet others saying its tools / IDEs that are the issue. So I made as small an example as I could. Here are the two files I have: compile_commands.json [ { "arguments": [ "gcc...
Short answer No, the directory in compile_commands.json cannot be relative. It must be absolute to work with clang-tidy. What the spec says The specification for compile_commands.json says: directory: The working directory of the compilation. All paths specified in the command or file fields must be either absolute ...
72,898,340
72,898,396
C++: Insert an element in a Vector without insert()
I have been trying to solve the above problem for a friend, everytime the last element of the vector gets removed although I feel that its size should increase dynamically after insertion. Here's the Code: #include <vector> #include <iostream> #include <algorithm> using namespace std; void display(vector<int> arr){ ...
You have two problems. The first is with the function signature: void indsert(vector<int> arr, ...) You pass the vector by value. That means a copy of the vector is made, and that copy is passed to the function. You can modify this copy as much as you want, but the original vector will still not change. You need to pa...
72,898,843
72,899,719
Adding new constructors to a specialised template class
I have a class defining an array of fixed length n, with some methods. template<int n> struct array_container{ /* some code here */ int array[n]; }; Let's say I want to add a constructor to array_container<3>, something along the lines of: array_container<3>::array_container(int a0, int a1 ,int a2){ array[...
Is there any approach that avoids both pitfalls? Ie. doesn't need to copy-paste the entire generic base code for the specialization, and doesn't add unnecessary constructors to the generic base? Ignoring the fact that, as @Goswin von Brederlow mentions, you seem to be reinventing the wheel (std::array and aggregate i...
72,899,549
72,922,555
how to set a value to list or text box using wxWidgets library
I've been struggling with converting the numbers on my buttons to the text box for my assignment. Basically what I'm trying to do is when a user presses for example when I click on 7 it should appear in the text box but currently in my Button Pressed method it only puts in a . instead of 7 and I'm not too familiar with...
You need to use wxTextCtrl::SetValue() (or ChangeValue(), which is very similar, but doesn't generate any events about the change in the text control) to change the value (not the label) of wxTextCtrl.
72,899,920
72,900,340
Inheritance and operator overloading
Hi I am new to c++ and had some conceptual questions that I wasn't able to find any direct answers to online. So if we have a parent class and multiple children classes and we want to create an overloaded input function for it. So do we create it for every child class or just for once for the parent class. Also do we h...
So, what @john said, basically, something like this (reduced to a minimal example): #include <iostream> class A { public: friend std::ostream &operator << (std::ostream &os, const A &a); private: virtual std::ostream& print (std::ostream &os) const { std::cout << m_x; return os; } int m_x = 42; }; class ...
72,900,175
72,901,482
Deduction of template arguments for friend function declared in class template
Consider the following example: #include <iostream> template <class T, int V> struct S { friend int Func(T) // decl-1 { return V; } }; struct U { friend int Func(U); // decl-2 }; template struct S<U, 42>; // spec-1 int main() { std::cout << Func(U{}) << std::endl; // Compiles and prints ...
what rule(s) in the standard allow the compiler to use the template parameters from the specialization spec-1 to instantiate the class template that contains decl-1. This is specified in temp.explicit-12 which states that: An explicit instantiation definition that names a class template specialization explicitly ins...
72,900,372
72,901,206
std::thread and ros::ok() do not work in ROS
I have a function that is executing by std::thread. I want it works until the user closes the terminal that running roscore by pressing Ctrl+C. Because of that I use this inside the thread: void publish_camera_on_topic(std::vector<Camera> cameras, const std::vector<ros::Publisher> publishers, const int camera_index) { ...
The problem is solved. The issue is ros::ok() does not check for ROS master. Instead of this line: while (ros::ok()) { //do sth} This line should be used: while (ros::ok() && ros::master::check()) { // do sth}
72,900,864
72,901,165
Deleting nodes recursively
I have created this function to recursively delete nodes from a doubly linked list. The issue here is that based on the call stack, it starts from the second so it does not delete the entire list. I can delete the remaining node from the method where I'm calling this but there should be a way around that. Is there a wa...
First: Don't use a leading _. You modify _curr in the function so by the time you end up at the delete the original pointer is gone. So don't do that, just call the function wiht the next value without modifying the local vbariable: RecursiveClear(_curr->next); You also shouldn't do a recursion like that because lists...
72,900,938
72,906,268
Failing Tictactoe in c++
I'm a beginner in c++, i'm trying to make a tictactoe. My program fails at the part acfter i enter input. When I enter an input, there is no next action from the program like i expected it to ("unvalid", check if win or loose, ask for input again). It only shows blank. like below: after I enter "1", nothing happens, an...
You have infinite loop at while (filled == false) { ... }, because filled_f always sets filled to false (and the else if branch of the condition inside this loop as well does so). It's because you most likely missed figure brackets when writing else if block in filled_f. Your indentation hints that you wanted 2 stateme...
72,900,977
72,906,771
Typecasting from one class to another isnot working
Conversion from SI to ImperialSystem is working but the reverse isnot working. The error message: static_cast: cannot convert from ImperialSystem to SI code: #include<iostream> #define endl '\n' using std::cout; #define MTRTOFEETRATIO 3.28084; /* Write two classes to store distances in meter-centimeter and feet-inch s...
Remove, operator float() { return mfeet + minch / 12.0; } from your SI class. This creates confusion in construction and casting in msvs and clang compiler.
72,901,268
73,047,016
COleDateTimeSpan dates difference returns incorrect value sometimes
I am using the following code to find the difference between two dates basically one is current system date and another server date. I am getting different values at different times, hence I changed the format to only include dates and not datetimes. But still the difference of values remains the same issue. Issue as m...
Hello I was able to solve it by getting the date, month and year separately from COleDateTime class and getting the difference manually. Thanks for all the help.
72,901,339
72,904,766
Is it possible to use a literal double if a given template type doesn't have a method that returns a double
Here's my problem, I have a class Foo() which holds two doubles, its value and an extra one: class Foo { public: Foo(double value, double extra) : value_(value), extra_(extra) { } operator double() const { return value_; } double extra() const { return extra_; ...
To me it sounds like you could do several things. Either Testing should not be a template and only have Foo members, so that you can use a converting constructor for Foo, Foo(double value, double extra = 1); to allow implicit conversion from a single double. Or, as you say, another Foo-like class whose extra() simply ...
72,901,652
72,901,803
Applying a function to a parameter pack
I'm playing around with parameter packs, and I'm trying to apply a mapping via a lambda function which adds 1 to each member of the parameter pack as shown. However, I get the output 4 while 234 is expected. #include <iostream> // method to print a variadic list of arguments template<typename... Args> void print(const...
You can't return a parameter pack. The closest thing is std::tuple. Something like this: template<typename F, typename ...Args> auto mapping(F f, Args &&... args) { // Note `{...}` instead of `(...)`, forcing the call order of `f`. return std::tuple{f(std::forward<Args>(args))...}; } You'll need to modify your...
72,901,883
72,913,274
why is linking to libOpenCL.dylib failing with undefined symbol
I am trying to build the pocl library on MacOS System: MBP 16" 2019 Intel i9, AMD Radeon 5500m Mac OS 12.4 using bash, instead of zsh llvm from home-brew, -version 14 I have the following in my .bash_profile to setup the build environment export PATH=/usr/local/opt/llvm/bin:$PATH export CC=clang export CMAKE_C_COMPILE...
The meaning of the lower case t is that the symbols are local, i.e. not externally visible to linking programs. Upper case T would be externally visible. POCL has a number of configuration options, not all of which are documented in the Build section of the docs. The VISIBILITY_HIDDEN option is on by default unless th...
72,902,751
72,905,144
Is it defined behavior to explicitly call a destructor and then use placement new to reconstruct it?
This is very similar to Correct usage of placement-new and explicit destructor call but tighter in scope: If I have a type, S, for which std::is_nothrow_default_constructible_v<S> and std::is_nothrow_destructible_v<S> and not std::has_virtual_destructor_v<S> and not std::is_polymorphic_v<S>, is it defined behavior to c...
Unfortunately, sometimes it is defined behavior, and other times you have to run the pointer through std::launder. There are a number of cases where the compiler may assume that the object hasn't changed, particularly if there are references or const fields in struct S. More information is available in the cppreferen...
72,903,031
72,903,364
PI Approximation not approximating right
i just started on C++ and i tried to convert my working PI approximation JS code to C++ But when compiling my C++ it doesn't approximate correctly... I think it's because i'm not using double variables at the right way. Here's my code: #include <iostream> using namespace std; double four = 4, pi = 4, num = 1; bool le...
It looks like you're implementing the approximation π = 4 – 4/3 + 4/5 – 4/7 + 4/9 – … In that case, the line pi = (four/num) - pi; is backwards. It should be pi = pi - (four/num);, which represents the subtraction terms. Also, subtraction from the initial value of 4 should be the first operation, so the lever flag sho...
72,903,637
72,903,675
check string equal with regex
I have a simple question. How would i check if my string equals another string if that string has changing numbers at the end. Random:1 Random (1):1 Random (2):1 Random (3):1 Random (4):1 So on... and also with a string like this Random Random_1 Random_2 Random_3 Random_4 So on...
You need std::regex_match and std::regex from <regex>: #include <regex> bool match(const char* cstr) { static auto re = std::regex("Random \\([0-9]*\\):1"); // or whatever regex you'd like return std::regex_match(cstr, re); }
72,903,966
72,903,990
My C++ code seems to stop in the middle of a for loop
I've been practicing USACO questions and I solved the problem but my code just randomly stops executing in the second for loop. Code: #include <vector> #include <string> using namespace std; int main() { int R = 0; int C = 0; cin >> R >> C; vector<vector<char>> values; string temp; for (int i = ...
When i equals zero then values[i-1][j] is an out of bounds access on your vector. When i equals R-1 then values[i+1][j] is an out of bounds access on your vector. Similar errors exist for j.
72,904,426
72,913,967
Moving objects can change the order destructors are called. Why isn't that a problem?
In the following example, a mutex is used to protect a file: #include <fstream> #include <memory> #include <mutex> std::mutex m; int main() { std::unique_ptr<std::lock_guard<std::mutex>> ptr_1 = std::make_unique<std::lock_guard<std::mutex>>(m); std::fstream file_1("file_name.txt"); std::unique_ptr<std::lo...
There are two guidelines/best practices that I see are violated here. The first is enshrined in the C++ Core Guidelines as R.5: Prefer scoped objects, don’t heap-allocate unnecessarily Using heap allocation removes the structure afforded by the lexical scoping rules in C++. It is effectively an assertion that the pro...
72,904,457
72,904,537
How in multimap run for range from to?
I need to go from the beginning +3 and from the end -3 that is, if the total size is 10, then I have to iterate from 3 to 7 who it doesnt work? std::multimap<int,int> _multimap; for(auto it = _multimap.begin() + 3; it != _multimap.end() - 3; it++) { std::cout << it->first; }
The problem is that the class template std::multimap does not have random access iterators. It has bidirectional iterators. So you may not write _multimap.begin() + 3 or _multimap.end() - 3 Instead you could write the for loop the following way using standard function std::next and std::prev #include <iterator> //....
72,904,485
72,904,555
Improve the execution time of a function which manage std::map objects, how?
I have a header file header.hpp in which is declared this function: #ifndef COMMON_HPP #define COMMON_HPP #include <string> #include <map> extern std::string func( const std::map <std::string, std::string>& generic_map, const std::string& feat_string ) #endif and that function is defined in a .cpp file: #include "h...
Given how small the code is, there is really not many changes you can make to it, but there are a few: use the iterator that map::find() returns, you don't need to call map::at() afterwards. You are actually performing the same search 2 times, when you really want to perform it only 1 time. return a reference to the...
72,904,549
72,909,549
How to use C++ struct array for QML ComboBox?
I've got a struct with two fields, for example: struct testStruct { Q_GADGET Q_PROPERTY(QString text MEMBER m_text); Q_PROPERTY(QString value MEMBER m_value); public: QString m_text; QString m_value; }; There is a QList<testStruct> m_testStructs member of my "AppEngine" class exposed to QML via Q_PROPERTY(Q...
As I checked in the main.qml model property cant find and understand as you show it is undefined. qml: currentIndex: 0; currentText: ; currentValue: undefined qml: currentIndex: 1; currentText: ; currentValue: undefined from ListView::model property The model provides the set of data that is used to create the item...
72,904,666
72,904,947
Transmit data to an adress stm32CubeIde
I am newly working on Stm32CubeIde and I am trying to understand how it works. I would like to transmit data to a specific address using the UART port and I don't know how to do it. So far I have been able to transmit using these three methods: using the poll —> HAL_UART_Transmit using the interrupt —> HAL_UART_Transmi...
The UART hardware will transmit a series of high a low voltages onto the wire. RS232 and RS422 are full duplex so there is only a single receiver. RS485 is half duplex so there can be multiple receivers listening to the same data. How that data is framed including which receiver the data is for depends on the higher le...
72,904,741
72,905,097
Can I make separate definitions of function template members of a class template?
Here's a minimal code example to show what I'm attempting that works, but not how I'd like it to: #include <string> #include <type_traits> #include <iostream> struct string_tag { using R=const std::string; }; struct int_tag { using R=const int; }; template <bool TS> class Wibble { public: template<typ...
I gave it a thought, read language specs etc. and the following things come to my mind: Class template has to be specialized in order to specialize member function template. Period. This cannot be overcome with concepts, or at least I haven't found a way. I guess you don't want to replicate the code for each case of T...
72,905,028
72,905,107
Is there a way to have a C or C++ program open a new terminal window and start executing code for you?
I want to create a C or C++ program that automates some things for me. The idea is as such: I run the program ./a.out and sit back and watch as it opens up three or four new terminal windows and runs various UNIX commands. Is there a way to do this? I am on a MacBook.
As the comments point out, this is probably best accomplished by a shell script. However, you can execute shell commands from C with the system(3) standard library function. To open a terminal, just run a terminal with a particular command. For example: system("xterm -e 'echo hello; sleep 5'");
72,905,471
72,905,654
Why is my console not showing up when my Dll is loaded?
I have two files, the file which I'll use to load the Dll into the process is the following: #include <Windows.h> int main() { // path to our dll LPCSTR DllPath = any_path; // Open a handle to target process HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 26188); // Allocate memory for t...
One issue I see is that your thread is re-mapping only stdout to the new console, but it is not re-mapping stdin as well. So it is quite likely (use a debugger to verify this) that std::cin.get() is failing and thus not blocking the thread from closing the console immediately after creating it.
72,905,675
72,906,198
Macros not expanding properly
I have these macros defined: #define AL_ASSERT_NO_MSG(x) if (!(x)) { assertDialog(__LINE__, __FILE__); __debugbreak(); } #define AL_ASSERT_MSG(x, msg) if (!(x)) { assertDialog(msg, __LINE__, __FILE__); __debugbreak(); } #define GET_MACRO(_1, _2, NAME, ...) NAME #define AL_ASSERT(...) GET_MACRO(__VA_ARGS__, AL_ASSERT_M...
It seems that MSVC does not expand __VA_ARGS__ into multiple arguments (see this related question: MSVC doesn't expand __VA_ARGS__ correctly) This seems to work: #define GET_MACRO(_1, _2, NAME, ...) NAME #define XGET_MACRO(args) GET_MACRO args #define AL_ASSERT(...) XGET_MACRO((__VA_ARGS__, AL_ASSERT_MSG, AL_ASSERT_NO_...
72,905,721
72,906,890
Is there a good way to make vscode intellisense detect g++ gcm files generated from -xc++-system-header flag for importing?
I'm trying to dabble with the c++20 modules feature and would like to import the standard library headers as modules. Currently I have import <iostream>; int main() { std::cout << "hello world!" << std::endl; return 0; } and I run the commands g++-11 -fmodules-ts -std=c++20 -xc++-system-header iostream g++-11...
This is the known IntelliSense issue. When importing C++20 modules or header units in C++ source: You may not see IntelliSense completions or colorization. You may see red squiggles that don’t match the compiler. Status (as of June 2022) Workaround #if __INTELLISENSE__ #include <iostream> #else import <iostream>; #...
72,906,106
72,909,435
Can somebody explain the mathematics of this Color Balance formula?
I have found a good example of a Color Balance implementation here and was wondering if someone could explain the derivation of these formula's: float DR=(1-cr_val)*R1+(cr_val)*R2-0.5; float DG=(1-cr_val)*G1+(cr_val)*G2-0.5; float DB=(1-cr_val)*B1+(cr_val)*B2-0.5; The full code is here: #include <iostream> #include <v...
This is just a linear interpolation between C1(R1, G1, B1) and C2(R2, G2, B2). If you imagine C1 and C2 as points in 3D space, c_val lets you choose a point on the line that goes from C1 to C2. 0 is on C1 1 is on C2 anything in (0,1) is on the line segment between (C1, C2) anything below 0 or above 1 is extrapolated. ...
72,907,198
72,907,522
Logfile game from array to file text is not writing anything c++
I developed a game and everything went well except I want to make a logfile (means data from array to text file) but nothing is coming out for the array. My code: void writeToFile(ofstream &outputfile, string name, string s2, string s3, string s4, string s5) { outputfile << "HI" << endl; outputfile << e...
Look at what your code actually does Allocate arrays of empty strings string *name; name= new string[count]; string *s2; s2= new string[count]; string *s3; s3= new string[count]; string *s4 ; s4 = new string[count]; string *s5 ; s5 = new string[count]; string *s6 ; s6 = new string[count]; Call a function wit...
72,907,714
72,911,288
How can I silence all errors of a particular kind in clang-tidy?
I'm currently working on a university assignment where it is mandated that we use C-style arrays for our code. Infuriatingly, they have left the default setting for warning about C-style arrays, which means that every time I use a one I need to add a // NOLINTNEXTLINT(modernize-avoid-c-arrays), which is absolutely terr...
Disable a check To disable a check in .clang-tidy, add a Checks: line, and as its value put the name of the check, preceded by a hyphen (meaning to disable rather than enable). For example, here is a complete .clang-tidy file that first enables all of the modernize-* checks (since they are not enabled by default), the...
72,907,820
72,911,697
passing null structure pointer ctypes
I am writing a Python wrapper for cpp APIs in that for one API I am trying to pass a NULL structure pointer as a parameter. Not sure how we can achieve that in Python. Below is my sample implementation: cpp_header.hpp typedef enum { E_FLAG_ON = 0, E_FLAG_OFF } option; typedef struct { float *a; float b...
Use None to pass a null pointer: so_lib.op_init(None) To send the actual structure instantiate one and send it. Best to define .argtypes and restype as well so ctypes doesn't have to guess and can perform better error checking: so_lib.op_init.argtypes = POINTER(inputs), so_lib.op_init.restype = c_int arg = inputs() ...
72,908,252
72,908,275
C++ create chain using struct cause circular reference. nextNode refer to the same address and value
The first call of appendChild work as expected, but then the next point to itself. need an example how to do it. why LinkNode nextNode; not create a new instance zsbd zsbd zsbd zsbd zsbd zsbd #include "iostream" using namespace std; template<typename T> struct LinkNode { T data; bool hasNext = false; Link...
LinkNode<T> nextNode; This is a local variable. It is destroyed when it goes out of scope. Thus ptr->next = &nextNode; will add the address of a local variable. Accessing it's address is Undefined Behavior. edit: a modern solution would be to use std::unique_ptr (we don't use new anymore). E.g. #include <iostream> #inc...
72,908,385
72,908,687
Lifetime of lambda c++
I have the following situations and trying to understand the scope of the lambdas std::future<void> thread_run; void run(Someclass& dbserver){ thread_run = std::async(std::launch::async, [&]{ dbserver.m_com.run([&dbserver]() { // implement another nested lambda fo...
Create the dbserver before the future and let the future go out of scope before dbserver and you are fine (the future destructor will synchronize with the end of the thread) . If you somehow cannot manage that you may need to use a std::shared_ptr<Someclass> and pass that by value to your lambda to extend the lifetime ...
72,908,482
72,909,224
C++11 Move heap array into std::string
Looking around other answers on stackoverflow the answer may just be a no, but please humor me before marking it a duplicate. So I want to be able for format a string snprintf style as shown below, but only make a single heap allocation. Lots of examples say to touch the std::String::data() or std::String::c_str() but ...
The comments in your question are correctly directing you to instantiate a string with a specific size and use the .data() or &[0] operator to get what you need. Let me suggest a simpler solution with a constraint. Consider that your output strings have some reasonable length and that you have plenty of stack memory to...
72,909,233
72,911,178
Error: invalid use of incomplete type 'class Move' / undefined reference to Move::NONE
Please, I don't know why this simple code is rejected. It give me 2 compilation errors. Help me please. I use Code::Blocks 20.03 My compiler is GNU GCC ---move.hpp--- class Move { public: Move(); Move(int, int); public: int from; int to; const static Move NONE = M...
You should provide an out-of-class definition for the static data member NONE in the source file(like move.cpp) which will work because at that point the class is complete as shown below: move.hpp #pragma once class Move { public: Move(); Move(int, int); public: int from; int ...
72,909,258
72,909,955
switch in switch, does the outer case break if inner case break
In languages that have switch, usually a break; statement is needed. What if a switch within a switch statement? Is it necessary to put a break; statement in the outer switch when the inner switch has a break;? e.g.: // outer switch switch (a) { case 1: // inner switch switch (b) { // this inner swi...
Both break statements are useful. This gives the language greater flexibility, and it keeps the language itself simpler to work with. You seem to be thinking of a simple situation, where the nested switch is choosing which one thing to do. This is often a good design. However, what if more needs to be done? There might...
72,909,458
72,909,642
Error subtracting hex constant when it ends in an 'E'
int main() { 0xD-0; // Fine 0xE-0; // Fails } This second line fails to compile on both clang and gcc. Any other hex constant ending is ok (0-9, A-D, F). Error: <source>:4:5: error: unable to find numeric literal operator 'operator""-0' 4 | 0xE-0; | ^~~~~ I have a fix (adding a space after t...
Actually, this behaviour is mandated by the C++ standard (and documented), as strange as it may seem. This is because of how C++ compiles using Preprocessing Tokens (a.k.a pp-tokens). If we look closely at how the compiler generates a token for numbers: A preprocessing number is made up of a digit, optionally preceded...
72,909,703
72,910,361
How to compare two datetime structures in C++ efficiently?
I have the following DateTime structure: struct DateTime { std::uint16_t year; std::uint8_t month; std::uint8_t day; std::uint8_t hour; std::uint8_t minute; std::uint8_t second; std::uint16_t milisecond; }; My doubt is about the LessThan and GreaterThan methods. I have implemented as follow...
From all the comments, I think the best solution was proposed by – Richard Critten: bool GreaterThan(const DateTime& date_time) { return (std::tie(year, month, day, hour, minute, second, milisecond) > std::tie(date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.s...
72,910,739
72,911,538
Vulkan Storage Buffer Memory Mapping
I'm refactoring and re-writing the guide made by VkGuide as to fit my idea of an engine. I'm using VMA to handle my memory needs. I've stumbled upon a strange (?) issue in refactoring my memory mapping code into something more easily readable: Original code: Renderer fields //------------------------------------------...
Your usage example only ever sets the first SSBO in the buffer, as data is *t_pointer and never changes. Change your code to pass t_pointer directly, change the type of the callback and then you can use it as MemoryMapper::effect_mmap<ObjectData>(allocator, frame().object_buffer, [&](ObjectData* data) { for (auto& ...
72,910,829
72,911,415
Same template class specialization for std::variant and boost::variant template types
I want to create a class specialization that has the same implementation if it gets passed any std::variant or any boost::variant. I tried to play around with std::enable_if, std::disjunction and std::is_same but I couldn't make it compile. Here is a code sample to show what I want to achieve. #include <variant> #inclu...
You can use a template template parameter e.g. like this template <typename T> struct TypeChecker { void operator()() { std::cout << "I am other type\n"; } }; template<typename ... Ts, template<typename...> typename V> requires std::same_as<V<Ts...>, std::variant<Ts...>> || std::same_as<V<Ts.....
72,911,198
72,911,278
C++14 variadic function template expect 2 arguments - 0 provided
I'm currently working on a variadic function using template, however, I keep getting the same error: C2780: 'void print(T,Types...)': expects 2 arguments - 0 provided even if it is the simplest one: template <typename T, typename... Types> void print(T var1, Types... var2) { cout << var1 << endl; print(var2......
Your calls to print will be like this: print(1, 2, 3); print(2, 3); print(3); print(); Your template function needs at least one argument (var1), and there is no function that takes zero arguments. This can easily be solved by adding another function overload to handle the "no argument" case: void print() { // Do ...
72,911,809
72,913,313
How is this function returning the correct answer (trying to find the minimum value in a sorted and rotated array)?
I am trying to find the minimum element in an array that has been sorted and rotated (Edit: distinct elements). I wrote a function that uses binary search, splitting the array into smaller components and checking whether the "mid" value of the current component was either greater than the "high" value or lesser than th...
Short answer: Undefined behavior doesn't mean it can't give the right answer. <source>: In member function 'int Solution::minNumber(int*, int, int)': <source>:31:5: warning: control reaches end of non-void function [-Wreturn-type] When the array isn't rotated you hit that case and you are simply getting lucky. Some ni...
72,911,836
72,913,027
How do I fix error LNK2019: unresolved external symbol _glfwInit
I have the basic code from the vulkan tutorial. I'm not using Visual Studio and opted to just compile from the command line. cl lib/*.lib main.cpp /I include. I sort of assumed that the symbols would be resolved in the .lib files which seem to compile properly, but it doesn't link so what do I do? #define GLFW_INCLUDE_...
First I had to install the windows 10 SDK Then I had to change my vcvarsall in path to the VS2022 one Then I had to run the vcvarsall x64 Then I had to remove the glfw3.lib in favor of the glfw3_mt.lib Then I had to add the vulkan-1.lib to my lib/ directory And finally it compiled and showed a window
72,912,054
72,912,982
Why does MISRA C++ allow modifying parameters when MISRA C doesn't?
MISRA rule 17.8 prohibits modification of function parameters in the function body. The rationale is that programmers new to C may misinterpret the semantics of doing so. But in MISRA C++ it seem to be no corresponding rule. Apart from the objections to the practice of modifying parameters is equally valid in C++ there...
This rule wasn't present in MISRA C:2004 either, which is the C version most similar to MISRA C++:2008. MISRA C was updated and much improved in 2012 but MISRA C++ never went through such an update - it is actually getting reviewed and updated right now, but the next version is still a work in progress, yet to be publi...
72,912,782
72,914,470
Compare DayTime strings in C++
If I have a single string storing both Day and Time in the format "mm/dd-hh:mm" how can I create the string of two days ahead?
You can use Howard Hinnant's date library. First of all, fix the input string by adding something that could be parsed as a year, and not a leap year (e.g. "01/"), so that date::from_stream parses the date and time input string into a time point (tp1) correctly. Get the date two days ahead of tp1, that is, tp1 + days{...
72,913,047
72,913,927
Deselect edit control win32 c++
How would I go about deselecting the text in edit control? After entering the input I want the user to be able to deselect the edit control. Because even after you click out of it and press a key, it gets entered into the edit. Here is the code for my edit control: HFONT fontMain = CreateFont( -16, ...
You could use the same trick that works to dismiss dropdown list (of combo box), popup menus, and the like. You'll need to subclass the EDIT control so you receive messages first to your own window procedure. In your textbox subclass WM_SETFOCUS handler, call SetCapture so the next click is delivered to the textbox e...
72,913,138
72,916,944
Atomic wait memory_order
I don't completely understand why atomic wait needs a memory order parameter. It compares its own value, so the atomic value itself is synchronized anyway. I couldn't figure out an example where anything else than std::memory_order_relaxed makes sense. If I need additional logic based on the atomic variable I need to c...
If I need additional logic based on the atomic variable I need to call other functions Do you? Consider if T is a bool. It only has one of two states: true or false. If you wait until it is not true, then it must be false and no further atomic operations are needed. And that's just the case where T is a type that can...
72,913,745
73,313,271
VS Code takes several seconds to save a document in C++
This is my C/C++ configs in /home/user/.config/Code/User/settings.json: "C_Cpp.formatting": "clangFormat", "C_Cpp.default.intelliSenseMode": "linux-clang-x64", "C_Cpp.dimInactiveRegions": false, "C_Cpp.clang_format_path": "/usr/bin/clang-format", "C_Cpp.clang_format_sortIncludes": true, "C_Cpp.codeAnalysis....
In vscode, i tried to disable all the extensions that i installed previously, i disabled them one by one, after each disable, i test by changing the code then saving, yet the problem persists, until all the extensions are off. Then i remembered there are some other built-in extensions. I opened the extensions, then pre...
72,913,925
72,914,008
printf - raw string literal with format macro of fixed width integer types
How do I use raw string literal R with format macro of fixed width integer types? For example std::int64_t num = INT64_MAX; std::printf(R"("name":"%s", "number":"%")" PRId64, "david", num); // wrong syntax The output should be "name":"david", "number":"9223372036854775807" Use of escape sequences instead of R is not ...
Firstly, you should check your current format string with puts(). #include <cstdio> #include <cinttypes> int main(void) { std::puts(R"("name":"%s", "number":"%")" PRId64); return 0; } Result: "name":"%s", "number":"%"ld Now you see the errors: You have an extra " between % and ld. " is missing after ld. Ba...
72,913,964
72,914,076
libvips in C++ on Mac
I trying to write a program in CLion IDE that read a pdf file with C++ vips library and I get this error. What it's wrong? Undefined symbols for architecture x86_64: "vips::VImage::pdfload(char const*, vips::VOption*)", referenced from: _main in main.cpp.o "vips::VImage::write_to_file(char const*, vips::VOpti...
The missing libraries libvips-cpp to link to. # pkg_search_module(VIPS REQUIRED vips) pkg_search_module(VIPS REQUIRED vips-cpp) pkg_search_module(GLIB REQUIRED glib-2.0) can be removed, vips-cpp provides it in the libs $ pkg-config --libs vips-cpp -L/usr/local/lib -lvips-cpp -lvips -lgobject-2.0 -lglib-2.0
72,914,454
72,972,429
Default copy constructor and assignment operator
If among the elements of my class I have also a const data member, how do copy constructor and assignment operator behave? I think, but I am not sure, that copy constructor is provided (as most cases) while assignment operator is not provided (differently from what happens normally) and so if I want to use it, I must i...
struct foo { int const x; }; foo f0{3}; // legal foo f1 = f0; // legal, copy-construction foo make_foo(int y) { return {y}; } // legal, direct-initialization foo f2 = make_foo(3); // legal, elision and/or move-construction f2 = f1; // illegal, copy-assignment f2 = make_foo(3); // illegal, move-assignment Constru...
72,915,272
72,915,337
Unordered Map Performing Much Slower than Map
Say I am attempting to solve the two-sum problem. Below are two samples of the same algorithm, one using an ordered map, and one using an un-ordered map. Using unordered_map: class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> d; int indx {0}; ...
The unordered_map has to allocate and copy to grow over and over while the map just allocates nodes.
72,915,339
72,919,284
C++ permutation using std::list produces infinite loop
I'm trying to generate all permutations of a vector v using backtracking. The basic idea of my algorithm is: at each recursive step, iterate through the remaining elements of v, and pick one to add the resulting permutation. I then delete it from the vector v. I'm trying to speed up the deletion operation by using a st...
The problem is here: v.insert(it, d); You will need to insert the value d back where it was, but you are not doing it. list is not suitable for what you're trying to do. Use a vector, and instead of deleting, use swaps.
72,915,869
73,533,143
How to hook Java method with JNI during runtime?
Other questions I saw about this topic were not about while the Java program is running or were unclear to me, so I'm asking a separate question I'd like to know if there's a way to hook/override methods with JNI during runtime It would work as Mixins (like in Fabric API), which "injects" code at the beginning or at th...
Thank you all for the answers but I found exactly what I wanted (not sure if it's what everyone is looking for but this was my goal with this question) Basically I found out that jmethodIDs are pointers, which I thought of actually being the address of the method on the stack To check if this would work I debugged the ...
72,916,331
72,917,630
Undefined behavior when reading from FIFO
I am trying to send data from javascript to C via a named pipe/FIFO. Everything seems to be working other than every couple messages there will be an additional iteration of the loop reading 0 bytes rather than the expected 256. I realize I could add something like if (bytes_read>0) {... but this seems like a band aid ...
A reador 0 bytes indicates the pipe was closed on the other end. So this is absolutely expected behavior. So you do have to catch that 0 and read again so the kernel waits for the next time the pipe is opened. Note: read can also return -1 with errno set to EINTR. Same deal, just read again.
72,916,424
72,916,464
Why the output not show up according to my txt file?
Why can't I retrieve all of the data from a txt file using c++? This is the data in the txt file: Standard ;40 90 120 Delux ;70 150 200 VIP ;110 200 300 This is my coding: #include <iostream> #include <fstream> #include <string> #include <sstream> #include <bits/stdc++.h> #include <vector> using names...
Look at your input loop while (getline (ss, temp, ';')) { tokens[i] = temp; i++; } that reads tokens separated by semicolons. Look at you actual input Standard ;40 90 120 Only the first and second token are separated by a semicolon. The rest are separated by spaces. The simple thing ...
72,916,809
72,917,439
Better way to give constant view of pointers in C++
I have a class that must return a constant view of some pointers to the upper layers of software. Internally, the pointers must be non-const, because the class will need to manipulate the objects internally. I don't see any option for providing this const view of the pointers to a higher level client, without making a ...
As the OP has pointed out in one of the comments, this is the API the code needs to comply to: https://github.com/Xilinx/Vitis-AI/blob/master/src/Vitis-AI-Runtime/VART/vart/runner/include/vart/runner.hpp#L157 So by design it returns by copy, which is unavoidable really, thus what really can be done is this: #include <v...
72,917,382
73,053,491
Crypto++ generating AES key to a file
I generate key to a file using the following function std::filesystem::path create_key(std::filesystem::path folder_path) { CryptoPP::AutoSeededRandomPool prng; CryptoPP::byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; prng.GenerateBlock(key, sizeof(key)); std::cout << "Size of key : " << sizeof(key) << s...
This function is valid and works , No changes need to be added in my scenario.
72,917,672
72,919,189
type 'X' is not a direct type of 'Y' - but with std::conditional
I have a Base class, two classes inheriting from that base class (they are slightly different from each other) and a Last class which can either inherit from Derived1 or Derived2 based on a template. I use std::conditional to determine at compile time which DerivedX it should actually use: template< class > class Base;...
In your declaration of the base class: template< class T, class ...Args > class Last< T(Args...) > : public std::conditional< std::is_void<T>::value, Derived1< void(Args...) >, Derived2< T(Args...) > > { ... } You either need to say public std::conditional_t (where the _t is very important at the end), or ...
72,917,908
72,917,972
class template and member function template with requires
I have a template class called Speaker, with a template member function called speak. These both have a requires clause. How do I define the member function outside of the class in the same header file? // speaker.h #include <concepts> namespace prj { template <typename T> requires std::is_integral<T> str...
The rules for defining template members of class templates are the same in principle as they were since the early days of C++. You need the same template-head(s) grammar component(s), in the same order template <typename T> requires std::is_integral_v<T> template <typename U> requires std::is_integral_v<U> const void S...
72,917,993
72,918,986
Using consistent RNG with OpenMP
So I have a function, let's call it dostuff() in which it's beneficial for my application to sometimes parallelize within, or to do it multiple times and parallelize the whole thing. The function does not change though between both use cases. Note: object is large enough that it cannot viably be stored in a list, and ...
First of all you have to make sure that both function_that_accesses_rand and do_stuff are threadsafe. You do not have to duplicate your code if you use the if clause: #pragma omp parallel for if(!parallelize_within) To make sure that in function dostuff(i, randomized,...); i reflects the order of creation of randomi...
72,918,308
72,943,899
Unpacking system verilog packed struct in DPI-C call
I have a very complicated packed struct, C, with nested packed structs, A and B, in SystemVerilog: typedef struct packed { logic [31:0] ex1; logic [3:0] ex2; } A; typedef struct packed { logic ex3; A [7:0] ex4; } B; typedef struct packed { logic ex5 A [5:0]ex6; B ex7; } C; I need to s...
I came up with an example which allows you to use vpi calls to traverse fields of the structure. It is pure vpi example involved from a dpi function. You can use something similar. Here is verilog code typedef struct packed { logic [3:0] f1; logic f2; } s1_t; typedef struct packed { logic f3; s1_t s1; ...
72,918,431
72,918,521
Compile Time vs Run time speed
Why is getting a number of the Fibonacci sequence at compile-time using templates much faster than run-time using a recursive function? #include <iostream> using namespace std; template<unsigned long long int I> struct Fib { static const unsigned long long int val = Fib<I - 1>::val + Fib<I - 2>::val; }; template<...
A recursive function has all of its code executed at runtime (unless the compiler optimizes it). A template is typically faster at runtime because all of its code is executed by the compiler itself and only the result is stored in the final executable, so there is no code executed at runtime at all. So, this code: #inc...
72,918,848
72,918,876
How to get parent folder from path in C++
I am using C++ in linux and I want to extract the parent folder from a path in C++ 14. For example, I have the path likes /home/abc/fi.mp4 My expected output be abc. How can I do it in C++ This is that I did std::string getFolderName(const std::string &path) { size_t found = path.find_last_of("/\\"); string fo...
You probably want something like this: // Returns the path-string without the filename part std::string getFolderPath(const std::string &path) { const size_t found = path.find_last_of("/\\"); return (found == string::npos) ? path : path.substr(0, found); } // Returns only the filename part (after the last slash)...
72,919,866
72,919,994
Why doesn't _ui64tow_s work when _ui64tow does?
I wrote some code which uses the _ui64tow function, but I'd like to use _ui64tow_s, which is safer. Unfortunately, it seems I can't get it to work properly. Here's the original code: #define PERCENT_SHIFT 10000000 #define SHORTSTRLEN 32 TCHAR g_szZero[SHORTSTRLEN] = TEXT("0"); WCHAR* PerfGraph::Floa...
The _ui64tow_s function returns an error_t value which is zero on success (unlike the plain _ui64tow function, which returns a copy of the string pointer argument). So, when changing from using _ui64tow to using _ui64tow_s, you must check against zero for success, typically by adding the ! operator to the (returned val...