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
68,960,382
68,969,453
Why is a function parameter behaving like a variable declaration?
I am using Unreal and ran into some weird errors. I eventually found that simply renaming my function parameters fixed the problem. Here is the full header and class. The problem is the InitCard function: #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Components/StaticMeshComponent....
It is not because of the parameter is behaves like a variable declaration (though, they differs only by the way of initialization), but because of just name reusing (it could be a name of not only an already existing variable). To name the parameters as you did initially is totally correct in regard to C++ language, bu...
68,960,650
68,990,123
Why call a Base Class virtual member from an Inherited class?
I've done C++ stuff for a number of years, no formal training, though. Most of my background is aerospace where we had to always reinvent the wheel, no use of 3rd party libraries or APIs, so those are kind of new to me. I'm working on something that does have an API and I am a little confused by some existing code. W...
I think that original question has been answered as best as it can be given the info that I provided. The implementation of the framework dictates how this is used. In my case, the specific framework is hiding a lot of details. While not common, this is not unheard of and can be considered an anti-pattern, "Call Super"...
68,960,734
68,960,853
insert function result in rubish number
I don't know why I get these rubish numbers in my vector container? here is the code: #include <iostream> #include <vector> int main() { std::vector<int> ivec = {2,3,5,7}; std::vector<int>::iterator it = ivec.begin(); std::vector<int>::iterator pos = ivec.begin()+1; ivec.insert(pos,444); while(it != ivec.begin())...
When you insert a value in to a container (a vector in this case) you can invalidate any iterator's you currently have if the vector needs to resize. If the vector doesn't resize only iterator's before the insertion remain valid. The past the end iterator is also invalidated. Also, your while loop condition should be i...
68,960,939
68,961,124
Iterate through an array randomly but fast
I have a 2d array that I need to iterate through randomly. This is part of an update loop in a little simulation, so it runs about 200 times a second. Currently I am achieving this by creating a array of the appropriate size, filling it with a range, and shuffling it to use to subscript my other arrays. std::array<int,...
You should shuffle the entire matrix rather than going through one row/column at a time. This should work pretty fast. It's 125k and should be reasonably cache friendly. constexpr int N = 250; std::array<uint16_t, N* N> nums; std::iota(nums.begin(), nums.end(), 0); std::shuffle(nums.begin(), nums.end(), engine); for (...
68,961,005
68,961,059
Is it safe to delete a nullptr twice in C++?
I have watched a talk in CPPCon which is back to basic: class layout and the link is this. At 54:20, he said it's undefined bahavior to delete the nullptr twice. As far as I know, C++ standard guarantee deleting a nullptr does nothing but why deleting a nullptr twice is undefined bahavior? And I was told before that th...
Is it safe to delete a nullptr twice in C++? Yes (in all standard versions of C++). It is guarnteed to work (by work, I mean it doesn't do anyting). Deletion has no effects if the argument is a null pointer. The compiler that the presenter describes did not conform to the C++ standard. The described compiler also was...
68,961,080
68,961,116
What does cstdint stand for?
I know the purpose of cstdint as a header to provide more accurate descriptions for numbers, but what does the actual header name stand for? I have a hard time remembering shortened names, especially in programming, when I don't know what the full name is. I imagine it's something like "c standard type defintions integ...
"C standard library integer support header" is a reasonable description. The c prefix indicates that it's a carryover from C, where it is called <stdint.h>. It's standard practice for C headers named <foo.h> to be named <cfoo> in C++. The std part is because it's part of the C standard library, and parallels other C ...
68,961,415
68,961,514
Breaking out of loop from function after printing the last prime number of a given range
I'm writing a code to find the last prime number of a given range. Suppose the range is 1 to 50. Then the last prime no. I want to print must be 47. My idea was to maybe reverse the order of prime numbers in the range and then try printing only the first value. Again kinda like if my order was 1 to 50 then I would star...
You can just use exit() in the place you want to end the program, and it works fine in your case. But by far the best approach is returning a value to test for continuation, it is the most readable. #include<iostream> #include <stdlib.h> using namespace std; int prime_bef(int n) { int check = 0; for (int i = 1; i <= n...
68,961,677
68,963,967
Longest substring that appears at least twice in O(n.logn)
Problem: Given a String S of N characters (N <= 200 000), find the length of the longest substring that appears at least twice (the substrings can overlap). My solution: Here's what i've tried: int main() { std::string s; std::cin >> s; int max = 0; typedef std::string::const_iterator sit; sit end =...
Suffix tree is an overkill for this problem. In fact, binary search suffices and the implementation is much easier. Idea The idea is simple: If there exists a duplicated substring of length N (N > 1), there must also exists one of length N - 1. Therefore, if we let f(x) to denote a function that returns true if there e...
68,961,917
68,962,211
Why `std::array` doesn't offer bit packing for boolean values like what `std::vector` does?
As far as I know std::array doesn't pack bits for boolean values like bitset but std::vector does, but I cannot find any explanation for this online. Why did the C++ developers decide not to do this?
Q: Why does std::vector pack bits? A: Poor design. Q: Why doesn't std::array pack bits? A: Learned from the previous mistake.
68,962,767
68,962,938
Performance difference between string concat by using str += "A" or str = str + "A"
I want to know why str += "A" and str = str + "A" have different performances. In practice, string str = "cool" for(int i = 0; i < 1000000; i++) str += "A" // -> approximately 15000~20000 ms for(int i = 0; i < 1000000; i++) str = str + "A" // -> 10000000 ms According to what I've looked for, str = str + "A" have to...
In very short terms, str += "A" will result in less assembly being generated (x86-64 gcc 11.2): lea rax, [rbp-96] mov esi, OFFSET FLAT:.LC1 mov rdi, rax call std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::operator+=(char const*) While str = str + "A" will result in this...
68,962,815
68,967,634
Perfect forwarding constructor and inheriting constructors
Given this class hierarchy: #include <iostream> class Base { public: Base() = default; Base(const Base&) { std::cout << " copy\n"; } template<typename T> Base(T&&) { std::cout << " T&&\n"; } }; class Sub : public Base { public: using Base::Base; }; It is known that this code would print T&...
This is CWG2356: the inherited constructor is still a better match for a non-const input (because of the qualification conversion required), but it is discarded by [over.match.funcs]/8. Part of the reason for this is to avoid making any class that inherits constructors implicitly convertible from its base class. There...
68,962,880
68,963,269
The correct way to initialize a buffer
Which of these is the correct way to initialize a buffer to zero? WCHAR szBuffer[100]={}; WCHAR szBuffer[100]={0}; WCHAR szBuffer[100]={'\0'}; WCHAR szBuffer[100]{}; WCHAR szBuffer[100]; wmemset(szBuffer, '\0', 100);
All of them are equivalent. I would avoid (2) and (3) though, because to some they give a false impression that you can put any character in there to fill the array with it, while in reality it only controls the first character of the array, the rest are always zeroed.
68,963,052
68,963,184
Visual Studio 2019 is it possible to output file to upper case?
Is it possible to output a file always with upper case file name? For example if I use the effect compiler: Can I make my output .cso files always to upper case, no matter in the (Filename) is lower or upper case?
Yep, you can use a subset of the .NET functions in MSBUILD as described here: https://learn.microsoft.com/en-us/visualstudio/msbuild/property-functions?view=vs-2019 In your case this should work: $(OutDir)shaders/$([System.String]::Copy('%(Filename)').ToUpper()).cso Just make sure you delete existing files with the sa...
68,963,345
68,964,076
problem with [] operator when using a vector
I'm trying to make a copy constructor for Game. throughout the copy constructor I have to copy the elements of one game into another. However when I try to access the inner elemnts of the game I want to copy I get an error saying : no operator "[]" matches these operands -- operand types are: mtm::Game [ std::_Vector...
The [] operator of a vector expects a size_t argument. You are passing an iterator which is why it doesn't compile. other[row][col] can be replaced with just *col. game[row][col] is a little more tricky, you can't use the row and col iterators with game as they are from a different container. You can convert the iterat...
68,963,826
68,965,818
Returning an object by value which should conceptually not be copied
I'd like to have an object whose constructor acts as a begin() and it's destructor acts as an end(), and provides functions that are only valid between these two calls as methods. However... I also want to use named constructors, and also have functions that act as factories for this object too. // this is the object I...
So this is what I had in mind. You can run this and see the console output. It's a moveable only type (if you attempt to copy you'll see a compiler error about a deleted function). It prevents sending the command to the thread if the object has been moved from. class DrawCommand { public: explicit DrawCommand( std...
68,964,170
68,966,905
Changed QGuiApplication to QApplication resulted in unresolved errors
The reason why I made the change is because I needed to use QtWidgets. I've been trying to build the project however I keep getting the following errors: 18:37:58: Starting: "C:\Qt\Tools\CMake_64\bin\cmake.exe" --build C:/Users/user/Desktop/build-project-Desktop_Qt_5_15_2_MinGW_64_bit-Debug --target all [1/4 11.1/sec] ...
Turns out I wasn't linking the Widgets library. target_link_libraries(project PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Quick Qt${QT_VERSION_MAJOR}::Widgets)
68,964,243
68,964,290
How to elegantly pass long type name to template parameter?
I am using c++17. I have some code that looks like this: typedef uint64_t z_hash_t; struct MoveEdge { uint64_t dest_hash; uint32_t times_played; uint32_t move_key; std::string pgn_move; }; struct OpeningTablebase { std::unordered_map<z_hash_t, std::shared_ptr<std::vector<MoveEdge>>> m_tablebase; }; void fo...
You almost got it. You are looking for decltype: void foo() { auto root = m_tablebase.find(m_root_hash); // VVVVVVVVVVVVV std::queue<decltype(root)> to_visit; to_visit.push(root); }
68,964,460
68,964,487
Why std::unique_ptr is not compatible with assignement operator?
For example: std::unique_ptr<int> int_ptr = new int(10); // error: conversion from ‘int*’ to non-scalar type ‘std::unique_ptr’ requested std::unique_ptr<int> pointer(new int(10)); // this work fine
Both of them are initialization, but not assignment. The 1st one is copy initialization, the 2nd one is direct initialization. The constructor of std::unique_ptr taking raw pointer is marked as explicit, it could be used in direct initialization but not copy initialization. explicit unique_ptr( pointer p ) noexcept; ...
68,964,469
68,964,774
Best approach to Independently Timing each Tick of a For Loop in another Thread
Suppose I have a client thread and a server thread. The client thread must perform an expensive for loop operation which is prone to hanging. Thus, the server has independently determine whether each tick of the for loop has exceeded the max time. The context behind this is that the server will timeout the client if it...
One way of doing this might be: Shared vars: std::vector<std::chrono::time_point<std::chrono::high_resolution_clock>> ledger; std::mutex ledger_mtx; Client: for (int i = 0; i < 10; i++) { { std::scoped_lock lock(ledger_mtx); ledger.push_back(std::chrono::high_resolution_clock::now()); } // Do work ...
68,964,644
68,965,722
Storing 3D Array on Heap as Structure Member
I recently started working with C++ for numerical computations where I want to use a Struct Operators to store 3D Fields over the course of the simulation. I create the 3D arrays on the heap with const unsigned int RES = 256; auto arr3D = new double [RES][RES][RES]; because from what I've tested this approach is faste...
The error message returns the correct declaration, std::complex<double>(*wfc)[RES][RES];. const unsigned int RES = 256; struct Settings {}; struct Operators { public: std::complex<double>(*wfc)[RES][RES]; // edited, see 'spitconsumers' comment Operators(Settings& set) { // just another structure...
68,964,778
68,965,012
Boost Spirit X3 parse grammar a^(2n+1)
I am using Boost Spirit X3 to parse some grammars but I encountered some errors which I can not explain. The code below is the simplified version of what I am trying to do. #ifndef BOOST_SPIRIT_X3_NO_RTTI #define BOOST_SPIRIT_X3_NO_RTTI #endif #include "boost/spirit/home/x3.hpp" #include <iostream> #include <string> ...
It's the grammar. To help you diagnose the issue I'd suggest debugging it: Live On Coliru #define BOOST_SPIRIT_X3_DEBUG #include <boost/spirit/home/x3.hpp> namespace x3 = boost::spirit::x3; // Grammar for the language: a^(2n+1) // S -> aPa // P -> aPa | a constexpr auto P = x3::rule<struct P_id>{"P"}; constexpr a...
68,964,852
68,965,524
List/Vector iterator wont change const reference attribute in a derived class
new to c++. I dont know (cant find the right search terms) why the following happens. Basically the Parent class has a member inputs. The Child class has a const reference to Parent::inputs and a Child::set_inputs() method to alter Parent::inputs. When I have a std::list<Child> or std::vector<Child> to which i iterate...
The default copy-ctor is establishing the reference input from one instance to another. You're making copies of your child objects when you put them in your container. In other words, the input members of your container copies still reference the inputs members of you test1, test, etc. instances. Therefore when calling...
68,965,384
68,965,438
c++ How to read a wchar_t* to into a std::wsting variable and print in HEX
In main I have a wstring mystr that contains unicode characters. int main() { std::wcout << std::hex << 16 << endl; std::wstring mystr = L"abc - "; result = myfun(mystr); // here I want to print out my variable result //std::wcout << hex<<result; } I also have a function myfun which takes this wstring...
Use a std::wstringstream: Edit: Edited to use range-based for loop. std::wstring myfun(std::wstring const& mystr) { std::wstringstream out; for (auto const& ch : mystr) out << "(" << std::hex << static_cast<int>(ch) << ")"; return out.str(); }
68,965,515
68,969,005
How is C++ syntactic evolution managed?
Separate from frontend implementers' experiences, are there formal standards that syntactic extensions to the C++ grammar are required to meet? That is, are proposed extensions subjected to any form of mechanical analysis before being accepted? I ask because I have read that the two most widely used C++ compilers, g++...
The C++ standard defines a language; it does not restrict what that language might become in the future. (The C standard does contain a section called "future directions", but that is more a warning to users of features which have been deprecated, and which identifiers might be reserved in the future, rather than being...
68,967,361
68,967,637
Is it legal to get access to protected base class via a friend of additional child class in C++?
Consider we have some third party library with a class B derived from A using protected inheritance. So having an object of B we may not normally access its base A. But we can create some additional class C (no objects of which will ever be constructed) deriving it from B and declare its friendship with the function th...
But is it well formed (no undefined behavior)? Yes undefined behavior. [expr.static.cast] (emphasis mine) 2 An lvalue of type “cv1 B”, where B is a class type, can be cast to type “reference to cv2 D”, where D is a class derived from B, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. I...
68,967,408
68,978,651
Failed to find Qt component "Widgets" config file at ""
I'm setting up a new computer as development machine and working with cmake that worked just fine on another computer. I have installed Qt6 to my home directory, whereas on the old computer, it was installed into the /opt directory. Here is what CMakeLists.txt file looks like: set(Qt_DIR "~/Qt/6.1.2/gcc_64/lib/cmake/"...
The Trolltech installer does not check for dependencies during installation, instead the dependencies are checked in find_package(qt_module). And if the dependencies are not found, then find_package(qt_module) will fail without error messages. Thus, you should make sure that the system has all the required development ...
68,967,844
68,967,936
use of enum on shift bytes in c/c++
I want to create specific byte - uint8_t to set it in a register. This byte consists from 2 sections. Bits <7:6> is a multiplication factor. These 2 bits can be: 00 for multiplication with 1 01 for multiplication with 4 10 for multiplication with 16 11 for multiplication with 64 for these 2 bits i am using an enum like...
typedef enum{ FACTOR_1 = 0, FACTOR_4 = 1 << 6, FACTOR_16 = 2 << 6, FACTOR_64 = 3 << 6, }MultiFactor; uint8_t val = MultiFactor::FACTOR_16 | timeValue; if you need to clear bits 6:7 in the time value before ORing uint8_t val = MultiFactor::FACTOR_16 | (timeValue & ~MultiFactor::FACTOR_64);
68,967,891
68,968,021
Why is the compiler allowed to optimize out this busy waiting loop?
#include <iostream> #include <thread> #include <mutex> int main() { std::atomic<bool> ready = false; std::thread threadB = std::thread([&]() { while (!ready) {} printf("Hello from B\n"); }); std::this_thread::sleep_for(std::chrono::seconds(1)); printf("Hello from A\n"); rea...
The author admits in one of the comments below the video that he was wrong: I had thought so, but it appears I was wrong; the compiler cannot hoist the atomic read out of the loop. The advice at @17:54 is still correct — you should still be very careful and beware of situations where the compiler might reorder or coal...
68,968,043
68,968,776
C++ binary reading to dynamic char
Something wrong with my code and I don't know what exactly causes the problem. Source.cpp #include "class.h" int main() { Book book1("At Mountain of Madness", "H.P Lovecraft", 1936); book1.binaryFileWrite(); book1.binaryFileRead(); Book book2("Danwych's horror", "H.P Lovecraft", 1929); book2.binar...
The main problem is that Book contains pointers to data stored elsewhere in memory. When you read/write a Book object the way you are, you are reading/writing those pointers as-is, not the data they are pointing at. So, you need to handle that char* data separately. Also, your binaryFileRead() is not even reading into...
68,968,265
68,969,029
String from boost::asio::ip::tcp::socket weird behaviour
I am trying to implement an application that uses sockets in C++. I'm trying to read the string from the socket, but I'm having all sorts of issues. I can't get the string in the main function, but I can get it in the function. Can anyone point me in the right direction? Here is my code: int main(int argc, char *argv[]...
Yeah, as the others have pointed out, printf doesn't work with std::string. You can easily work around it, but it's perhaps a good idea to write C++ code: std::cout << "Message: " << message << "\n"; // ... std::cout << "Text: " << result << ", and length: " << result.length() << "\n"; std::cout << "Text cas...
68,968,316
68,968,381
Trying to open file dialog with Qt
I'm trying to write a simple C++ code using Qt to grab the path to a folder. I got the code from this answer and tweaked it a bit to fit what I wanted. My problem is that it's flagging my 'this' declaration saying my class is incompatible with the 'QWidget *' parameter type. #include <iostream> #include <qt5/QtWidgets/...
There are several errors in your code: QFileDialog requires a QWidget or a nullptr as the first argument. tr() is a QObject method, since there is none, you must use QObject::tr(). To convert QString to std::string you must use the toStdString() method. Any QWidget(like QFileDialog) requires a QApplication to have bee...
68,968,616
68,968,728
Visual Studio C++ 2019, broken undetailed Intellisense
I'm just starting off with C++, setting up an environment in Visual Studio 2019. As I got used to coding in C# with intellisense, I thought it'd work the same way with C++, however it seems to be broken for me. as you can see, it doesn't provide detailed information about methods (or anything at all) like it does with ...
as you can see, it doesn't provide detailed information about methods It doesn't appear to be broken, c++ intellisense with Visual Studio just doesn't offer the documentation style descriptions that C# may. Though you can provide you own descriptions for methods by adding a comment just before their declaration and i...
68,969,162
68,969,246
Make array part of input directly
I am trying to write my own vector. I have to initialize an array first, then set the value of the vector to the array (block 2). How do I combine these two steps (block 3)? template <class T> class Test{ public: T value Test operator= (T list[]){ ...//value = list[2] ... ... ...//do st...
You need to make initializer for class with 'initializer_list' parameter. Test(const std::initializer_list<T>& Initializer); Then you need to implement it Test<T>::Test(const std::initializer_list<T> &Initializer) { //InnerArray = new T[Initializer.size()]; int i = 0; // There is no indexer for initia...
68,969,217
68,969,269
initialize uint8_t array from txt file
I have, in a .txt file, a uint8_t array already formatted, like this: 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, What I need is to initialize it from C++ like so: static const uint8_t binary[] = { 0x4d, 0x5a, 0x9...
Is the .txt file storing the hex values as bytes, or as 4 characters representing the hex values with literal commas and spaces? If you're storing the actual hexadecimal values, the code becomes as simple as #include <fstream> #include <vector> // input file stream std::ifstream is("MyFile.txt"); // iterators to sta...
68,969,219
68,975,453
Conversion functions, std::is_base_of and spurious incomplete types: substitution failure IS an error
I'm attempting to implement a conversion function operator, and use std::is_base_of to limit the scope of applicability, but I'm running into issues. #include <type_traits> class Spurious; class MyClassBase {}; template< typename T > class MyClass: public MyClassBase { public: template< typename U, std::enable_i...
This isn’t SFINAE, which certainly applies to incomplete types: template<class T,bool=false> struct size : std::integral_constant<std::size_t,0> {}; template<class T> struct size<T,!sizeof(T)> : std::integral_constant<std::size_t,sizeof(T)> {}; static_assert(size<char>::value==1); // OK struct A; static_assert(size<A...
68,969,248
68,969,665
how to format a UTC time string using howardhinnant's c++ date library
Can someone help me to format a date string using Howard Hinnant's excellent date/time library. I am trying to output a UTC date from the current time. The desired format of the date/time is zulu time per: "2018-11-01T15:32:56Z" - i.e. "YYYY-MM-DDTHH:MM:SSZ" - So far using Howard's documentation I was able to get th...
If you're using std::format, then you're using C++20, instead of Howard Hinnant's date/time library. Though the latter is the basis of the C++20 chrono library. Your code should look like: const auto today = floor<seconds>(system_clock::now()); auto dateTimeString = std::format("{:%FT%T}Z", today); The variable today...
68,969,291
68,969,315
XOR between Python and C++
I have scripted a Python script (Python v3.9) to give me the little endian output of a XOR encrypted string. And then I tried to write a C++ program that will decode those bytes by using the same XOR key. My Python script follows. import itertools stringMessage = "TEST STRING !@#" xorKey = "Hello324234523" def xor(me...
Changed for (int i = 0; i < sizeof shellcode; i++) { to for (int i = 0; i < sizeof shellcode - 1; i++) { and it now works!
68,969,313
68,969,641
Generate preprocessor definitions based on CMAKE_CONFIGURATION_TYPES
I want to generate a Visual Studio project with two configurations using cmake. I want cmake to define different preprocessor symbols for these configurations. I generate the project with the following command cmake -B intermediate/cmake -G "Visual Studio 16 2019" -T v142 -DCMAKE_GENERATOR_PLATFORM=x64 In my CMakeList...
The conventional way to handle configuration-specific details in a multi-configuration generator is through the use of generator expressions. Generator expressions allow you to specify symbols, values, flags, etc that will only be expanded at generation time based on the current state of the generator (such as the curr...
68,969,332
68,969,442
Proper use of _mm256_maskload_ps for loading less than 8 floats into __m256
I am having trouble wrapping my mind around which bits need to be set for masking using _mm256_maskload_ps. The documentation states that the mask is the "integer value calculated based on the most-significant-bit of each doubleword of a mask register" Parsing this out, I think that there are 4 64 bit integers. I want ...
A doubleword is 32-bits, not 64. Word = 16, doubleword = 32, quadword = 64. The first two elements get selected because -1 is all ones across all 64 bits, so when the maskload treats it as two 32-bit values instead of one 64-bit value the highest bit of both elements will be set. 0xFFFFFFFF, OTOH, is the least sigif...
68,969,394
68,969,422
What does a typecast at the beginning of an arithmetic expression apply to?
I don't understand how a typecast can sit at the beginning of a binary arithmetic expression. Does it typecast both variables or only one? #include <stdio.h> main() { int sum = 17, count = 5; double mean = (double) sum / count; printf("Value of mean : %f\n", mean ); } Is it casting (double) (sum / count) o...
It is parsed as ((double) sum) / count. Casting one of the operands is a common trick to force floating-point division. int / int would use integral division which truncates the decimal portion. double / int forces the second operand to be coerced into a double as well, resulting in double / double which doesn't trunca...
68,969,445
68,969,518
User-defined literal doesn't work when the body is written in a different .cpp file
I created a user-defined literal like this, in is OWN .cpp file (declared as a friend function in .h file): fraction operator"" _frac(const long double val) { return fraction(static_cast<float>(val)); } But in main it produces this error: Error (active)E2486 user-defined literal operator not found But, when I wri...
The user-defined literal function just is not declared in your main.cpp. Place test operator "" _t(const long double a); in your test.h
68,969,652
68,971,369
enable templated base class only for derived classes
How would I go about doing the equivalent of the following? template < class T, typename = std::enable_if< std::is_base_of< Self, T >::value > > // Can not use std::is_base_of on self class Self { protected: typedef T self; }; class ValidDerived : public Self< ValidDerived > { }; // This should compile because T i...
In CRTP, T is incomplete in class MyClass : Self<MyClass> {};. You can add an extra check in a method which should be called/instantiated (such as constructor/destructor): template<class T> class Self { protected: using self = T; Self() { static_assert(std::is_base_of<Self, T >::value); } };
68,969,702
68,969,792
how many days left between 2 dates using std::chrono
I'm trying to check how many days are left for my application, one from the current time and the second one from a std::string that comes from a database, but every time I try to subtract the 2 dates using std::chrono::duration<int> I get "expected unqualified-d before = token", not sure what is chrono expecting below...
There's two problems, one of which is pointed out by JohnFilleau in the comments. You are assigning to a type instead of to a variable. It is as if you are coding:   int = 3; instead of: int i = 3; You need something like: tiempo t = end - now; You are trying to implicitly convert from the precision of system_c...
68,970,111
74,255,773
How is std::mutex's constexpr constructor implemented?
While looking at the C++ Reference for std::mutex, I noticed that the constructor for std::mutex is marked constexpr. This is surprising at first, since we usually have to make a system call (either pthread_mutex_init() (POSIX) or CreateMutex() (Windows)) to initialize a mutex. However, on closer inspection, for POSIX...
On Windows, it is possible to implement std::mutex as constexpr using SRWLOCK. Unfortunately full SRWLOCK is available starting in Windows 7. It was introduced in Windows Vista, but without the ability to implement try_lock using it. Visual Studio 2022 has dropped Windows Vista support, so it could have switched to SRW...
68,970,147
68,970,356
Why does char occupy 7 bits when the length is 1 byte ie 8 bits?
I've seen that the below program is taking only 7 bits of memory to store the character, but in general everywhere I've studied says that char occupies 1 byte of memory ie is 8 bits. Does a single character require 8 bits or 7 bits? If it requires 8 bits, what will be stored in the other bit? #include <iostream> using ...
Your first code sample doesn't print leading zero bits, as ASCII characters all have the upper bit set to zero you'll only get at most seven bits printed if using ASCII characters. Extended ASCII characters or utf-8 use the upper bit for characters outside the basic ASCII character set. Your second example is actually ...
68,970,223
68,970,272
Compile time floating point division by zero in C++
It is well known, if one divides a floating-point number on zero in run-time then the result will be either infinity or not-a-number (the latter case if the dividend was also zero). But is it allowed to divide by zero in C++ constexpr expressions (in compile time), e.g. #include <iostream> int main() { double x = ...
Division by zero is undefined behavior. (So anything goes) http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdf Section 8.5.5, point 4
68,971,068
68,971,256
Why is type checking not happening for std::function?
#include <functional> void toggleOk(bool& b) { b = !b; } void toggleBroken(bool b) { b = !b; } void toggleInt(int i) { i = !i; } void tooManyParams(bool b, int i) { i = !b; } int main() { typedef std::function<void(bool&)> CallbackType; typedef std::function<void(bool)> WrongCallbackType; CallbackType cb...
Yes, this is defined behavior from std::function The std::function uses a type erasure mechanism to warp almost all kinds of callable objects, and parameterized to the non-const, non-ref non-volatile arguments and the return type of the callable. You need to use plane typed function pointer to get the expected errors i...
68,971,130
68,971,157
Getting kth digit in a string concatenating all natural numbers
I have an infinitely long string "12345678910111213141516171819202122232425..." which is a concatentation of every natural numbers in ascending order. I want to find the kth character in the string. However, my program is giving me incorrect output despite the logic being correct. I suspect an implementation bug somewh...
It's almost correct but it seems that you do not have to minus 1 in ans += (k - 1) / digit - 1, changing it to ans += (k - 1) / digit should work. Output: 7 4 1
68,971,688
68,981,655
VS2019 Output Window Comes with lot of whitespace
I don't think this question has been asked before, but here it is: When I run my program in VS2019, the output window executes properly, depending on errors. But this time I am creating a program, which depends on the fullscreen console output window columns and rows length. But I've noticed that the number of columns ...
I suggest you could try to use SMALL_RECT structure to specified console screen buffer. I suggest you could follow the following code: #include <stdlib.h> #include <stdio.h> #include <iostream> #include <Windows.h> #include <string> using namespace std; int main() { SetConsoleDisplayMode(GetStdHandle(STD_OUTPUT_HA...
68,971,715
68,971,924
When I change array to vector, the program is abnormal
When I use an array, the following code works well. I tried to replace array with std::vector, but found that procedures often appear abnormalities, need to run more times. Anything I missed? I am using g++ 10.3. #include <iostream> #include <vector> int main() { int n = 3; for (int k = 1; k <= 4; ++k) { // ...
In this for loop in its third part for (; i >= 0; A[i]++) { ^^^^^^ the variable i can be equal to -1 after the inner loop for (i = k - 1; i >= 0 && A[i] == n - 1; i--) where the same variable i is used (for example when k is equal to 1). So it is unimportant whether you are using a vector or an array....
68,971,870
68,973,078
Overloading Function Templates for C-strings
The following snippet code is an example from book c++ templates. My question is why the the statement return max (max(a,b), c) in the last line becomes a runtime error. Could anyone give me some hints? Thanks! #include <cstring> // maximum of two values of any type (call-by-reference) template<typename T> T const& max...
char const* max (char const* a, char const* b) returns an const char * variable by value. Then T const& max (T const& a, T const& b, T const& c) creates a temporary variable that stores that value and returns a const& reference to it (with T = const char *). That temporary pointer does not exist, when auto m2 = is assi...
68,972,565
68,973,452
Install and run c++ program on machine that doesn't have a compiler
I have made a small c++ program using glfw, glut and dearImgui on linux machine. As i know, i have written this program so it should build on windows as well. I would like to send this program to my friend who's running windows and doesn't have a compiler. How is it possible to build a program on a computer without a c...
Yes, you can make an installer for your c++ project that should allow your someone on windows to simply install and run it. There are multiple options for doing this but the first way that comes to mind for me is using cmake with cpack, but that would take learning how to use both, which, if you plan on continuing to ...
68,972,704
68,972,748
Overloading Function templates Rules
The following snippet is from the book C++ templates 2nd edition. template<typename T1, typename T2> auto max (T1 a, T2 b) { return b < a ? a : b; } template<typename RT, typename T1, typename T2> RT max (T1 a, T2 b) { return b < a ? a : b; } auto b = ::max<long double>(7.2, 4); // uses second template My question is...
For the 1st overload, if T1 is specified as long double, and pass 7.2 which is a double, the implicit conversion from double to long double is required. For the 2nd overload, RT is specified as long double, and T1 will be deduced as double, so it's an exact match and wins in overload resolution. If you specify template...
68,972,957
68,973,428
Passing an array of pointers to child objects to a function that takes an array of pointers to parent objects
I want to do what's said in the title but I run in the following error: error: invalid conversion from ‘Child**’ to ‘Parent**’ [-fpermissive] For clarity, here is my parent.hpp file: #ifndef PARENT #define PARENT class Parent { //something }; #endif Here my child.hpp file #ifndef CHILD #define CHILD #include "p...
Passing an array of pointers to child objects to a function that takes an array of pointers to parent objects You then need to create an array of Parent* that you populate with Child*s. Example: class Parent { public: virtual ~Parent() = default; }; class Child : public Parent {}; void func(Parent *p[]) { /...
68,973,060
68,974,493
OpenCL : incompatible integer to pointer conversion passing
I wrote the following kernel code, but it gave me the following warning. I have tried different solutions but failed. plz any suggestion would help `26:48: warning: incompatible integer to pointer conversion passing '__global int' to parameter of type 'int *' array_dist[i] = Euclidean_distance(X_train[i], ...
__global int* and int* for the function parameter (identical to __private int*) are different memory spaces. __global is video memory and __private is registers on the silicon of the GPU die. To get rid of the warning, in your Euclidean_distance function, make both array_point_A and array_point_B type __global int* res...
68,973,103
68,973,255
How to create outline
I have a set of points , which is in shape of a line. How can we create new set of points which would be at a offset distance from the current set of points and using GL_TRIANGLE_STRIP we would be able to create a polygon shape. This is my current code but I could not get any meaningful result from it. // outlineVert...
You have to compute the Miter joint between 2 line segments. To do this, you need to calculate the vectors along the line segments to be connected. Calculate the normalized normal vectors to the line segments. The vector along the miter joint is the sum of the normal vectors. (You can even do this in the vertex shader:...
68,973,407
68,973,838
Call std::visit with passed lambdas
I have a struct that contains a variant. I want to write a member function for that struct that should run code depending on which type variant currently holds. However, I have issues making it compile. I don't want to use more "template shenanigans" like using a separate struct to define operator(T&) since it pollutes...
Your problem is that std::visit() needs a "visitor" that must handle every type of the std::variant. However, I have issues making it compile. I don't want to use more "template shenanigans" like using a separate struct to define operator(T&) since it pollutes the syntax even more. There is nothing complicated. You c...
68,973,757
68,973,793
Is unique_ptr faster than raw pointer? C++
I was experimenting with the benchmarking here and found weird results. Apparently creating and deleting raw pointer is slower (according to my measurements of course) than creating unique_ptr, how is this possible? struct deleter { template<typename T> void operator()(T* ptr) { delete ptr; } ...
Is unique_ptr faster than row pointer? No. how is this possible? Benchmarking is difficult. It is possible to measure differences that are caused by incidental differences in memory layout.
68,973,866
68,974,101
C++ - Convert vector<uint64> to a single number
There is a method to convert a std::vector<uint64> to a single number? I have a vector like this: v[0] = 0; v[1] = 6796890219657246832; Or like this: v[0] = 16377; v[1] = 2631694347470643681; v[2] = 11730294873282192384; The result I like to get is, in the first case 6796890219657246832 and in the second: 16377263169...
No C++ provided types will support that many digits. So obviously, you need BIG-INT for that. Ethier implemented by yourself or using a tested library like GMP. For example, using GMP will be like: static mpz_class convert_to_i(std::vector<std::size_t> const& vec) { std::string sum; for (auto const numb...
68,974,103
68,974,143
Is there a version of offsetof that applies to methods?
Given the struct: struct Struct { int _a; int a () { return _a; } }; One is able to get the offset of _a with offsetof( Struct, _a ). How would I go about doing the same for something like &Struct::a?
Quoting from cppreference.com's page on the offsetof macro: (emphasis mine) Given an object o of type type and static storage duration, o.member shall be an lvalue constant expression that refers to a subobject of o. Otherwise, the behavior is undefined. Particularly, if member is a static data member, a bit-field, or...
68,974,500
68,974,528
What is @ in C++ and why it is used in C++ header files?
I was looking into the queue header file of C++ and found a piece of code. PIECE OF CODE FROM QUEUE HEADER FILE #include <debug/debug.h> #include <bits/move.h> #include <bits/predefined_ops.h> namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @defgroup heap_algorithms Heap * ...
@ is not part of the C++ language. Any characters can be used in comments. Comments can have markups that can be processed by 3rd party processors. In this case, @ is most likely for Doxygen. Here is an example of the markups in the comments above: Heap [Sorting]. Another example of markup in comments is XML Documentat...
68,974,977
68,975,682
Are destructors of library types well defined?
For example the iterator type - here I need to have a polymorphic iterator of different types depending on the usage. So I create a union with user defined constructor and destructor: I'm specifically questioning the destructors names (eg. ~iterator()). #include <list> #include <string> struct val_origin { union {...
Name lookup for destructors is very subtle to support things like typedef-names for non-class types. There’s no guarantee, though, that iterator is available here since the iterator need not be a class type named iterator (or reverse_iterator) so as to provide that as an injected-class-name and since there’s no declar...
68,975,049
68,979,202
Program getting stuck
I have written a program for Round Robin Scheduling for CPU processes. The program was working fine before, but all of a sudden, the program stops working after several lines of code. I have tried to restart the Dev C++ app but the issue still persists. Is something wrong with my code? #include<iostream> #include<vecto...
You have the wrong logic in the for iteration loop. The point is that your program iterates through this loop endlessly. After the first two loops, your entered data does not satisfy any condition, and i always resets to zero, so the program is constantly checking for the same unsuitable data.
68,975,057
68,975,157
Trying to read in a CSV file and print to console c++
I haven't programmed in a while and am trying to work on a project which will read in tweets from a csv file and then manipulate what is stored. Currently, I am trying to just extract the data from the file and print to the console. I know that my file is opening because I had included a conditional statement, however,...
I know that my file is opening because I had included a conditional statement, however, when it comes to reading the data rather than getting any actual information I am just getting blank lines. You never initialize the line variable anywhere inside your code so lineSS is initialized with an empty buffer. Consequent...
68,975,185
68,975,383
How to sort vector in c++
I have some vectors like this: vector<int> vec {3;0;1;0;5}; vector<int> vec1{3;2;1;7;5}; I want to sort them in ascending order but, if they contain any elements that are zero, the must be moved to the end of the vector. My desired result is: vector<int> vec {1;3;5;0;0}; vector<int> vec1 {1;2;3;5;7}; I used the f...
Your sort algorithm should take into account a zero in either position. So, if b is zero, then return true if a is not zero, or false if a is also zero†; otherwise, if a is zero, return false; otherwise (neither is zero), return the result of the normal comparison. Here's a working example, using your data (note also t...
68,975,325
68,975,394
The function collects the array and returns it. After ciout memory is still occupied by this array, right?
I have the following function: void setFore(const short arg) { char ansicode[12] = "\e[38;5;"; char code[4]; snprintf(code, 4, "%d", arg); strcat(ansicode, code); strcat(ansicode, "m"); std::cout << ansicode; } Using it looks like std::cout << "Some text"; setFore(...
But one question remains, will the memory occupied by the ansicode array continue to occupy the memory? C-style arrays have automatic lifetime, they will get destroyed after the local scope ends, so it is undefined behavior to try to do anything with them after the function has returned, you should consider using a c...
68,975,644
68,975,730
making vectors of an object independent of each other
I have a question regarding vectors, shared_ptr, and copy c'tors. class Character { int health;//and more stuff that aren't important for the sake of this question //more code... } class Game { int size; vector<shared_ptr<Character>> board; } When I do this: Game game1 = (53,...)//say that I gav...
game2 will contain copy of vector in game1. It will basically copy all its std::shared_ptr. However, copy of std::shared_ptr means only, that internal ref count will be incremented, object which it points to will be the same as in the original std::shared_ptr. Example: std::shared_ptr<Character> ptr1 = std::make_shared...
68,976,022
68,976,141
filesystem value_type pointer to string?
I have a directory_iterator and I want the filename but I can't seem to get anything to work, it just throws an error saying that value_type* cannot be converted into a string. I can't cast it to a string and std::to_string() doesn't work either! for (auto& p : std::experimental::filesystem::directory_iterator(dir)) { ...
A range-for loop uses an iterator to enumerate a sequence of elements, dereferencing the iterator on each loop iteration to access the next element in the sequence. When a filesystem::directory_iterator is dereferenced, it yields a filesystem::directory_entry, which has a path() method (and a conversion operator) for r...
68,976,153
68,976,167
Convert Little Endian to Big Endian - Not getting expected result
I have a very small code where I am trying to convert a 16 bit number from little endian to big endian format. The value of number is 0x8000 and after conversion I am expecting it to be as 0x0080 - but I am getting some different value as mentioned below: #include <iostream> int main() { int num = 0x8000; ...
If you do 0x8000 << 8 you'll get 0x800000. If you | that with 0x80 you get the answer you now get. You need to filter away the upper part: int swap = (num>>8) | (0xFF00 & (num<<8)); Suggestion: Use fixed width types, like uint8_t, uint16_t, uint32_t and uint64_t.
68,976,173
68,976,217
What does bool(T::* ...) do?
From ROS 1's node_handle.h, a certain API is specified as: template<class T, class MReq, class MRes> ServiceServer NodeHandle::advertiseService(const std::string &service, bool(T::*srv_func)(MReq &, MRes &), T* obj) srv_func is a callback for this service, MReq is a request class, MRes is a result class. obj is becaus...
template<class T, class MReq, class MRes> ServiceServer NodeHandle::advertiseService(const std::string &service, bool(T::*srv_func)(MReq &, MRes &), T* obj) This is a function template. T, MReq and MRes are template type parameters of the template. (const std::string &service, bool(T::*srv_func)(MReq &, MRes &), T*...
68,976,416
68,976,454
What if the function would return a pointer to a char array and I would not use it
So, for example i have this function: char* retCharPtr(void) { char data[15] {"Data is here"}; return data; } And char* retCharPtr1(void) { char *data = new char[15]; strcat(data, "Data is here"); return data; } Please explain where the data array will be placed if std::cout << retCharPtr1();, and...
When a function returns a value, that value exists as a local variable within the caller's current scope (whether the caller uses it or not), and will be destroyed when the variable goes out of scope. So, in your examples, the returned char* pointer (but not the data being pointed at) is destroyed on the ; following t...
68,976,726
68,976,919
Hash map of struct keys and getter functions
I have a nested struct (simplified): struct Person { struct JobDetails { std::string company_name; std::string address; }; JobDetails job_details; int32_t age; std::string name; }; Is it possible to create a hash map of keys and getters (functions) for each struct field, even for nested ones? E.g. s...
Somewhat. You'll want std::function<something> as the map's value type to be able to store a variety of lambdas. The harder issue is that every expression must have a single type known at compile time. If I have a std::string key;, then the expression hash_map[key](person) could be either a std::string, or an int32_t, ...
68,977,087
68,977,336
C++ How to use dlopen() in c++?
I am trying to use the prebuilt tensorflow c-api with a cpp-wrapper in my package. Unfortunately I am getting a segfault error. After searching I found out that there is a Git Issue about it: Linking to both tensorflow and protobuf causes segmentation fault during static initializers. So I could resolve the Issues by d...
A little dlopen example: Some lib written in C, we call it foobar.so #include <stdio.h> void foo() { printf("foo\n"); } void bar() { printf("bar\n"); } gcc -o foobar.so foobar.c -shared -fPIC A (foobar) wrapper in C++ #include <dlfcn.h> struct FooBar { typedef void (*foo_handle)(); //same signature as in the l...
68,977,090
68,977,250
smart pointer as argument of function which uses std::function, std::bind
#include <functional> #include <iostream> #include <memory> template <typename T> struct Message { T a; }; template <typename T> class Connection : public std::enable_shared_from_this<T> { typedef std::function<void(Message<T>&)> msg_handle; public: void SetHandle(msg_handle handle) { handle_ = ...
std::enable_shared_from_this requires you specify the type of the class that is to be enabled, and is deriving. You mistakenly specify T, when the class you are enabling is Connection<T>. The error is pointing out (indirectly) that the hidden weak_ptr member has the wrong type. Simply put, this needs to be your class t...
68,977,239
68,978,570
Efficiency of std::sort() algorithm in sorting std::vector of std::list
The example below is adopted from Jossuttis(2012), with some small changes. Essentially, it's sorting a vector of lists of integers. My questions are as follows: Is the std::sort() algorithm sorting the pointers (to the lists)? If the answer is no, what's the best way to still use std::sort() to sort a vector of (smar...
Is the std::sort() algorithm sorting the pointers (to the lists)? No, neither in c++11 or c++03. The difference is the since c++11, move semantic is used in sorting. I think what you are actually asked is about move semantic. For std::list, they are moveable, and in the implementation of std::sort, the element swap is ...
68,977,311
68,977,358
How can a pointer to double that is 4 Bytes point to double that is 8 Bytes?
I have this naive question: A double is 8 Bytes even on 32 bit machines, also long long, and we know that the pointer size on that implementation is just 4 Bytes. Because that has a relationship with the processor's register size. So a processor register must be able to address any data type. Here is my code, run with ...
Q: So how can the a pointer to double of 4 Bytes point to 8 Bytes (double object)? A: Because the "pointer" is different from what's being "pointed to". Think about it: Your "pointer" can point to a double ... a float ... a char. Q: Does this mean double works more effectively on 64 bit systems than on 32 bit ones? Tha...
68,977,576
68,977,686
C++ error [1] 41387 illegal hardware instruction
I am writing a program to take in a user value, return a changed version back. When it builds fine, but when I run it and insert a word I get an error saying "[1] 41387 illegal hardware instruction". I am new to C++ so I'm not sure what to do, let me know if I need to explain more using namespace std; string isFemi...
countryName.length() returns the value of how many characters are in a string. If the string was abc, the length of the string would be 3. Because C++ arrays start from 0, this would be out of bounds. You can fix this by simply just changing countryName.length() to countryName.length() - 1.
68,977,591
68,977,634
error: no matching function for call to 'DollarAmount::DollarAmount(<brace-enclosed initializer list>)'
I'm receiving this error from g++: error: no matching function for call to 'DollarAmount::DollarAmount(<brace-enclosed initializer list>)' I also get notes from gcc saying that less arguments were provided than expected and there is no known conversion for argument 1 to const DollarAmount&. I've tried looking at the ma...
The error is in the addInterest() method, where you create a DollarAmount using an initializer list with only one value, while the only defined constructor takes two values. void addInterest(int rate, int divisor) { //Right Here Is What The Error Is About DollarAmount interest { (amount * rate + diviso...
68,977,778
68,978,504
Unexpected output while sending a pointer by reference
So, I was trying out a few things and decided to intentionally remove a return statement from a function supposed to return an int. My guess was, that the function would return a garbage value, and the program would terminate normally. However, the program got stuck in an infinite loop. Is this a bug ? Or am I missing ...
Is this a bug ? Yes. This is a bug in your program. Or am I missing something? Yes. You're missing a return statement. why we are getting this output. Because the behaviour of the program is undefined. This explains all that a C++ programmer needs to know about the behaviour of the program, and it is all that we ...
68,978,146
68,978,165
What can cause a Stack Overflow in this function?
I was writing a casual minesweeper, and wanted to realize a method to track an empty cells at the field, so I had wrote this algorothm: //bigger array was taken to prevent out of range,when init mines and numbers /*creating mines in 1 to FIELD_NUM range(0 -non-active field,1-active field) * { * 0 0 0 0 0 ...
OpenVoidCells doesn't have anything to prevent visiting the same square over and over. It will go north, south, north, south, north, south ... forever, until you run out of stack. You need to keep track of visited squares and avoid re-checking them.
68,978,261
68,992,030
What is the time complexity of this top down dynamic programming code?
I can't analyze time complexity of top down dynamic programming approach like below example. Can you please help me? Problem : Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the diction...
A worst-case bound for memoised DP algorithms can be found by separating out the computational work done inside recursive calls from other work. Specifically we need to determine: The maximum possible number of times that the recursive function gets called with distinct inputs (parameter values) -- this is the maximum...
68,978,294
68,978,569
Determine if the second array is the first array shifted to the right by 1
The question is to determine if the second array is the first array shifted to the right by 1. Examples: simonSays([1, 2, 3, 4, 5], [0, 1, 2, 3, 4]) ➞ true simonSays([1, 2, 3, 4, 5], [5, 5, 1, 2, 3]) ➞ false My code is as follows: bool simonSays(std::vector<int> arr1, std::vector<int> arr2) { for(int i=0; i<ar...
You need to perform an additional check so that you don't access outside the bounds of arr2: // You should prefer const references to avoid copying of the vectors in the parameters bool simonSays(std::vector<int> const& arr1, std::vector<int> const& arr2) { for (int i = 0; i < arr1.size() && i + 1 < arr2.size(); i+...
68,978,698
68,978,712
Unable to access class while method chaining in c++
I'm working on a library and I'm running into weird issues and I'm not sure what's happening. I broke out the core pieces of the classes I'm writing to replicate the issue. The gist is that I've got a couple of classes I'm using to manage groupings of indexes for LEDs in a project. I have a class to keep track of the L...
getSection returns a Section by value, so the calling code gets a brand new copy. You can change your code to return a reference like so: Section& getSection(int index){ return _sections[index]; }
68,978,882
68,979,036
C++ Program Hanging Indefinetely
I have written code to solve a programming problem. To summarise the problem, I have three balls - red, green, and blue. I am given a number k. I have to systematically destroy each ball i.e., destroy one red, then move onto green, destroy one green, then move onto blue, destroy one blue, and then start over from red a...
The program is probably not hanging. Have a look at this, executed on my i9 system: So if we extrapolate until we reach your input: Your program will likely take (on my computer) around 10000s (2.8 hours) to run! You are going to need to approach this issue differently, perhaps look into a mathematical or logical app...
68,978,930
69,007,148
How to access individual frames of an animated GIF loaded into a ID3D11ShaderResourceView?
I used CreateWICTextureFromFile() from DirectXTK to load an animated GIF texture. ID3D11Resource* Resource; ID3D11ShaderResourceView* View; hr = CreateWICTextureFromFile(d3dDevice, L"sample.gif", &Resource, &View); Then I displayed it on an ImageButton in dear IMGUI library: ImGui::ImageButton((void*)View, ImVec2(...
The CreateWICTextureFromFile function in DirectX Tool Kit (a.k.a. the 'light-weight' version in the WICTextureLoader module) only loads a single 2D texture, not multi-frame images like animated GIF or TIFF. The DirectXTex function LoadFromWICFile can load multiframe images if you give it the WIC_FLAGS_ALL_FRAMES flag. ...
68,979,142
68,979,284
Why are these two numbers comparing equal?
I'm wondering why it's the case that these two numbers are comparing equal. I had a (maybe false) realisation that I messed up my enums, because in my enums I often do: enum class SomeFlags : unsigned long long { ALL = ~0, FLAG1 = 1, FLAG2 }; And I thought that 0 being an int and being assigned to an unsigned long lon...
cppreference: "The result of operator~ is the bitwise NOT (one's complement) value of the argument (after promotion." No promotion (to int or unsigned int) is however needed here - but flipping all bits in a signed type with the value 0 will make it -1 (all bits set) which when converted to an unsigned type will be the...
68,979,830
68,979,938
problem with operator[] when trying to access a vector of shared_ptr
I have the following class : class Character { /unimportant code } class Fighter : public Character { /unimportant code } class Healer: public Character { /unimportant code } class Game { public: void move(const GridPoint & src_coordinates, const GridPoint & dst_coordinates); //there are more ...
Iterators are a generalization of pointers. You use * to get the pointed-at thing from a pointer; you use * to get the element of a container that an iterator is currently "pointing at". The iterator type uses operator overloading so that it can behave like a pointer, even when the underlying container isn't a simple a...
68,980,215
68,981,591
I have some kind of Schrödinger variable
I'm creating a lexer and I need to compute things. I created my compute function which takes three arguments: the two strings value and the operator. For instance when I do compute("34","63","+") it returns "94". But when comes the time to compute I first have to convert some values into int or float: if(is_int(val...
What you are looking for is called a variant or a tagged union/algebraic sum type. It goes by many names, but the pattern of "represent a single value that could be 1 of N types" is very common in programming languages and is usually hard-coded into variables (Python, Ruby, Lisp, JavaScript, etc.) or represented throug...
68,980,250
68,985,565
Why does std::initializer_list in ctor not behave as expected?
#include <vector> int main() { auto v = std::vector{std::vector<int>{}}; return v.front().empty(); // error } See online demo However, according to Scott Meyers' Effective Modern C++ (emphasis in original): If, however, one or more constructors declare a parameter of type std::initializer_list, calls using t...
Meyers is mostly correct (the exception is that T{} is value-initialization if a default constructor exists), but his statement is about overload resolution. That takes place after CTAD, which chooses the class (and hence the set of constructors) to use. CTAD doesn’t “prefer” initializer-list constructors in that it p...
68,980,359
68,997,851
CMake cannot set CUDA standard c++17
I'm using CMake to configure a CUDA/C++ project. Some of the files compiled with NVCC require C++ 17 features. To enable those, I would use: cmake_minimum_required(VERSION 3.19) project(RISA LANGUAGES CXX CUDA) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CUDA_STANDARD 17) which results in an error message: Target "RISA" requ...
As is turns out, CMake was not using the correct nvcc binary. In my case, I've had two versions of nvcc on the system: nvcc v10.1.243 in /usr/bin and nvcc v11.2.152 in /usr/local/cuda-11.2/bin In my CMake configuration, CUDA_NVCC_EXECUTABLE was set to /usr/local/cuda-11.2/bin, but CMAKE_CUDA_COMPILER was set to the ...
68,981,028
68,981,085
Preprocessor macro definition of a macro definition
The C++ standard has a way of converting the function a line is in into a char array, but it doesn't take account of class qualifications (doesn't include outer classes the function is nested in. However there are a bunch of compiler extensions that do, and do other things like include the function signature. I wanted ...
can I rely on this working every time? Yes. Is it a standardised feature of the C++ preprocessor (or is it C?) Both. it does something like this: Generally, basically, let's say yes. Macros are expanded upon use. The result of expansion is "rescanned for more macro names to replace", let's say recursively with so...
68,981,340
68,985,001
How to detect floats when input is expected to be integer?
How can I detect when a float number is inputted ? I have written a program as below. When inputting values for the number of quarters such as 5. The output is 5. Which is expected. When I input 5.5 The output is 5. This is incorrect as it's impossible to get 0.5 of a quarter. Is this an issue with the way, values are ...
#include <iostream> #include <regex> #include <string> #include <cmath> bool is_valid_coin_amount(const std::string& input) { // Allow 1 or more characters in range '0'-'9' until end of string // only initialize regex once by making it static (optimization) static std::regex numbers_only("[0-9]+$"); re...
68,981,393
68,981,447
C++ Casting out a int into string
I am planning to change the elements inside the array of my x[] to cast out the number like 1, 2, 3, 4. But once i execute the code. it will show this error message. error: no matching function for call to std::__cxx11::basic_string<char>::basic_string(int&) Please anyone can help me to do anything to change my eleme...
this is the reason of the error: x[i] = (string)i; read here: how to use the function std::to_string so you can convert a number into a string std::to_string(i); #include <iostream> std::string x[] = {"X", "O", "X", "O"}; int main() { std::cout << "Before: " << x[0] + x[1] + x[2] + x[3] << std::endl; for (...
68,981,561
68,986,945
How do I use have a constructor with another class object in c++?
I've got a simple program where I have two classes which are Hat and Person. Each Person has a string name, a int idNum and a hat object. Each hat simply has a string of hatType and a char of hatSize. In the main method I want to simply declare 2 people and use a display method to show the information. Here's my curren...
Below is the complete corrected(working) version. I have added some comments to show the changes i made. #include <iostream> #include <string> using namespace std; class Hat { private: string hatType; char hatSize; // S, M, L public: Hat(string,char); //Added this default constructor since it won't...
68,982,624
68,982,990
Deleting a node at nth position in a linked list in C++ ------ Last number is not getting deleted
On running this code, when I enter n as 4, the program stops instead of getting output as 2 4 6 I cant delete the last node in this linked list. it works fine for all other position but not for the last node. Is it because the there is no (n+1)th node after the last node to which the (n-1)th node should point. and shou...
Looks like you need to do a little more work on your delete algorithm. If you expand your test case to more than 4 nodes, I think you'll discover that there are more issues than just deleting the last node. I rewrote your delete function while trying to keep some of your same logic. The comments mention some of your is...
68,982,992
68,983,081
C++ Linked List HEAD keeps resetting to NULL
I need help in understanding why my Linked List approach doesn't work as expected. #include <iostream> using namespace std; class Node { public: int Data; Node* Next; Node(int data) { Data = data; Next = NULL; } }; void insertNodeAtEnd(Node* HEAD, int data) { Node* it = HEAD; ...
The underlying issue can be reduced to this code: void insertNodeAtEnd(Node* HEAD, int data) { //... if (HEAD == NULL) { HEAD = new Node(data); } //... } int main() { Node* HEAD = NULL; insertNodeAtEnd(HEAD, 5); //... You seem to assume that assigning to HEAD inside insertNodeAtEnd would chang...
68,983,258
68,995,767
Capturing NS3 return/exit code (through waf) as a variable in Bash script
I would like to capture the return/exit code of my NS3 simulation as a variable in my Bash script. Code #!/bin/bash rv=-1 #set initial return value ./waf --run "ns3-simulation-name --simulationInput1=value1 --simInput2=value2" #run ns3 simulation using waf rv=$? #capture return value echo -e "return value cap...
The problem is that the wscript written by ns3 doesn't care of the return code of the executed program. You can either modify the wscript like this: # near line 1426 on current repository if Options.options.run: rv = wutils.run_program( Options.options.run, env, wutils.get_command_template(...
68,983,524
68,991,289
Performance of custom bitwise vs native CPU operations
everyone! I have been trying to create my own big integer class for RSA implementation in C++ (for practice purposes only). The only way I see such thing to be implemented well in terms of performance is by using C++'s built-in bitwise operations (&|^), meaning implementing custom full-adders for addition, binary multi...
Software implementations cannot even come close to arithmetic circuits that are typically used in hardware. It's not even a question of benchmarking or of different results depending on the system (assuming we're talking about hardware that isn't prehistoric), it's a hands-down win for hardware circuits, guaranteed, ev...
68,983,613
68,983,811
AVX2: Is there a way to implement _mm256_mul_epi8 function for a constant power of 2?
I would like to implement the following operation on 8 bit elements: _a = _b * 8 + _c with vectors. For the plus there is obviously _mm256_add_epi8 but i was not able to find a _mm256_mul_epi8 or something to multiply with 8 bit elements. I also tried to find a function to left shift by 3, but no luck. Thanks for helpi...
You can do this with only add: __m256i _b2 = _mm256_add_epi8(_b,_b); __m256i _b4 = _mm256_add_epi8(_b2,_b2); __m256i _b8 = _mm256_add_epi8(_b4,_b4); __m256i _a = _mm256_add_epi8(_b8,_c); You can also do this with any shift, if you mask out high bits of each byte to emulate shifting out: // not needed if _b values are...
68,983,917
68,984,357
Class storage specifier (static/non static) as template argument to avoid duplicate code
Lets say I have a generic wrapper class for an object called worker with many methods: template<typename T> class Wrapper { private: T m_Worker; public: void DoSomeWork1() { m_Worker.Work1(); } void DoSomeWork2() { m_Worker.Work2(); } // ... }; Now I can simply use my Wrapper class by creating an obje...
(You can find the original answer and approach bellow) Sergey's answer has the most merit, and can be expanded to what you are after. Use the Wrapper itself as a static member and delegate to it. To get the syntax you are after, you simply use a "dummy policy" argument and some template specialization to structure the ...