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,849,474
72,849,830
what is boost::geometry::correct doing in this case?
The following code generates the output I expect: MULTILINESTRING((5 5,4 4),(2 2,1 1)) However, if I remove the call to boost::geometry::correct() it returns the incorrect result: MULTILINESTRING((5 5,1 1)) Code below: #include <boost/geometry.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/ge...
boost::correct() is closing both the inner and outer polygons. That is, the following returns the expected output: namespace bg = boost::geometry; namespace bgm = boost::geometry::model; using point = bgm::point<double, 2, bg::cs::cartesian>; using polygon = bgm::polygon<point>; using polyline = bgm::linestring<point>...
72,849,505
72,849,639
Public Setters vs. Friend Class vs. Specific Constructor
I'm making a simple programming language, and have encountered the following problem: I have a Parser class which has methods that return derived classes of the Node struct. Currently all of the Parser class methods look something like this: DerivedNode Parser::ParseDerived() { DerivedNode node{}; node.Field1 ...
A class is supposed to hold an invariant. Unless all combination of all field values are correct, 2nd version is strongly discouraged; 3rd is recommended. It's also the way to go for immutable structures which help debugging and testing very much.
72,849,627
72,850,561
why does the code execute list in a wrong sequence?
I am trying to concatenate two lists based on array (in c++), empty the first over the second, and if the insertion failed (maximum size reached) it will keep each list as it was before insertion. therefor, the code works well, but the problem is that it execute the list in a wrong sequence like, the first list contain...
First some nagging: Stop lying. This is not a list. It's a vector. 0 is not a bool, use true/false if you are going to return a bool to say if something failed then actually check the return value don't use out parameters use exceptions, std::optional or std::expected for error handling with return values retrieve and...
72,849,632
72,849,787
How to find occurrences of a pair in a multimap
I have been trying to write a program that finds the occurrences of a pair in a multimap. So far I am thinking of using multimap::equal_range. For example, if my multimap is {(BO, MA), (CL, SC), (DA, TX), (FL, MI), (FL, MI), (MI, FL), (OR, FL)} and I search for all occurrences of (FL, MI) in the multimap, then my progr...
I suggest using a std::unordered_map<std::string, std::unordered_map<std::string, unsigned>> instead. You then get 2 fast lookups and the count without iterating. Example: #include <iostream> #include <iterator> #include <map> #include <unordered_map> int main(void) { // your original looks something like this: ...
72,849,733
72,849,856
boost asio with little endian
I am integrating a library that requires little endian for length. It's formatted with little endian and then a custom serialized object. How do I convert 4 byte char into a int? The little endian tells me the size of the serialized object to read. so if I receive "\x00\x00\x00H\x00" I would like to be able to get ...
For a simple solution you could do couple of tricks, Reverse with a cast: // #include <stdafx.h> #include <cassert> #include <iomanip> #include <iostream> #include <algorithm> #include <string> int main() { char buff[4] = {3,2,1,0}; std::cout << (*reinterpret_cast<int*>(&buff[0])) << "\n"; std::reverse(...
72,849,963
72,850,125
Why TIFFReadRGBAImage() throws an exception when raster is smaller than image?
I'm using libtiff to read Image data into an array. I have the following code std::vector <uint32>> image; uint32 width; uint32 height; TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height); uint32 npixels = width * height; ...
You just changed the number of elements in allocated buffer, but still try to read the image of original size, thus you get access violation since the buffer is overflown. To get the cropping you should pass correct width and height to TIFFReadRGBAImageOriented as well: uint32 nwidth = width - 100; uint32 nheight = hei...
72,850,153
72,850,246
Why is function call treated as instantiation when I cast in template arguments?
I've got the following code: template <bool condition> struct enable_if { }; template <> struct enable_if<true> { using type = bool; }; template <typename T> class is_callable { using Yes = char[1]; using No = char[2]; template <typename U> static Yes& filter(decltype(&U::operator())); template <type...
No, your understanding is not correct. Firstly, a name can't refer to both a class template and a function template. If that happens the program is ill-formed. (And defining both in the same scope is not allowed to begin with.) Secondly, is_callable<Lambda>() as template argument is not a function call to begin with. I...
72,850,570
72,850,606
Garbage value in an array where array length and input is defined
I am a beginner, and I am trying to learn C++. For now, all I am trying to do is input 3 numbers, and print them back. #include <iostream> using namespace std; int main(){ int n[2]; cout << "Enter three numbers" << endl; for (int j = 0; j <= 2; j++){ cin >> n[j]; } cout << "Debug " <<...
This for for (int j=0;j<=2;j++){ cin>>n[j]; } expects that the array has at least three elements with indices in the range [0, 2]. However you declared an array with two elements int n[2]; If you are going to input three elements then the array should be defined as int n[3];
72,850,876
72,850,951
Emplace with primitive types
Since in C++, primitive types destructors do nothing [Do Primitive Types in C++ have destructors?], is it safe to rely on the value of int a to be the same after a call to queue::emplace? Specifically, queue<int> q; int a = 5; q.emplace(a); // is a==5 here? Perhaps the first question would also answer this, though for...
The parameters in the shown code are all lvalues. For the emplaced primitive type, as is the case here: an lvalue that gets passed to emplace() does not get modified. If the container contains a class with a constructor, that emplace ends up invoking, for a "well-behaved" constructor the parameter won't get modified wh...
72,851,022
72,851,200
How to use BOOST_PP_SEQ_FOR_EACH for execting a function for each in the sequence?
I intend to use BOOST_PP_SEQ_FOR_EACH to run a function for all variables of a sequence: #include <iostream> #include <boost/preprocessor.hpp> #include <boost/preprocessor/seq/for_each.hpp> #define SEQ (w)(x)(y)(z) #define MACRO(r, data, elem) foo(#elem); using namespace std; void foo(string a) { cout << a << en...
BOOST_PP_SEQ_HEAD((a)(b)(c)) is a macro to get the head of a preprocessor sequence and would expand to a. But #elem prevents that macro from being expanded. Use BOOST_PP_STRINGIZE to expand the macro as well: #define MACRO(r, data, elem) foo(BOOST_PP_STRINGIZE(elem));
72,851,116
72,851,293
Is std::construct_at on const member safe?
I have a class Obj with a const member i: class Obj { const int i; ... }; But I need to set i to 0 in my move constructor. (Because if i isn't 0, the destructor will delete stuff, and since I moved the object, that will result in a double free) Is it safe to modify Obj::i in the move constructor like this? Obj...
A potentially-overlapping subobject is a base class subobject or a member marked with [[no_unique_address]]. Obj::i is not so 8.4 applies. If you take p1 and p2 to be the same object, other, then 8.5 probably applies (an object can transparently replace itself), except in that it doesn't apply recursively (e.g., Obj is...
72,852,384
72,854,033
Can I hide implementation details of this concept from the end user?
I have looked at several similar questions on SO. Maybe I am not grokking the solutions there. In those questions when the return type is auto or templated then separating declaration and definition in two different units causes a failure in compilation. This can be solved by explicitly declaring a concrete signature f...
The return type of a function is a static property, it can't change based on runtime data. If you can, lift UseCase to a template parameter, and use if constexpr to have exactly one active return for each instantiation. template<UseCase a> auto Engine::getInstance() { if constexpr (a == USECASE1) return Use...
72,852,555
72,865,359
How to validate properly ffmpeg pts/dts after demuxing/decoding?
How should I validate pts/dts after demuxing and then after decoding? For me it is significant to have valid pts all the time for days and possibly weeks of continuous streaming. After demuxing I check: dts <= pts prev_packet_dts < next_packet_pts I also discard packets with AV_NOPTS_VALUE and wait for packets with pr...
At libav support I was advised to not rely on decoder output. It is more solid to produce pts/dts for encoding/muxing manually and I should search for ffmpeg tools sources to proper implementation. I will search for this approach. For now I discard AVFrames only with AV_NOPTS_VALUE, and the rest of encoding/muxing work...
72,853,130
72,869,205
How I can combine log entries based on the second column?
So I have email.log file(limited example): 2021-04-30T23:55:00.127629 886715E6D6C9D4FB status=rejected 2021-04-30T23:55:00.791921 F8F63278A6A3AD87 from=<sarah.smith@example.com> 2021-04-30T23:55:01.470432 418512384DDDD2C6 from=<robert.rodriguez@example.com> 2021-04-30T23:55:01.697902 0D8760D4ADAB456D me...
I will write a quick answer, because comments discussion is getting too long. Assuming your operator>> is working correctly, you could easily combine your log entries using std::unordered_map (faster, but elements are not sorted) or std::map (slower, but your map entries will be sorted by sessionid). For a quick exampl...
72,853,651
72,853,992
Cant make addition of array, no match for call to '(std::string {aka std::basic_string<char>}) (std::string&, std::string&)'
I have function in array and cant make the addition of it in main function because it wont 'allow'? can someone help me? The error: 154 no match for call to '(std::string {aka std::basic_string}) (std::string&, std::string&)'. If anyone wants to see the full code, please head to https://github.com/infaddil/beyblade/blo...
First line of your main(): string player1_name, player2_name, beyblade_name, product_code, type, plus_mode, system; You defined string type,and your function is type too; Add :: before type like this cout << "Your mark is " << ::type(s4[randomnumber], s3[randomnumber]) << endl; or pick another name.
72,856,018
72,857,109
How can I parse a std::string (YYYY-MM-DD) into a COleDateTime object?
I have a COleDateTime object and I want to parse a date string in the format YYYY-MM-DD. The string variable, for example, is: std::string strDate = "2022-07-04"; COleDateTime allows me to use ParseDateTime to parse a string, but I see no way to tell it what format the components of the date string are. In C# I can do...
Based on the suggestion by @xMRi in the comments I have decided to use: CString strDutyMeetingDate = CString(tinyxml2::attribute_value(pDutyWeek, "Date").c_str()); int iDay{}, iMonth{}, iYear{}; if(_stscanf_s(strDutyMeetingDate, L"%d-%d-%d", &iYear, &iMonth, &iDay) == 3) { const auto datDutyMeetingDate = COleDateTi...
72,856,268
72,856,461
Unfamiliar C++ code with strange return types
I encountered some really strange c++ code that I have never seen before, even though I have a little bit of experience. I tryed searching for it but I had no luck. This is super strange and either im really stupid or this is some wizard magic code. My question is how can the GetHelixCenter have a bool return type but ...
The helixcenterpos array is passed as the second argument: Bool_t AliV0ReaderV1::GetHelixCenter(const AliExternalTrackParam *track,Double_t center[2]){ Here, center decays to a pointer to the first value of your original array. Hence center[0] = xpos + xpoint; center[1] = ypos + ypoint; write to that array. It sho...
72,856,569
72,856,606
Does const_cast waste extra memory?
Let's see the example first. #include <iostream> int main() { const int constant = 1; const int* const_p = &constant; int* modifier = const_cast<int*>(const_p); *modifier = 100; std::cout << "constant: " << constant << ", *const_p=" << *const_p; //Output: constant: 1, *const_p=100 return 0; ...
This *modifier = 100; is undefined. You cannot change the value of a const int. You can cast away constness but you cannot possibly modify something that is constant. A correct usage of the const cast would be for example: int not_constant = 1; // not const !! const int* const_p = &not_const...
72,857,296
72,857,671
Why my code is not working for problem (Marathon) Code forces
You are given four distinct integers a, b, c, d. Timur and three other people are running a marathon. The value a is the distance that Timur has run and b, c, d correspond to the distances the other three participants ran. Output the number of participants in front of Timur. Input The first line contains a single integ...
Try changing the else ifs to ifs and declaring the variable p inside the loop: #include <iostream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int p = 0; int a, b, c, d; cin >> a >> b >> c >> d; if (b > a) { p++; } i...
72,857,582
72,857,620
HelloWorld.exe (process 12192) exited with code 0 issue
I'm a beginner in learning C++ programming and just started to use IDE VS Community 2022. I've created the new project corresponding to tutorial and when i run it i get the messege in the console: C:\Users\??????\source\repos\HelloWorld\x64\Debug\HelloWorld.exe (process 12192) exited with code 0. The code is #include ...
This is a feature of the IDE you are using. Try to run your program using the command line prompt directly and the message will not be displayed.
72,857,889
72,858,254
different behaviour for filesystem::path(filePath).filename() between gcc7.3 and gcc9.3
I see different outputs when running this piece of code in gcc7.3 (using C++14) and gcc9.3 (using C++17): #include <iostream> #if (__cplusplus >= 201703L) #include <filesystem> namespace fs = std::filesystem; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #endif u...
<experimental/filesystem> implements the filesystem library according to the Filesystem TS (basically an experimental extension of C++14), while <filesystem> is the filesystem library part of C++17 (and later). The two are not identical specifications. The latter is based on the experience with the former, but as the f...
72,857,891
72,863,253
Create Internet shortcut using C++
I need to be able to create an Internet shortcut to a specific URL and always open it with Microsoft Edge. The only info that is out there seems to be [this page][1]. I'm not sure how to use this site, or look for an example on how to create an Internet shortcut with target path and URL. Any ideas? I did manage to fin...
MSDN provides example code for creating shortcuts with IShellLink. This is also referenced in answers on Stack Overflow, most notably this one: How to programmatically create a shortcut using Win32 For your requirement specifically, note that the IShellLink object provides a method SetArguments. You can use this to spe...
72,857,947
72,858,095
Combining static data structures
I am trying to come up with a good way to define data for a seven-segment display. Let's say that the display segments are named like this: -A- F B -G- E C -D- So to display a 1 you need to turn on B,C - and for 2 you need A,B,G,E,D. Furthermore, each line of the display is connected to an IO expander chip, and...
You are just missing a mapping from digits to the segments that should light up. Your current mapping is from digits to hardware addresses directly. Just don't do it all at once. Actually for a nice visual code, I'd suggest to internally rename the segments like this: -S0- S1 S2 -S3- S4 S5 -S6- In the following I...
72,858,061
72,893,623
Are I/O streams really thread-safe?
I wrote a program that writes random numbers to one file in the first thread, and another thread reads them from there and writes to another file those that are prime numbers. The third thread is needed to stop/start the work. I read that I/O threads are thread-safe. Since writing to a single shared resource is thread-...
Thanks to those who wrote about read-behind-write, now I know more. But that was not the problem. The main problem was that if it was a new file, when calling pFile.peek() in the is_empty function, we permanently set the file flag to eofbit. Thus, until the end of the program in.rdstate() == std::ios_base::eofbit. Fix:...
72,858,345
72,858,515
How to call non-const method when a const method with the same signature exists?
OpenCV's Mat class contains the following two methods: template<typename _Tp> inline _Tp* Mat::ptr(int y) { CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); return (_Tp*)(data + step.p[0] * y); } template<typename _Tp> inline const _Tp* Mat::ptr(int y) const { CV_DbgAsser...
Typically you don't "select" which function to call, but the compiler will call the right function for you. Consider this example: #include <iostream> struct foo { int bar() { return 1;}; int bar() const { return 2;} }; int main(){ const foo f; foo f2; std::cout << f.bar(); std::cout << f2.b...
72,858,434
72,858,713
Qt6: "Unable to read Memory" when pointing to a QLineEdit from a QFormLayout
I want to get the text from a QLineEdit, which is in a QFormLayout, to save it to a File. The saving works fine, but I am not able to get the text form the QLineEdit and when I look at it from the Debugger it says "Unable to read Memory". I can´t figure out how to correctly point to the QLineEdit, so that I can get the...
Replace settingsEdit = (QLineEdit*)formLayout->itemAt(i, QFormLayout::ItemRole::FieldRole); with settingsEdit = (QLineEdit*)(formLayout->itemAt(i, FormLayout::ItemRole::FieldRole)->widget()); Background: itemAt() returns a QLayoutItem*, so you need to call QWidget *QLayoutItem::widget() to get the widget.
72,858,660
72,862,882
How do I find the indices of elements in a vector which are also in another vector using RcppArmadillo?
I am stuck trying to find the indices of elements in a vector x whose elements are also in another vector vals using Rcpp Armadillo. Both x and vals are of type arma::uvec. In R, this would be straightforward: x <- c(1,1,1,4,2,4,4) vals <- c(1,4) which(v %in% vals) I've scanned the Armadillo docs and find() was my obv...
A quick dirty way: Rcpp::cppFunction(" arma::uvec ind(arma::uvec x, arma::uvec y){ arma::vec a(x.size(), arma::fill::zeros); for (auto i:y) a = a + (x==i); return arma::find(a) + 1; } ", 'RcppArmadillo') c(ind(v, vals)) [1] 1 2 3 4 6 7
72,858,877
72,858,979
Is it safe to transfer C++ objects among shared libs with the extern "C"?
Suppose I have C++ object, like std::function. Is it safe in every way to pass such an object to another dynamically loaded shared library like this: // lib extern "C" { void call( void* f ) { auto f_callable = (std::function<void()>*)f; f_callable->operator()(); } } // executable auto call = ( void (*) ( void...
This is defined behavior, provided that both parts of the C++ code gets generated by the same exact compiler. Casting the same thing to/from a void * is defined behavior. Presuming that the second C++ code sees the same C linkage, this is also defined behavior. Whether or not it is safe when different compilers or diff...
72,858,915
72,859,347
Getting the Address of a function that can only be called
I already asked a Question but I think thats very special and will not get a concrete answer. Im trying to give a simpler Explanation of what i need help with. The Issue is that d3d12::pCommandList->CopyTextureRegion; doesnt work because CopyTextureRegion is a function that can only be called, but i need the address of...
Taking the address of the member function: auto RegionHookAddress = &d3d12::ID3D12GraphicsCommandList::CopyTextureRegion; Calling the member function: (d3d12::pCommandList->*RegionHookAddress)(...);
72,859,109
72,859,458
Is enable_if the most concise way to define a function accepting only rvalues, but of any type?
I'm referring to this: #include <utility> template<typename T, typename = std::enable_if_t<std::is_rvalue_reference_v<T&&>>> auto f(T&&) {} int main(){ int i{}; f(std::move(i)); // ok f(int{1}); // ok f(i); // compile time error, as expected } Are there any other, shorter ways to acc...
As @HolyBlackCat commented, you can use concepts to simplify the function signature #include <type_traits> template<typename T> requires (!std::is_lvalue_reference_v<T>) auto f(T&&) {} Or detect lvalue or rvalue by checking the validity of a lambda expression that accepts an lvalue reference #include <utility> tem...
72,859,143
72,862,301
Boost graph non contiguous vertex indices
#include <boost/graph/adjacency_list.hpp> typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::edge_weight_t, double>> DiGraph; typedef boost::graph_traits<DiGra...
With the boost::vecS vertex container selection, the vertex index is implicit, and the call DiGraph di_graph( edges.begin(), edges.end(), weights.begin(), vertices.size()); is a lie: you tell it that there are 3 vertices, but then you index out of bounds (5, 10 are outside [0,1,2]). Note also that V v_start = boos...
72,859,235
72,860,428
Qt connect signals and slots of different windows/ mirror a lineEdit text on two windows
I'm new to any form of programming but have to do a project with Qt for my "programming for engineers" course where we simultaneously learn the basics of c++. I have to display a text from one lineEdit to a lineEdit in another window. I have a userWindow that opens from the mainWindow and in this userWindow I have a li...
"I get the error 'mainWindow' does not refer to a value" I don't see you having any "mainWindow" named variable anywhere, but you also mentioned that the MainWindow is the parent, which means you could get reference anytime, like: MainWindow *mainWindow = qobject_cast<MainWindow *>(this->parent()); Also, your signa...
72,859,241
72,863,041
Horizontal min on avx2 8 float register and shuffle paired registers alongside
After ray vs triangle intersection test in 8 wide simd, I'm left with updating t, u and v which I've done in scalar below (find lowest t and updating t,u,v if lower than previous t). Is there a way to do this in simd instead of scalar? int update_tuv(__m256 t, __m256 u, __m256 v, float* t_out, float* u_out, float* v_ou...
First find horizontal minimum of the t vector. This alone is enough to reject values with your first test. Then find index of that first minimum element, extract and store that lane from u and v vectors. // Horizontal minimum of the vector inline float horizontalMinimum( __m256 v ) { __m128 i = _mm256_extractf128_p...
72,859,301
72,860,463
CMake with multiple sub projects building into one directory
I'm not very familiar with CMake and still find it quite confusing. I have a project that has a server and client that I want to be able to run independent of each other but that builds together into the same directory (specifically the top level project build directory kind of like how games have the server launcher a...
You cannot have multiple subdirectories use the same build directory, but that doesn't seem what you're trying to achieve. Assuming you don't set the variable CMAKE_RUNTIME_OUTPUT_DIRECTORY anywhere in your project, and you don't specify the RUNTIME_OUTPUT_DIRECTORY target property for any of your targets by some other...
72,860,277
72,860,325
No memory is allocated while creating the class, then where variables in the class saved?
In object oriented programming, there is concept of class and objects. We define a class and then create its instance (object). Consider the below C++ example: class Car{ public: string model; bool petrol; int wheels = 4; } int main(){ Car A; cout << A.wheels; return 0; } Now I know no memory was...
There are 2 types of storage at work here. The information about Car is stored in memory. That is the code in its methods, its layout, including the literal value 4 which initializes wheels. This exists in the binary executable file, and exists in memory at all times your application is running. But when you say "no me...
72,860,507
72,860,684
How do i make a void method know what type to use?
So my question is very simple but i can't find how to do it . I created this method on .cpp void Message_Test::Integers(const uint64_t &_value){} and in the .hpp void Integers(const uint64_t &_value) I'm passing a uint64_t value { 35000 } to the method like so Integers(value), but i also would like to use this method...
Given that you want a const reference, assuming you had a good reason for it to be a reference, you can not allow any implicit conversion to happen. If the function is called with an uint16_t the compiler will create a temporary uint64_t and pass the address of that. For any valid reason to use a reference to a primiti...
72,860,572
72,863,702
C++ inline function inside a static class or namespace
I have a very small function that could be a macro, but anyway, I thought inline function would do exactly the same. But nah, when I mark a function in a namespace as inline it is not visible by any other file that includes my module. I tried it both with a static class and a namespace. No error when the function is de...
An inline function should be defined identically in every translation unit that uses it. So you should define your inline function exactly as you would a macro--in a header file that gets included by all of the files that need it.
72,862,163
72,872,786
Content of directory messes with how the code runs even though there's no reference of it
So I spent 2 hours trying to narrow down the cause of my code not working and I think it might just be something weird. Here's the exact example code I have and I can't minimize it further (yes, bar does literally nothing) : // thread example #include <iostream> // std::cout #include <thread> // std::thre...
The issue was the presence of a file called "libstdc++-6.dll" in my project directory. I have no memories of why it's here because I copied all libraries from another project but if anyone does the same mistake, here's your solution. Edit : I found out about why I had this in my files : it's because my build wasn't sta...
72,862,644
72,862,684
How to do error handling with vector of pointers?
This is probably a noob question, but I am a bit confused. I have a block of code that looks like this: std::vector<MyObject*> datas; try { MyObject data = get_me_data(); MyObject* dat=&data; datas.push_back(dat); } catch (...) {} do_something_with_datas(datas); The issue is that function after try/catch code that ...
I think the issue is that dat goes out of scope in try block Your hunch is correct. I am also uncertain if vector is cleared properly. Although this cannot be determined, based on the shown code this is very likely. This happens very often in code that suffers from a common problem called "Pointless Use Of Pointers...
72,864,514
72,864,585
Passing pointer reference from template function to non-template function
I am attempting to move around a pointer by reference (T*&) between some template functions. Under certain conditions this pointer reference may get passed to a different function that accepts a void pointer reference (void*&). When I attempt to pass the templated type into the function accepting a void*&, it gives m...
Case 1 Here we discuss the reason for the mentioned error. The problem is that param is an lvalue of type int* and it can be converted to a prvalue of type void* when passing it as the call argument in NonTempFunct( Param ); but the parameter of NonTempFunct is a non-const lvalue reference which cannot be bound to an r...
72,864,596
72,865,115
iterate over a Variadic Template function and choose pointer arguments
I have a Variadic Template function in C++ and I want to iterate over the template arguments and cherry-pick those arguments that are pointers. PLEASE SEE THE UPDATE SECTION BELOW. So, I have the following code below. I wrote a skeleton code that is compilable and runnable. g++ -std=c++17 f3_stackoverflow.cpp && ./a.ou...
template <int N, typename Arg, typename... Args> void helper(std::vector<std::pair<int, void*>>& v, Arg arg, Args... args) { if constexpr(std::is_pointer_v<Arg>) { v.emplace_back(N, (void*)arg); } if constexpr(sizeof...(args) > 0) { helper<N+1, Args...>(v, args...); } } template <type...
72,864,817
72,865,875
Pass array from C# to C++
I am trying to pass an array from C# to a C++ DLL and then print it from C++. The C# code is the following: [DllImport("DLL1.dll", CallingConvention = CallingConvention.StdCall)] public static extern void GMSH_PassVector([MarshalAs(UnmanagedType.SafeArray,SafeArraySubType = VarEnum.VT_I4)] int[] curveTag); int[] curve...
I don't think the marshal mechanism is able to translate a int[] to a std::vector. It's better to use language base types. Change the C++ function as void GMSH_PassVector(int * arr, int size) and in C# you have to instantiate a IntPtr to hold the address of the first element of the array. int bufferSize = 4; int[] buff...
72,864,937
72,865,021
How to do Google test for function which are not a part of class?
Am performing Google test, Here am facing one challenge. In my project some of the functions are not included in the header file, they are directly included in the source file. I can access the functions which are in header file by creating obj of the class but am not able to access which are only in source file. Pleas...
Declare them extern in your test code. Example. Let's say you have a source file like this: // Function declared and defined in .cpp file void myFunction() { // implementation } Then you could go ahead and do the following in your test code: extern void myFunction(); TEST(MyTest) { myFunction(); } Unless the...
72,865,106
72,866,133
May this kind of rewrite of placement new compile?
Background I am cleaning up a legacy codebase by applying a coding guideline for the new statement. There is code like auto x = new(ClassName); that I rewrite to auto x = new ClassName();. It's quite obvious that this is not a placement new and I don't need to think about it. However, there's also code like auto x = ne...
placement-params is not a type, it is a value. Consider this code with a placement new: int* buf = new int; int* a = new(buf)(int); If we remove parenthesis around buf, the compiler can easily detect buf is not a type. int* a = new buf(int); // compile error Even if we create a type named buf, by the name lookup rule...
72,865,756
72,865,967
How can I transfer matrix data from Matlab to OpenCV, C++?
I have a 57X1 double matrix in Matlab and I want to find a way to save that data and then load it to a new OpenCV Mat. For actual images I used to do imwrite in Matlab and then imread in OpenCV but, in this current situation, the result was a Mat with all of the values equal to 255.
The simplest way is to just use csvwrite to write as a text file, and then load it in C++ by reading the numbers from the text file. If you must have binary exact values, you can use the fopen, fwrite, fclose to write the values in binary format, and then use the equivalent functions (i.e. fread or ifstream::read) to r...
72,865,925
72,866,049
On uint64 to double conversion: Why is the code simpler after a shift right by 1?
Why is AsDouble1 much more straightforward than AsDouble0? // AsDouble0(unsigned long): # @AsDouble0(unsigned long) // movq xmm1, rdi // punpckldq xmm1, xmmword ptr [rip + .LCPI0_0] # xmm1 = xmm1[0],mem[0],xmm1[1],mem[1] // subpd xmm1, xmmword ptr [rip + .LCPI...
x86 has an instruction to convert between signed integers and floats. Unsigned integer conversion is (I think) supported by AVX512, which most compilers don't assume by default. If you shift right a uint64_t once, the sign bit is gone, so you can interpret it as a signed integer and have the same result.
72,865,996
72,866,174
Facing problems in my first time handling CMake, Third party(header only) libraries
I want to use the following library https://github.com/gmeuli/caterpillar It's documentation says that it's a header-only library, and that I should "directly integrate it into my source files with #include <caterpillar/caterpillar.h>." It also depends on a few other libraries, one of which I need to use directly as we...
Firstly, modern cmake recommends target_include_directories() instead of old include_directories() for better scope management. Actually <caterpillar/caterpillar.hpp> is not in $PROJECT_SOURCE_DIR/lib directory. That's why your code not works. CMakeLists example: cmake_minimum_required(VERSION 3.22) project(myproject) ...
72,866,491
72,868,563
VS Code is incorrectly formatting numbers separated by apostrophes in C++
I am using VS Code for developing C++ code and these are my settings: Editor: Format On Save: on C_Cpp: Formatting: Default C_Cpp: Clang_format_fallback: GNU This is my code before formatting: #include <iostream> using namespace std; int main () { cout << endl; long large_number{ 7'958'482'164 }; cout << "Lar...
Change C_Cpp: Clang_format_fallback to a value other than GNU, I changed it to Visual Studio and it now works fine.
72,866,641
72,898,110
Black background appears after converting from Mat(OpenCV) to UIImage
I have an application that uses some functions of the OpenCV library to edit images. After converting UIImage to Mat and Mat to UIImage I get a black background in the image please tell me how to fix it my code which i use to convert UIImage to Mat - (cv::Mat)cvMatFromUIImage:(UIImage *)image { CGColorSpaceRef colo...
Functionally functional, no reproduction issues. Because of a hint, I adjusted kCGImageAlphaNoneSkipLast|kCGBitmapByteOrderDefault to kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast kCGImageAlphaNone|kCGBitmapByteOrderDefault to kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast
72,867,013
72,867,691
Read non-specified format file data
I have a problem reading file data packed as binary resource. I have something like this 7ë?Vý˝‹ĺ”>˙†J˙l$í?źÔ=ć$ľ>˙†J˙(çî?Yý˝ć$ľ>˙†J˙'Šč?[ý˝"6?˙†J˙KÓć?[YČ="6?˙†J˙…?Ů?[ý˝fË$?˙†J˙4Ą×?ĄŰŞ=fË$?˙†J˙ĚúĹ?[ý˝n8?˙†J˙r„Ä?s˛…=n8?˙†J˙Ôž°?[ý˝.2??˙†J˙?š?$>Í<n8?˙†J˙ÜB›?[ý˝n8?˙†J˙#ţ‡?[ý˝fË$?˙†J˙}ű†?eâ;fË$?˙†J˙gq?[ý˝"6?˙†J˙Ëšo?Đuő»"6?˙...
If your data is the binary representation of IEEE 754 floating point numbers, which it looks like it is, you can memcpy that data into a float variable. You may need to do endianness conversion, depending on the platform you're compiling for. Compiler explorer // read this from a file and store it in some container. //...
72,868,191
72,868,392
C++: Alternative to this range's view construction with same requirements?
To remove manual logic in my code, I use that construct: std::ranges::drop_view a { std::ranges::take_view(my_range, my_range.size() -X), Y}; with X and Y values I pass at runtime. Even though I check the algorithms, I could not find a shorter way that has the following constraints: don't go beyond or below the range...
You can compose take_view and drop_view into a new adaptor auto take_and_drop = [](auto n, auto m) { return std::views::take(n) | std::views::drop(m); }; auto a = my_range | take_and_drop(my_range.size() - X, Y);
72,868,412
72,868,793
How can I set add_executable WIN32 property or not depending on the build type?
This fails with the error "Cannot find source file: WIN32. Tried extensions..." add_executable(${PROJECT_NAME} $<$<CONFIG:Release>:WIN32> main.cpp) I need this in order to launch the app in the console in Debug mode and being able to read information printed to the console. And as far as I know it's wrong and is advis...
As you noticed you cannot use generator expressions for the WIN32 keyword in the add_executable command. Instead, try setting the corresponding property WIN32_EXECUTABLE on the target: set_target_properties(${PROJECT_NAME} PROPERTIES WIN32_EXECUTABLE $<CONFIG:Release>)
72,869,955
72,870,229
derived class as a parameter of templated function which is specialized for its base class
class Base {}; class Derived : public Base {}; class SomeClass { template<typename T> static void SetContent(T* pChild, OVariant content) { LOG_ASSERT(0, "All classes must be specialized!. Please provide implementation for this class."); } }; template <> void SomeClass::SetContent(Base* valu...
You can convert a Derived* to a Base*, but I think you rather want to specialize for all T that have Base as base #include <type_traits> #include <iostream> class Base {}; class Derived : public Base {}; template <typename T,typename = void> struct impl { void operator()(T*) { std::cout <<"All classes mu...
72,870,279
72,873,583
access variable in so file and register callback function in ctypes
I'm trying to access variable declared in cpp header file from the compiled shared object. Below is my case /cpp_header.hpp/ #include <stdint.h> #include <stdio.h> #include <string.h> //variables declaration const uint8_t variable1 = 3; const uint16_t variable2 = 4056; const uint16_t variable3 = 3040; typedef struct ...
Variables and function in must be exported for ctypes to find them. extern may be sufficient on Linux to export variables, but on Windows both variables and functions need an additional __declspec(dllexport) declaration. ctypes also expects exported variables and functions to be C linkage, so C++ variables and functio...
72,870,293
72,871,591
Cmake reconfiguration with sanitizers added doesn't trigger ninja to recompile
Let's assume a minimal top level CMakeLists.txt like this: 1 cmake_minimum_required(VERSION 3.22) 2 set(CMAKE_CXX_STANDARD 20) 3 4 project(stackoverflow LANGUAGES CXX C) 5 6 add_executable(prog src/main.cpp) 7 8 option(ENABLE_SANITIZER "Enables sanitizer" OFF) 9 if(ENABLE_SANITIZER) 10 target_co...
When you set a variable, it is set inside cache CMakeCache.txt. When you don't reset it when reconfiguring, it preserves its previous value. The option.... OFF, only set's the option to OFF if it is unset. Even set(ENABLE_SANITIZER OFF) will not set the variable if it is in cache, only set(.... CACHE "" "" FORCE), refe...
72,870,386
72,870,456
why the destructor is called only one time when the constructor is called 5 times?
I'm trying to learn more about C++ ,int this code I'm allocating an array of A's (5 in this case), what I understand that 5 A's will be allocated ...so the compiler will call 5 times the constructer , but in case of deleting that array it calls the destructor one time only ,so my question is why does it call the destr...
You need to use delete[] a to delete an array of things allocated with new[]. If you do that, you'll see the correct output: IM in C'tor IM in C'tor IM in C'tor IM in C'tor IM in C'tor IM in De'tor IM in De'tor IM in De'tor IM in De'tor IM in De'tor
72,870,732
73,090,786
Array, which elements links to elements of another array
I want to have an array each elements of each somehow indicates some element of another resizable array I tried: vector <int> a={1,2,3}; vector <int*> b={*(a[0]),*(a[1]),*(a[2])); But every editing of size of vector a, copies himself to empty place of memory, so pointers in array b links to an empty place
I used unordered_map to store elements. In second array I stored keys to map. How to close this question?
72,870,778
72,882,610
C++ - detect is first base class at compile time
I'd like to detect that class Base is the first base of class Deriv. That is, they have the same pointer. The example below doesn't work. I tried a few more things, wrapping casts in functions and unions, and got nowhere. With a union it works only if all the types are literal - default destructable etc, which my class...
For aggregate classes you can probably use the aggregate initialization mechanism and conversion operator templates to detect the first base's type. Except for this class, I don't think it is generally possible to detect the first base class. If you want to test instead whether the base has the same address, then stat...
72,870,785
72,871,588
If-else statement either all or none
PS: Not a homework question I have three strings: string1, string2, string3 Either all of them have to be empty or none of them. In the invalid scenario where some of them (not all) are empty, I have to inform which one(s) is/are empty. Following is my if-else block which is verbose. Is there a concise and better way t...
We can generically check for n booleans to be in agreement by simply adding them: if ((Check1() + Check2() + ... + Checkn()) % n) { // They're not all equal } Which we could make into a function like so: template <class ... bools> bool AllOrNothing (bools ... bs) { return (0 + ... + bs) % sizeof...(bs); } In ...
72,870,905
72,871,050
How compiler enforces C++ volatile in ARM assembly
According to cppreference, store of one volatile qualified cannot be reordered wrt to another volatile qualified variable. In other words, in the below example, when y becomes 20, it is guaranteed that x will be 10. volatile int x, y; ... x = 10; y = 20; According to Wikipedia, ARM processor a store can be reordered a...
so, in the below example, second store can be executed before first store since both destinations are disjoint, and hence they can be freely reordered. The volatile keyword limits the reordering (and elision) of instructions by the compiler, but its semantics don't say anything about visibility from other threads or ...
72,871,031
72,871,592
Does icc -xCORE-AVX2 force the non-utilisation of AVX512 instructions on Xeon Gold if -O3 is on?
As per the title, Will programs compiled with the intel compiler under icc -O3 -xCORE-AVX2 program.cpp Generate AVX512 instructions on a Xeon Gold 61XX? Our assembler analysis doesn't seem to find one, but that is no guarantee. Thanks!
In ICC classic, no, you can use intrinsics for any instruction without telling the compiler to enable it. (Unlike GCC or clang where you have to enable instruction sets to use their intrinsics, like the LLVM-based Intel OneAPI compiler.) But the compiler won't emit AVX-512 instructions other than from intrinsics (or i...
72,871,282
72,871,485
Is the std::vector copied or moved in this case?
In the following code which implements the Viterbi algorithm: (Wikipedia link) std::pair<std::vector<index_t>, float> viterbi_get_optimal_path(const SoundGraph &g, SequenceIter s_first, SequenceIter s_last, ...
Assuming C++17 or later, it will be copied once if the function returns via return {seq, prob}; and moved once if it returns via return {std::vector<index_t>({curr_index}), 1.0f};. You can avoid the copy, by explicitly moving in the return statement: return {std::move(seq), prob}; In the most common case such a move o...
72,871,304
72,871,834
Calling a common method of tuple elements
Say I have a tuple of types T1,...,TN that implement some method, apply(). How do I define a function that takes this tuple and some initial element, and returns the chained call of apply() on this element? For example: template <typename... Args, typename Input> auto apply(std::tuple<Args...> const &tpl, Input x) { ...
There may be snazzier C++17 ways of doing it, but there is always good old-fashioned partially-specialized recursion. We'll make a struct that represents your recursive algorithm, and then we'll build a function wrapper around that struct to aid in type inference. First, we'll need some imports. #include <tuple> #inclu...
72,871,346
72,873,055
How to simply build an external project with cmake externalproject_add
I've got a library I want to integrate into an existing cmake build. All cmake has to do is go into that directory, run "make", perform install steps as I lay out (probably just a copy to an included binary directory), and then keep doing its thing. Cmake continues to step on my toes trying to create directories and gu...
If you aren't downloading code then SOURCE_DIR needs to be set to an existing directory containing your library. If you aren't using cmake then you need to set CONFIGURE_COMMAND to an empty string as stated in the ExternalProject_Add documentation.
72,871,723
72,880,612
pybind11 very simple example: importError when importing in python
I'm trying to compile a very simple example using pybind11, but unlike all tutorials I can find, I don't want to copy the pybind11 repo into my project. I currently have CMakeLists.txt cmake_minimum_required(VERSION 3.22) project(relativity) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED YES) find_packag...
The first argument passed to the PYBIND11_MODULE macro should be the name of the module (and therefore should match the content of the "PROJECT_NAME" variable as defined in the cmake file): PYBIND11_MODULE(relativity, m) { // <---- "relativity" instead of "example" m.doc() = "pybind11 example plugin"; // optional m...
72,871,781
72,872,092
Creating custom sizeof() that returns narrower types
The Issue sizeof returns size_t type, so when passed as argument to functions that takes in narrower types (e.g. unsigned char), implicit conversion occurs. In many cases these are 3rd party library functions, so their prototypes are beyond my control. Compilers are now typically smart enough to detect whether such con...
For your specific problem, there need not be any runtime checks even on debug builds as some has suggested, since the value is itself a constexpr. You can write a simple utility to cast a value to the smallest type that is able to hold it. template<size_t N> inline constexpr auto minuint = []{ if constexpr(N >= 1ul...
72,872,200
72,872,232
How to convert string to an int array using stoi() && substr()
im triying to convert an string to an integer and save those numbers into an array, i tried like this #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { int number[5]; string input; //numbers cout << "type sonme numbers"<<endl; cin >> input; for(int i = 0 ...
Your first loop is asking for a substring beginning at index 0, with length 0, so you're passing an empty string to stoi. Even if you in fact provided valid inputs (a string of at least eight digits, so you could call .substr(4, 4) on it and get useful results), the first loop always tries to parse the empty string and...
72,872,373
73,068,894
How to color the output stream of std::cout, but not of std::cerr and std::clog?
I am dealing with the following problem: I am on Ubuntu and if I color all the stream in red, for example with the following command: #include <iostream> std::cout << "\033[31m" << "From now on the stream is red!"; what happens is that not only the std::cout object, but also std::cerr and std::clog objects will displ...
After a few days of tries I found a pretty suitable solution for this problem. I simply created a functor able to apply changes directly to the std::ostream object, to be used in this way: functor( std::cout ) << "Modified output stream"; Such an implementation si a bit long and can be found here.
72,873,044
72,938,120
Retrive Informations about currently running sessions using Windows.Media.Control with C++/WinRT
I would like to know, how to retrive informations(e.g application name) about all the sessions that are currently running. GlobalSystemMediaTransportControlsSessionManager SessionManager(); IVectorView<GlobalSystemMediaTransportControlsSession> Sessions; Sessions = SessionManager.GetSessions(); // for sessions - sessio...
Using, trial and error method, I have finally achived what I was looking for, in a way. Hopefully, it will be usefull to someone other, than me. I didn't know, you have to pass NULL as parameter to GlobalSystemMediaTransportControlsSessionManager class, for some reason. Also, had some problem with converting hstring ...
72,873,908
72,889,879
How Call C++ Variables Using CGo For Standard Libraries
I am trying to get a variable value from a c++ code using cgo. For libraries ended in .hall works fine, but for libraries like <iostream>, <map>, <string> etc, I got the following error: fatal error: iostream: No such file or directory 4 | #include <iostream> | ^~~~~~~~~~ Below my code: package mai...
CGo allows you to link your Go code against code that implements the C-style foreign function interfaces. This does not mean that you can just stick arbitrary-language code into place. Let's start with the first problem, which is that the import "C" line in one of your Go files must contain only C code above it. That...
72,874,026
72,876,082
Bad Request: message text is empty when sending get request via winapi to telegram bot
I'm trying to send message to telegram chat from bot using winapi and c++. Here is my code char szData[1024]; // initialize WinInet HINTERNET hInternet = ::InternetOpen(TEXT("WinInet Test"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hInternet != NULL) { // open HTTP session HINTERNET hConnect = ::Inter...
There are a number of issues with this code: You don't need to typecast the return value of wstring::c_str() to LPCWSTR (aka const wchar_t*), as it is already that type. You can't send body data in a GET request. The Telegram Bot API expects body data to be sent in a POST request instead. You are telling HttpSendReq...
72,874,439
72,874,485
What's going on, when trying to print uninitialized string
I'm just decided to test malloc and new. Here is a code: #include <iostream> #include <string> struct C { int a = 7; std::string str = "super str"; }; int main() { C* c = (C*)malloc(sizeof(C)); std::cout << c->a << "\n"; std::cout << c->str << "\n"; free(c); std::cout << "\nNew:\n\n"; ...
You've used malloc. One of the reasons to not do this is that it hasn't actually initialized your object. It's just allocated memory for it. As a result, when accessing member fields, you get undefined behavior. You have also forgotten to delete the C object you created with new. But you may wish to use a std::unique_p...
72,874,949
72,875,967
PlaySound plays default windows error sound
I'm trying to make a simple audio player in C++ using the Win32 API library. How this program currently works, is you select a file via file explorer, which then the file's location is saved onto a list box. When you press the "play" button, it takes the file location from the list box, and parses it to a function that...
When calling PlaySound(), you are type-casting a char* to a wchar_t*. Don't do that. Use PlaySoundA() when passing in a char* string, eg: void AudioPlayer::playAudio(const char* audioLocation) { PlaySoundA(audioLocation, 0, SND_FILENAME); } However, you are creating your ListBox as a Unicode window, so you should...
72,874,966
72,875,277
I cant send a message with a discord webhook using cURL error : "Cannot send an empty message
So im trying to send a message to a discord webhook using this code: #include <iostream> #include <curl/curl.h> int main(void) { CURL* curl; CURLcode res; const char* WEBHOOK = "webhookLink"; const char* content = "test"; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (cu...
You need to add the Content-Type header to your request. Example (I have no discord webhook so I can't test it): #include <curl/curl.h> #include <iostream> int main(void) { CURL* curl; CURLcode res; const char* WEBHOOK = "webhookLink"; const char* content = R"aw({"content": "Posted Via libcurl"})aw";...
72,875,177
72,875,849
Error using Eigen: Perform element-wise multiplication between a vector and matrix
I am trying to perform an element-wise multiplication of a row vector with matrix. In MATLAB this would be simply done by the "dot" operator or: deriv = 1i * k .* fk; where k is row vector and fk is a matrix. Now in C++ I have this code: static const int nx = 10; static const int ny = 10; static const int nyk = ny...
Eigen doesn't do broadcasting the same way Matlab or Numpy do unless you explicitely ask for it, for example with matrix.array().rowwise() * vector.array() The IMHO clearer form is to interpret the vector as a diagonal matrix. Eigen::VectorXd eK = ...; Eigen::Map<Eigen::MatrixXcd, Eigen::Unaligned> U = ...; Eigen::Mat...
72,875,270
72,876,093
Can you "hop" between "linked classes" in C++ metaprogramming?
Suppose you have something like this: template<class D> class HasDef { public: typedef D Def; }; class A : public HasDef<class B> {}; class B : public HasDef<class C> {}; class C {}; So it is like a "metaprogramming linked list", with type links, via the included typedef Def. Now I want to make a template "Leaf"...
I don't really like f(...) in modern code, thus my version uses void_t from C++17: #include <type_traits> template<class D> struct HasDef { typedef D Def; }; struct A : HasDef<class B> {}; struct B : HasDef<class C> {}; struct C {}; template <typename T, typename=void> struct DefPresent : std::false_type{}; ...
72,875,423
72,875,509
std::for_each and unordered_map value modification with parallel execution policy
Does this usage of parallel for_each is ok with unordered_map: void test() { std::vector<double> vec; constexpr auto N = 1000000; for(auto i=0;i<N;i++) // this is just for the example purpose vec.push_back(i*1.0); auto my_map = std::unordered_map<double,double>(); for(const auto d: vec) m...
According to cppreference: When using parallel execution policy, it is the programmer's responsibility to avoid data races and deadlocks So, no (direct) help from the Standard Library there. However, as you yourself point put, this line: my_map.at(d)=d+1.0; is only reading the map. The only thing it's writing to is ...
72,875,968
73,101,805
How to convert a quaternion to a polar/azimuthal angle rotation
I have an arcball camera with a rotation defined by two angles (phi/theta, polar/azimuthal) that is controlled with mouse movement. I convert these two angles (as euler angles) to a quaternion like this: glm::quat rotation = glm::quat(glm::vec3(phi, theta, 0)); At some point I need to convert a quaternion back to two ...
I found a solution: Start with a unit vector pointing in the Z axis (depends on your engine's handedness and up-vector) glm::vec3 v = glm::vec3(0, 0, 1); Rotate the vector with the quaternion you want to convert v = q*v; glm does this automatically, otherwise rotate a vector like this : quat v_quat = quat(v.x, v.y, ...
72,876,099
72,876,859
CUDA no operator += for volatile cuda::std::complex<float>
I have a kernel that uses cuda::std::complex<float>, and in this kernel I want to do warp reduction, following this post. The warpReduce function: template <typename T, unsigned int blockSize> __device__ void warpReduce(volatile T *sdata, unsigned int tid) { if (blockSize >= 64) sdata[tid] += sdata[tid + 32]; i...
According to my testing, in CUDA 11.7, the issue revolves around the use of volatile. According to this blog, this style of programming (implicit warp-synchronous) is deprecated. additionally, this part of your posted code could not possibly be correct: extern __shared__ int sdata[]; Combining these ideas, we can do t...
72,876,295
72,876,381
Pass List to Function Requiring std::initializer_list<std::initializer_list< type > >?
I'm using OpenNN to write a proof of concept right now, and I'm having an issue with declaring inputs for a Tensor. From the OpenNN website we see that the neural net accepts a Tensor input Tensor<type, 2> inputs(1,9); inputs.setValues({{type(4),type(3),type(3),type(2),type(3),type(4),type(3),type(2),type(1)}}); neural...
EDIT: Found a relevant post here This solution is more for anyone else that comes around and my question can't be answered; I solved this problem as follows: namespace Eigen { template < typename T > decltype(auto) TensorLayoutSwap(T&& t) { return Eigen::TensorLayoutSwapOp<typename std::remove_reference<T>::t...
72,876,587
72,890,798
static shared_ptr not keeping value across function calls
I have an input.hpp (which I won't post for the sake of brevity) and an input.cpp file that looks like this (some things removed): #include "details/macros.hpp" #if defined(PLATFORM_WINDOWS) #include "details/win32/input.inl" #else #error "No input implementation for this platform." #endif #define CHECK_INPUT_...
I found out the answer to this problem. I mistakingly (don't code while tired people!) had a call to the Win32 API GetKeyboardState that was using the wrong static variable as the output buffer and caused static memory corruption. Thank you for everyone's help and I apologize for not giving much information to deal wit...
72,876,699
72,876,706
vector size changes after push_back()
I am not sure why the .size() of a vector<string> (10) below is changing from 10 to 20 after .push_back(string) on it. I would assume it should remain the same. int main() { vector<string> StrVec(10); vector<int> intVec(10); iota(intVec.begin(), intVec.end(), 1); cout << "StrVec.length = " << StrVec.s...
When you write vector<string> StrVec(10);, it initializes StrVec with 10 default-initialized string elements. Then, each push_back() pushes a new element to StrVec while iterating over intVec, thus arriving at 20 elements. If you only wanted to pre-allocate memory (but not have any elements), you might consider using t...
72,876,717
72,876,767
Window closes only after clicking exit button multiple times?
When I try to exit the window by clicking the X at the top corner, the program wouldn't end and just continue running. Only after repeatedly clicking the X button, the window managed to close. Why is this the case? main.cpp: #include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "window.hpp" #in...
Those two loops will not exit just because you clicked exit: while (accumulator >= deltaTime) { while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: gameLoopRunning = false; } accumulator -= deltaTime; } } Th...
72,877,364
72,877,445
Why here template Vector3<int> cannot convert to Vector3<int>?
It seems quite weird. Here you can see the error message is that a convert happens between one type and it fails. If I remove the explicit modifier from Vector3's copy constructor it is fine, no error. Could someone explain why? I'm confused. template<typename T> class Vector3 { public: explicit Vector3(const Vecto...
return Vector3<T>(); performs copy initialization, which won't consider explicit constructors: including the copy constructor. That's why you should mark the copy constructor non-explicit. Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are n...
72,877,370
72,877,452
Why can't I run my getline code without the stringstream? How do i use stringstream to make this code work?
#include<iostream> #include<string> using namespace std; int main() { string randomwords,temp; getline(cin,randomwords); while(getline(randomwords,temp,' ')) { cout<<temp<<endl; } return 0; }
std::getline's first parameter is a std::basic_istream. There is no conversion between a std::basic_string and a std::basic_istream, so you cannot pass a std::string (a specialization of std::basic_string) as a first parameter to std::getline. This is a fundamental rule of C++, parameters to functions must have matchin...
72,877,408
72,878,033
Center viewport after resize OpenGL / GLUT
Im working in my reshape callback but i cant get the viewport centered after resize, it stays in the top-left corner. Im working with FreeGLUT. This is my reshape function: void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, w, h, 0); glM...
The problem is the orthographic projection and the view space coordinates: gluOrtho2D(0, w, h, 0); In this projection, the upper left coordinate is (0, 0) and the lower right is (w, h), so the center is (w/2, h/2), which depends on the size of the view. Since the object's coordinate has not changed, it is no longer ...
72,877,432
72,900,483
G++ failed to compile __attribute__ keyword
I tried compiling attribute with g++, but failed, gcc will compile successfully. g++ test.c -o test Here is the function: #include <stdio.h> #include <stdlib.h> struct student{ int num; }; static __inline int student_information (struct student *) __attribute__((__unused__)); static __inline int student_informati...
It's because g++ is a C++ compiler and you're giving it invalid C++: it has to reject this code, so it just tells you why and quits. Also, the __attribute__ keyword is a compiler-specific extension, which in this case could be replaced by [[maybe_unused]]. In fact nothing in standard C++ starts with any underscores: su...
72,877,471
72,879,841
C++ confusing closure captures [v] vs [v = v]
In the following code, it seems that the compiler sometimes prefer to call the templated constructor and fails to compile when a copy constructor should be just fine. The behavior seems to change depending on whether the value is captured as [v] or [v = v], I thought those should be exactly the same thing. What am I mi...
I don't disagree with 康桓瑋's answer, but I found it a little hard to follow, so let me explain it with a different example. Consider the following program: #include <functional> #include <iostream> #include <typeinfo> #include <type_traits> struct tracer { tracer() { std::cout << "default constructed\n"; } tracer(...
72,878,439
72,878,595
Debugger is not stepping into expected function
#include<iostream> #include<string> using namespace std; void reverse(string s){ if(s.length()==0){ //base case return; } string ros=s.substr(1); reverse(ros); cout<<s[0]; } int main(){ reverse("binod"); } debugger_img_1 debugger_img_2 PFA, The debugger is supposed to step into ...
The debugger is stepping into the std::string(const char*) constructor. Your code calls this implicitly before calling reverse because you pass "binod" (which effectively has type const char*) to a function expecting a std::string. There's nothing wrong here, it's not the wrong function, just a function you didn't real...
72,878,763
72,879,473
C++ template specialization for enum
I want to map known type to enum value defined by myself. enum class MyType : uint8_t { Int8, Uint8, Int16, Uint16, Int32, Uint32, ... // some other primitive types. }; template <typename T> constexpr uint8_t DeclTypeTrait(); template <> constexpr uint8_t DeclTypeTrait<int8_t>() { return...
Use a class template will be much simpler for your case. template <typename T, typename = std::void_t<>> struct DeclTypeTraitT { }; template <typename T> inline constexpr uint8_t DeclTypeTrait = DeclTypeTraitT<T>::value; template <> struct DeclTypeTraitT<int8_t> { static constexpr uint8_t value = static_cast<uint...
72,879,821
72,899,607
CUDA Unified Memory: Difference in behaviour on Windows and Linux
I am porting an application from Linux to Windows and discovered significant runtime differences of the same code on the same hardware between Windows and Linux. A minimal working example: #include <iostream> #include <chrono> #include <cuda.h> constexpr unsigned int MB = 1000000; constexpr unsigned int num_bytes = 20...
According to the documentation: GPUs with SM architecture 6.x or higher (Pascal class or newer) provide additional Unified Memory features such as on-demand page migration and GPU memory oversubscription. [...] Applications running on Windows (whether in TCC or WDDM mode) will use the basic Unified Memory model as on ...
72,879,874
72,879,917
Why iterative std::max with 2 constants is faster than std::max with initializer list?
Compiler : Visual Studio 2019 , Optimization : (Favor Speed)(/O2) In a loop (over 1 million cycles), I use std::max to find the maximum element among 10 elements. When I use std::max iteratively, like using namespace std; using namespace chrono; auto start = high_resolution_clock::now(); for(int i=0;i<1000000;i++) ...
You are copying all of the array elements when you are constructing an initializer list, which is going to incur more overhead.
72,880,385
72,880,456
How to allocate char poiter to pointer char ** is it possible in C++ or do I need C for this
Lets say I have char pointer to pointer now I want to allocate space for 3 pointers. I believe size of C++ char pointer is also 8 bytes. first pointer sized of 8 bytes will have strings that I will allocate later. I want to allocate memory for 3 pointers so I can access these pointers through a[0][string_num] to a[2][s...
Don't put parentheses around the type. a = new char *[3]; As an aside, if you are writing C++, use std::string for strings, and std::vector for dynamic arrays.
72,880,495
72,880,588
Why doesn't push_back keep working in a loop?
Completely new to C++. Programmed selection sort on 1D array of arbitrary length. Want to allow user to keep inputting integers into console to make an array of desired length, to be subsequently sorted. Can only seem to make arrays of length 2 using a while loop for adding elements. Code and example of erroneous resul...
This declaration int len = sizeof(v) / sizeof(v[0]); is equivalent to the declaration int len = sizeof( int * ) / sizeof( int ); because the variable v is declared like int* v = &vDyn[0]; The size of a pointer is equal usually to 4 or 8 bytes. So the variable length will have the value either 1 or 2 and does not dep...
72,880,528
72,915,991
Sonar cognitive complexity checking for a function
I try to understand how sonarqube calculates the coginitive complexity and I wonder if this is correct and for instance this function's complexity is indeed 16. I guess it is not 16 because limit of 15 was not exceeded. Can you help me what is exact cognitive complexity of this function? Thank you. bool sonarQuestion()...
That's an interesting way of looking at complexity. I'm not familiar with Sonar at all, but I did find this link where they explain the principles. Looking at that document, I think your example has a score of 12: bool sonarQuestion() { // 1 + 1 (1 if, 1 sequence of operators) if (not (1 and 0 and 1)) { ...
72,880,578
72,881,202
Ranges-v3 transform limitations
I am trying to use ranges-v3 to split an SNMP OID into parts and return them as a std::deque<uint32_t>. The following code works but only after I added a number of additional un-natural steps: #include <range/v3/all.hpp> /// split the supplied string into nodes, using '.' as a delimiter /// @param the path to split , ...
The value type of the range returned by ranges::views::split isn't std::string_view, it is a implementation detail type. I'm not sure why you were able to | to<std::vector<std::string>> at all. Because it uses a sentinel, you will need to convert it to a common range (prior to C++20, when std::string_view is constructi...
72,880,681
72,881,153
Why we need 'namespace scope' concept? - in C++
I learned that in namespace "name decoration(mangling)" takes place so that it can be differentiated from other same identifiers which is in different namespace. Wiki: Name mangling If then, Why "namespace scope" exists? I thought just 'name decoration' can solve all problem about name conflicting. Because in C, the re...
Namespaces scope is very useful in programming for the following reasons: Avoids name collisions between functions/classes, eg., Suppose you have two functions of same name but in different namespace scope (foo::func() and bar::func()) Can be used for managing similar functions inside it, eg., sin(), cos() and sqrt() ...
72,880,726
72,881,033
multi-thread program initialization using call_once vs atomic_flag
In book C++ Concurrency in Action 2nd, 3.3.1, the author introduced a way using call_once function to avoid double-checked locking pattern when doing initialization in multi-thread program, std::shared_ptr<some_resource> resource_ptr; std::once_flag resource_flag; void init_resource() { resource_ptr.reset(new some...
The race condition in your code happens when thread 1 enters DoInit and thread 2 skips it and proceeds to Foo. You handle it with if(!initialized) return in Foo but this is not always possible: you should always expect a method to accidently do nothing and you can forget to add such checks to other methods. With std::c...
72,880,751
72,882,027
Why does assigning a value to a string in a struct crash the program?
I have commented out the problematic string, attempted to pass the input to a string that is not a member of the struct, then passing it to the correct string, to no avail. To achieve the intended function, the string must go through this struct. Where is it going wrong? Structure code: #include <iostream> #include <st...
In labelsNeeded you store the size of the array. Then in the first iteration you use labelsNeeded to index into your array. Since C++ indexes an array starting from 0, the largest possible valid index is (the size of the array) - 1. Eg.: For an array of size 4, your valid index range is [0, 1, 2, 3]. Now what you are d...
72,881,213
72,882,345
How to handle invalid state after move especially for objects with validating constructor?
I made a class for a function's argument to delegate its validation and also for function overloading purposes. Throwing from constructor guarantees that the object will either be constructed in a valid state or will not be constructed at all. Hence, there is no need to introduce any checking member functions like expl...
You are trying to maintain two invariants at once, and their semantics are in conflict. The first invariant is the validity of the certificate. The second is for memory management. For the first invariant, you decided that there can be no invalid constructed object, but for the second, you decided that the object can b...