question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,242,648
73,243,333
Optimize the printing of the results of a recursive function
I have the following function, used to print shortest path from source to j void printPath(int parent[], int j) { // base case, i.e. if j is the source if (parent[j] == -1) return; printPath(parent, parent[j]); cout << j+1 << "-"; } It prints results like 1-3-5-6-. How can I change the c...
Here is one way: void printPath(int parent[], int j) { // base case, i.e. if j is the source if (parent[j] == -1) return; printPath(parent, parent[j]); if (parent[parent[j]] != -1) cout << "-"; cout << j+1; }
73,242,728
73,242,808
Why is this "expression" not modifiable?
I have a class called CircuitProfiler that has a public member function switchState. Below is the code for it: void CircuitProfiler::switchState(int index) { if (profilingNode) { switch (index) { case 0: node->getVoltage().isKnown = !node->getVoltage().isKnown; br...
You are essentially saying (MCVE): struct S { int i; }; // S as VariableValue<float> S f() { return S{}; } // f as getVoltage f().i = 1; // i as isKnown You return a temporary in getVoltage(), which does not bind to an lvalue argument of operator=(). Likely you wanted to return voltage by reference in getVoltage(...
73,242,815
73,243,290
Can someone explain this While loop in a linked list to me?
I'm confused with this while loop statement while creating a linked list: while(curr->next != NULL) But curr->next will always be NULL since we never initialized curr->next to point to anything, so that while loop should never run! Can someone explain this, please?? The code snippet is as follows: if (head != NUL...
curr->next is null only on the second call to AddNode. The first call to AddNode we go to the head = n; branch. On the second call, curr->next will be null and the while loop doesn't execute at all. But notice what happens after that, at the end of that second call. The curr->next = n; makes curr->next no longer null, ...
73,243,399
73,243,598
VMA how to tell the library to use the bigger of 2 heaps?
In my current system vulkan info returns these device specs: memoryHeaps[0]: size = 8589934592 (0x200000000) (8.00 GiB) budget = 7826571264 (0x1d2800000) (7.29 GiB) usage = 0 (0x00000000) (0.00 B) flags: count = 1 MEMORY_HEAP_DEVICE_LOCAL_BIT memoryHeaps[1]: ...
VMA's VmaAllocationCreateInfo structure has a member called memoryTypeBits. This allows you to supply a set of memory types from which VMA must select an allocation. So you can get the set of memory types from Vulkan and only specify those which use heap 0. That being said, the fact that this problem happened at all sh...
73,243,736
73,245,219
If I write a function pointer to use in BST template, can they take more than 1 object as argument?
I wrote a template for a binary search tree. I wish to overload the in-order traversal function. I can get it to work when the function pointer only takes in 1 object of class T. I would like it to use a function pointer that uses 2 integer values as well, so that I can pull the integers from outside the statement in m...
In C++ it is better to use std::function than old style function pointers. std::function is a template you instantiate by specifying the return value and arguments (as many as you need). It support passing a global function like you used in your code, as well as lambdas (you can also use a class method with std::bind)....
73,244,049
73,249,650
How to move a unique_ptr without custom deleter to another unique_ptr with custom deleter?
#include <memory> #include <functional> #include <iostream> struct TestStruct { int a = 100; }; struct StructDeleter { void operator()(TestStruct *ptr) const { delete ptr; } }; std::unique_ptr<TestStruct, StructDeleter> MakeNewStruct() { std::unique_ptr<TestStruct> st(new TestStruct()); ...
As noted in the comments, the brute-force way is to have the source .release() to the constructor of the destination. However there is a much more elegant solution (imho): Add an implicit conversion from std::default_delete<TestStruct> to StructDeleter: struct StructDeleter { StructDeleter(std::default_delete<Test...
73,245,070
73,246,613
how to match this line "04.08.2022 22:09" with regular expression in cpp
I want to match "04.08.2022 22:09" with regex in c++. The code below doesn't work (doesn't match). //04.08.2022 22:09 if (std::regex_match(line, std::regex("^/d{2}./d{2}./d{4}.*/d/d:/d/d.*"))) { cout << line << "\n"; cin.get(); }
You need to use \d not /d to match digits. You can also use \s+ to match one or more whitespaces instead of .* which matches zero or more of any character. You should also escape the . characters that you want to match to not make it match any character. I also recommend using raw string literals when creating string ...
73,245,182
73,245,463
Why am I getting different results on my PC and an online compiler?
I compiled the following C++ program for array sorting on my PC using dev C++ 6.30 with TDM-GCC 9.2.0 compiler. I get the following (undesirable) output: 2 4 5 9 23 69 Now, by using an online compiler of programizer, I get the following (desired/expected) output: 2 4 5 9 23 88 Thi...
In fact, this sorting algorithm does not work, and also you have some mistakes in your array initialization. You did this when you tried to initialize your array: int Arr[6] = {2, 9, 23, 88, 5, 4, }; That , in the end of your array is not necessary. This is how it should be: int Arr[6] = {2, 9, 23, 88, 5, 4 }; You sh...
73,245,215
73,245,690
How to initialize recurring `std::unordered_map` via curly braces
I need to initialize a type implementing tree-like structure. Tree t1 = 1; Tree t2 = {{"a",t1},{"b",{{"x",2},{"y",4}}},{"c",5}}; So i defined structure which inherits from std::unordered_map. I had to wrap recurring Tree in smart pointer. //tree.h using std; struct Tree : unordered_map<string, unique_ptr<Tree>...
Remove the reference from the initializer list. You cannot pass rvalues while using non const references. Also remove the simple{s} from the member initializer list if s isn't even defined anywhere. Tree(std::initializer_list<std::pair<std::string, std::unique_ptr<Tree>>> il) {}; Then something like this would compile...
73,245,406
73,245,580
Precision rounding problem with boost multiprecision
I want to multiply number 123456789.123456789 by 1000000000.0 and as a result of this operation I expect 123456789123456789 as int or float 123456789123456789.0, but I got: res: 123456789123456791.04328155517578125 int_res: 123456789123456791 Should I do it in other way ? #include <iostream> #include <boost/multiprec...
See https://www.boost.org/doc/libs/1_79_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html. You are initialising a with a double literal. 123456789.123456789 can't be represented by a double so you get the closest approximation which is 123456789.12345679104328155517578125. If yo...
73,245,575
73,304,280
add user include dir after standard include dir
when using -Idir1 flag to add include path, gcc search dir1 BEFORE system standard include dir, e.g: $ cpp -v /dev/null -I$HOME/glibc/include -o /dev/null gcc will search $HOME/glibc/include first,then the standard include dirs: /usr/lib/gcc/x86_64-linux-gnu/9/include /usr/local/include /usr/include/x86_64-linux-g...
There might some solutions for this, but the comment that Dmytro Ovdiienko posted provided the answer: Did you try to use -idirafter key? See: gcc.gnu.org/onlinedocs/gcc/…
73,246,502
73,247,414
c++ unorderd_map insert fails for value_type with atomic<bool> member
class strategy { int id; std::atomic<bool> strategyStarted; int startTime; int endTime; void getStartTime() { return startTime; } void setStartTime(int sTime) { startTime = sTime; } }; class strategyImpl{ std::unordered_map<int, strategy> allStrategies; strategyImpl() { s...
So the basic problem is that the compiler isn't able to generate the default copy constructor because of the std::atomic. So you must write one for yourself. E.g. class strategy { public: strategy() = default; strategy(const strategy& rhs) : id(rhs.id) , strategyStarted(rhs.strategyStarted.load...
73,246,665
73,246,753
How Comparator Works Internally?
#include <iostream> #include<bits/stdc++.h> using namespace std; bool compare (int a, int b) { return a>b; } int main() { int arr[5]= {1,2,5,9,6}; sort (arr,arr+5, compare); for (auto i: arr) cout << i << " "; return 0; } The above code is sorted in descending order. I am completely bl...
Because you are not calling it. You are passing the compare function to std::sort without calling it, so that std::sort can call it for you. It is called by std::sort (many times), and std::sort supplies the parameters from your array Again std::sort looks at the return value (true or false) and sorts the two number...
73,246,902
73,247,303
vs code intellisense broken with c++17 explicit template deduction
I have an issue with vs code intellisense for c++17. The following code runs perfectly fine, but vs code tells me it is wrong. It doesn't understand the explicit template deduction. The installed extensions can be seen on the left hand side of the image. I'm using vs Code in combination with wsl2. The same thing happen...
Thanks for the comments. I didn't know that i had to set the cppstandard in vs code to c++17 manually. Simply go to: File -> Preferences -> Settings, search for: cppstandard, set Cpp Standart to c++17
73,247,565
73,258,067
Undefined symbols for architecture arm64: "_glClear", referenced from: _main in main.cpp.o arm64 GLFW3
So i was build a GLFW program with cmake Everthing went fine Until i build it and make give me this error Undefined symbols for architecture arm64: "_glClear", referenced from: _main in main.cpp.o ld: symbol(s) not found for architecture arm64 I try with this command CMAKE_LINK_LIBRARY_SUFFIX And this link_directories ...
ANSWER: So you need to add this line: "-framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo" in the CMAKELISTS on target_link_libraries Or you can use "-framework OpenGL" but if you use all the solution up there it will give you some warning. I don't know but if you don't see any warning I think I'm...
73,247,656
73,248,117
How to declare a compile-time constant list of different size lists in a constant header file?
Introduction Good day, I want to optimize my application and especially a constant header file. In order to do so, I define inline constexpr constants in order to avoid multiple copies of those variable in files they are included. And also to have compile-time constants. I want now to add a new inline constexpr variabl...
The following may give you ideas: #include <array> const int size1 = 1; const int size2 = 2; const int size3 = 3; constexpr std::array<int, size1> first = { 1 }; constexpr std::array<int, size2> second= { 2 }; constexpr std::array<int, size3> third = { 3 }; #include <variant> // The safest, I guess, annoying to use. ...
73,247,711
73,250,506
Why is my Arduino MKR NB 1500 stuck after sending or receiving a couple of MQTT messages?
Good morning everyone, newcomer writing his first question here (and new to C++/OOP). So, i'm currently working on a project in which i have to send 2 types of JSON payloads to a MQTT broker after regular intervals (which can be set by sending a message to the Arduino MKR NB 1500). I'm currently using these libraries: ...
Well, here's a little update: turns out i ran out of memory, so 12288 bytes were too many for the poor microcontroller. By doing some "stupid" tries, i figured 10235 bytes are good and close to the maximum available (the program won't use more than 85% of the RAM); yeah, that's pretty close to the maximum, but the requ...
73,247,946
73,254,401
How change image in wxStaticBitmap in C++
The compiler tells me that the program class doesn't contain an element named SetBitmap when I want to change the image in it Solvo: wxImage bildo("./bildo.png", wxBITMAP_TYPE_PNG); objekto->SetBitmap(wxBitmap(bildo)); objekto is object with class wxStaticBitmap
As said by Igor, it is better to speak english if you want a response. Compiler says that program class does not contain an element with name "SetBitmap" when I want to change an image in it. You should post the part of your code, because wxStaticBitmap has a member named SetBitmap()
73,248,616
73,253,255
Which encoding works best for Windows API calls?
I use a function from the Windows API called GetFileAttributesW to retrieve attributes from a file. The function signature is defined as: DWORD GetFileAttributesW([in] LPCWSTR lpFileName); LPCWSTR is defined as const wchar_t*. I want to call the function: fs::path inputPath = ... GetFileAttributesW(inputPath.whichMet...
TL;DR: char16_t doesn't provide any substantial advantage over wchar_t on Windows, and it's less convenient to use. Choose wchar_t, always. Microsoft's implementation of path::native() returns a std::wstring (not a std::u16string) as a matter of a conscious decision. Which encoding does the Windows API generally expe...
73,248,673
73,248,819
Cannot convert unique_ptr<derived> to unique_ptr<base>
There are 3 classes: decoder_mqtt - Common decoder subdecoder_mqtt_base - Base subdecoder for each concrete version (not an abstract class, but have virtual method). subdecoder_mqtt_v5 : subdecoder_mqtt_base - Derived from subdecoder_mqtt_base subdecoder class. decoder_mqtt creates a subdecoder: // file: mqtt.cc #inclu...
What am I doing wrong? subdecoder_mqtt_v5 privately derives from subdecoder_mqtt_base, so there is only an implicit conversion of pointers in the members and friends of subdecoder_mqtt_v5. The unique_ptr constructor is not one of those places. You probably meant to publicly inherit: class subdecoder_mqtt_v5 : public ...
73,248,689
73,258,541
Is there any reason I should include a header in the associated cpp file if the former only provides declarations the latter defines?
Consider a foo.cpp file with the following content #include "foo.hpp" int foo() { return 7; } and its associated header #pragma once int foo(); The latter is obviously needed to make aware the following main function of the existence of foo: #include <iostream> #include "foo.hpp" // to make the name `foo` availab...
Some reasons to include the header (fpp.hpp) from its implementation file (fpp.cpp): If you include foo.hpp first in foo.cpp, then compilation of foo.cpp acts as a test that foo.hpp is self-contained, meaning it can be successfully compiled without including anything else first. The Google C++ coding guidelines speci...
73,249,006
73,263,365
Qt - Replacing 1 character with multiple characters in a QString
I'm building a text converter that converts things to an exagerrated Scottish accent. Naturally, I need to turn all "u"s into "oo"s. And drop the g in any words that end with g. I'd like to know whether there's a method of replacing one character with more that one character in a QString. Code I have so far, which conv...
Short: void MainWindow::on_replaceU_clicked() QString example = "summarize"; // Better: use QStringLiteral("summarize") QString inputTextScottish = example.replace(QChar('u'), QLatin1String("oo"), Qt::CaseInsensitive); qDebug() << inputTextScottish; // Output: soomarize Longer Why use QStringLiteral()? ...
73,249,538
73,249,869
Copy and Move Assignment with additional argument
I have a RAII class which manages a resource. The problem is, copying the resource requires an additional parameter which is in no way related to the resource, rather is an argument to the resource copy operation. Thus I have a class copy constructor which requires an additional argument. This is allowed provided the...
There is no absolute requirement in C++ that a copy or a move must be done by operator= or by a constructor. All that does is allow a copy or a move to result from a natural use of the = operator, or natural object construction. But there is no universal rule in C++ as to what copy or move must do, or what it means. It...
73,249,853
73,250,036
C++ How to Auto Increment static integer variable on object creation?
C++ How to Auto Increment static integer variable on object creation? When I run the program I want the account number to increment, and I am required to use a static member of the class to automatically assign numbers. I am currently getting a make error for undefined reference to `bankAccount::accountNumber' bankAcco...
Like this, I've renamed the static variable nextAccNum. Having one variable called accNum and another called accountNumber is obviously a recipe for confusion. bankAccount::bankAccount() { accountName = ""; accountNumber = nextAccNum++; accountType = ""; accountBalance = 0.00; ...
73,250,047
73,251,046
Why can't I create process in vs2022
I am new to programming. I want simply create a process , but it always fail. This is the code. #include <Windows.h> #include <atlconv.h> #include <iostream> wchar_t* atw(const char* oc) { USES_CONVERSION; return A2W(oc); } int main() { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeo...
I'm afraid than atw() return a dangling pointer. check A2W implementation details and warnings from the compiler. your usage of A2W is wrong. possible solutions : std::wstring atw(const char* oc) { USES_CONVERSION; return A2W(oc); } or use A2W directly in main
73,250,277
73,250,460
force generic type of template function to inherit some class
in Rust programing language you can declare a function with argument of generic type that must implement a trait. (for those who doesn't know, you can think implement is inheritance and trait is class). so the object you pass to that function must have that trait implemented. for example: // Define a function `printer`...
The C++20 way: template <std::derived_from<Display> T> void printer(const T &value) { // ... } Or the abbreviated template syntax: void printer(const std::derived_from<Display> auto &value) { // ... } Do note that there's some difference between std::derived_from and std::is_base_of_v (other than one of them ...
73,250,430
73,250,535
C++ thrown exception message not shown when running app from Windows CMD
If I run a simple app #include <stdexcept> int main() { throw std::runtime_error("Hello World!"); } with Windows CMD, the error message is not shown. How can I fix it?
Let's take a look at what throw does in C++ from the official Microsoft Docs. In the C++ exception mechanism, control moves from the throw statement to the first catch statement that can handle the thrown type. Note that this means throw does not actually output anything on its own — you'd have to catch it first, the...
73,250,728
73,250,826
How to Initialize a Map of Unique pointer Objects sorted by a Object Variable
Hello I am new to the c++ and have a problem with a Unique Pointer of a Object as a Key of a Map. What does the template need to look like on std::map<std::unique_ptr<Person>,string,?> phonebookMap2; so the Person gets Sorted/Inserted initial by first name? Or how do i sort the map, i tired it with sort(phonebookMap2....
You cannot std::sort a std::map. Elements in a std::map are sorted and you cannot change order, that would break invariants of the map. You can provide the comparison as functor. Then you only need to specify the functors type as argument of std::map: struct PersonCompare { bool operator()(const std::unique_ptr<Pe...
73,250,847
73,250,914
How does the compiler deduce which version of std::vector::begin() to call when passing it to std::vector::insert?
I am trying to make my own mini-vector class and I am attempting to replicate some of the functions, but I can not get them to behave the same way when passing calls such as begin() and end() as parameters - the compiler doesn't deduce the right version. Here is an example: template<typename T> class Iterator { public:...
There is no deduction. If myList is not const-qualified, then the non-const version of Begin() is called for myList.Begin(). Otherwise the const version is called. How you use the result of myList.Begin() is not relevant. The standard library avoids your issue by providing a conversion from the non-const iterator to th...
73,250,949
73,260,345
Custom formatting of the elements of std::vectors using the fmt library
While I can use <fmt/ranges.h> to readily output the contents of a std::vector<T>, I'm at a loss to format the display of its elements according to my preferences. #include <fmt/core.h> #include <fmt/ranges.h> int main() { double x1 = 1.324353; double x2 = 4.432345; std::vector<double> v = {x1, x2}; fm...
You can do it as follows: std::vector<double> v = {1.324353, 4.432345}; fmt::print("{::+5.2}\n", v); This prints: [ +1.3, +4.4] godbolt Note the extra :. Format specifiers after the first colon (empty in this case) apply to the vector itself. Specifiers after the second colon (+5.2) apply to elements.
73,251,137
73,251,461
OpenMP integer copied after tasks finish
I do not know if this is documented anywhere, if so I would love a reference to it, however I have found some unexpected behaviour when using OpenMP. I have a simple program below to illustrate the issue. Here in point form I will tell what I expect the program to do: I want to have 2 threads They both share an intege...
This is not permitted to unlock a mutex from another thread. Doing it causes an undefined behavior. The general solution is to use semaphores in this case. Wait conditions can also help (regarding the real-world use cases). To quote the OpenMP documentation (note that this constraint is shared by nearly all mutex imple...
73,251,357
73,251,947
string into const uint8_t*
I'm writing a program in C++/C for raspberry pi pico. Pico has a 2MB of flash memory and it's SDK provides a function which allows to write data to that memory: void flash_range_program(uint32_t flash_offs, const uint8_t *data, size_t count) Second parameter of that function is the data which we want to write in the m...
Assuming that std::uint8_t is unsigned char (as is usually the case), you are allowed to simply access the object representation of a float variable called f via reinterpret_cast<const unsigned char*>(&f) and the contents of a std::string variable called s via reinterpret_cast<const unsigned char*>(s.c_str()) The cor...
73,252,000
73,279,528
QWebEngineView causes window to move slow
m trying to move my QMainWindow by using another widget inside QMainWindow. Im moving my window by overriding : void mousePressEvent(QMouseEvent *event) void mouseMoveEvent(QMouseEvent *event) in a QTabWidget. The window moves well and everything works fine if there is no QWebEngineView widget, but if add the QWebEng...
Try to reimplement your mousePressEvent and mouseMoveEvent this way, with globalPosition() instead of pos(). Worked for me. Window started to move smoothly. void mousePressEvent(QMouseEvent *event) override { pressPoint = event->globalPosition().toPoint(); QWidget::mousePressEvent(event); } void mouseMoveEvent(...
73,252,011
73,252,097
Does private inheritance actually create a base-class object in the derived class?
In C++ Primer Plus p.797, Containment adds an object to a class as a named member object, whereas private inheritance adds an object to a class as an unnamed inherited object. I wonder if "private inheritance actually create a base-class object in the derived class" as this book said, Or is it just a conceptual expla...
The statement is basically correct, but requires some corrections in the C++ terminology if it is taken strictly. (However, especially when the point is to explain OOP concepts, this terminology is often not used strictly or even conflicts with OOP terminology.) It is not the class which contains a member object or an ...
73,252,481
73,304,426
How to solve Assertion Fail in GCC Compiler, C++
Hello dudes and dudettes! When I compile my C++ program on Ubuntu (a VirtualMachine in VirtualBox), which previously ran without errors under Windows, I get a segmentation fault. /usr/bin/ld: BFD (GNU Binutils for Ubuntu) 2.38 assertion fail ../../bfd/reloc.c:8580 /home/rafael/projects/Send06/lib/x86-64//libstar-api.a(...
I confused a Linux with a Windows library! The answer is quite simple. I had a folder with libraries with the ending xyz.lib and xyz.a. So I thought, .lib for Windows and .a for Linux. However, there was seperate distribution of libraries for Linux. Now everything works. Thank you for your input!
73,253,042
73,254,410
End thread from parent main vs. another thread
I'm new to C++ and am trying to have two threads run: i) Thread that keeps looping until an atomic bool is flipped. ii) A thread that polls for input from keyboard and flips the atomic bool. I seem to be unable to get std::cin.get() to react to an input unless it is assigned its' own thread (like below). Why? Would it ...
I'm not quite sure what your problem is, but use of cin.get() might be part of it. Let's simplify with this code: #include <iostream> using namespace std; int main(int, char **) { cout << "Type something: "; cin.get(); cout << "Done.\n"; } Try that code and run it. Then type a single character. Chances ...
73,253,049
73,253,817
Is it possible for CMake to show error when linking to two incompatible libraries?
Please see the below minimal example cmake_minimum_required(VERSION 3.20) project(sample) add_library(libA A.cpp A.h) add_library(libB B.cpp B.h) add_executable(${PROJECT_NAME} main.cpp) # Given it is known that libA and libB is incompatible, # is it possible to write some extra cmake code to show error while doing...
Yes! This is actually possible using a little-known feature called Compatible Interface Properties. You'll define a custom property with an arbitrary name. Here I'll call it ABI_GROUP and use two different GUIDs for the values. Then you'll add that property to COMPATIBLE_INTERFACE_STRING. See the code below: cmake_mini...
73,253,091
73,253,531
Can someone please explain this bit manipulation code to me?
I am new to competitive programming. I recently gave the Div 3 contest codeforces. Eventhough I solved the problem C, I really found this code from one of the top programmers really interesting. I have been trying to really understand his code, but it seems like I am too much of a beginner to understand it without some...
Mask is 9-bits long, each bit represents a digit from 1-9. Thus it counts from 0 and stops at 512. Each value in that number corresponds to possible solution. Find every solution that sums to the proper value, and remember the smallest one of them. For example, if mask is 235, in binary it is 011101011 // bit repr...
73,253,775
73,274,712
'identifier undefined' in C++11 for-loop with USTRUCT
I am implementing logging functionality in Unreal Engine 4.27 (in C++). A key part of my code is a function that is called once per game-tick. This function is responsible for iterating over an array of actors that I would like to log data for, checking whether a new log entry should be written at this point in time an...
Thanks to Avi Berger for helping me find my problem! In fact, ActorLoggingInfo was actually never undefined and the code within the body of the if-clause was also executed (it just didn't do what it was intended to do). When stepping through the code in the debugger it never showed the steps within the if-body and Acto...
73,253,926
73,254,089
Is it possible to use a static template variable in a template function?
For example, in this instance (the code is pretty self-explanatory): enum types : bool { READ, WRITE }; template<typename T> auto function(types i, T data) { static T datas; if (i == WRITE) { datas = data; } else if (i == READ) { return datas; } } int main() { f...
You should be able to use this kind of logic, but the issue here is that the type parameters for both calls are different. (There's also another issue of a function with return type T not returning anything, but I'll ignore this for now.) The first call uses char const* as template parameter and the second one either i...
73,254,797
73,254,844
Template does not work when it is not in the main class
I have tried using a template in a class but it works in the main class. Here is my main class: #include "AddSubtract.cpp" #include <iostream> #include <string> using namespace std; int main() { templEx(); } And here is the class where the template is located: #include <iostream> #include <string> using namesp...
You're compiling that code that defines tmplEx once in the main.cpp and additionally in the secondary source file, which leads to the conflict. Define the template in a separate header file that both can #include as necessary.
73,255,024
73,270,885
Zero Subsequences problem - What's wrong with my C++ solution?
Problem Statement: Given an array arr of n integers, count the number of non-empty subsequences of the given array such that their product of maximum element and minimum element is zero. Since this number can be huge, compute it modulo 10 ^ 9 + 7 A subsequence of an array is defined as the sequence obtained by deleting...
ans += ((1<<z)-1)*((1<<x)-1); ans += ((1<<y)-1)*((1<<z)-1); ans += ((1<<z)-1); Made this slight change in the logic, thanks a lot to everyone for the valuable feedback. It works now.
73,255,661
73,336,950
wxWidgets wxGetKeyState() and Wayland issue
I have run into a wxGetKeyState() issue with Wayland. Let me explain: In some of my apps, I add a test for the Shift key being pressed in the ctor of my app’s top wxFrame window. If the Shift key is down during launch, I run diagnostic code relevant to my app. This has always worked just fine until I switched to Ubuntu...
I implemented a temporary solution to my problem with the Wayland/wxGetKeyState() issue. The function get_key_state_hack(), below, offers the same functionally of wxGetKeyState() with the following caveats: The use of this function only makes sense when targeting Linux/Wayland. It does not provide any advantage in any...
73,255,930
73,258,034
Add namespace pcl functions and PointT in header file
I have a header file preprocess.h in the include folder that simply does noise removal from a point cloud. The point type of point cloud does not exist in the pcl library so I have to create a custom point type RadarPoint for pcl::PointCloud<PointT>. Also, it's a good practice to create a namespace for functions inside...
POINT_CLOUD_REGISTER_POINT_STRUCT must be used in the global namespace: https://github.com/PointCloudLibrary/pcl/blob/master/common/include/pcl/register_point_struct.h#L63 See also how the macro is used in PCL: https://github.com/PointCloudLibrary/pcl/blob/master/common/include/pcl/impl/point_types.hpp#L1781
73,256,565
73,258,767
My program for calculating pi using Chudnovsky in C++ precision problem
My code: #include <iostream> #include <iomanip> #include <cmath> long double fac(long double num) { long double result = 1.0; for (long double i=2.0; i<num; i++) result *= i; return result; } int main() { using namespace std; long double pi=0.0; for (long double k = 0.0; k < 10.0; k++) ...
First of all your factorial is wrong the loop should be for (long double i=2.0; i<=num; i++) instead of i<num !!! As mentioned in the comments double can hold only up to ~16 digits so your 100 digits is not doable by this method. To remedy this there are 2 ways: use high precision datatype there are libs for this, or ...
73,256,881
73,585,556
Why do we traverse backwards when using counting sort
I have been using counting sort for a few days now. I have noticed that we travers backwards when using it. I was wondering why? If anyone could answer it. It would be great.
We do this to maintain stability because if we traverse 1 4 1 2 7 2 as the frequency of 1 is 2 if we traverse from front it will move first one to 2nd position then again again move 3 one to first position disturbing their order this doesn't affect much if we consider these two ones same but this will affect if we are ...
73,256,915
73,270,939
Traversing byte string through uint16_t pointer
I have a list of uint16_t's that has been packed into a protobuf message that looks like: bytes values = 1; The generated stubs for this message in C allows me to set the field with some code like: protobufMessage.set_values(uint16ptr, sizeof(uint16_t) * amount); In the above example, uint16ptr is a uint16_t* to the ...
Protobuf encodes your message so you can't simply read the values back from a string. But a "repeated" uint16_t should be a big blob somewhere in the message. If you knew the offset you could access the data there. But that is still UB since the uint16_t in the protobuf message are not aligned. So on some CPUs this wil...
73,257,086
73,257,311
how to pack a std::string as a std::tuple<Ts...>
I have a parameter pack like <int, long, string, double> and a string like "100 1000 hello 1.0001" how can I resolve these data and pack them into a std::tuple<int, long, string, double>
One way is to use std::apply to expand the elements of the tuple and use istringstream to extract the formatted data and assign it to the element #include <string> #include <tuple> #include <sstream> int main() { std::string s = "100 1000 hello 1.0001"; std::tuple<int, long, std::string, double> t; auto os = std...
73,257,227
73,257,250
C++: wchar_t cannot be stored in a std::map as a key or value
I am trying to make a variable with the data type std::map<char, wchar_t> in C++. When I try this, Visual Studio gives this build error: C2440 'initializing': cannot convert from 'initializer list' to 'std::map<char,wchar_t,std::less<char>,std::allocator<std::pair<const char,wchar_t>>>' The same error also occurs whe...
It's a map from narrow char to wide char, not char to wide string: Instead of this: const std::map<char, wchar_t> UNICODE_MAP = { { 'X', L"█" }, { 'G', L"▓" }, { 'O', L"ᗣ" }, { 'P', L"ᗤ" } }; Use this: const std::map<char, wchar_t> UNICODE_MAP = { { 'X', L'█' }, { 'G', L'▓' }, { 'O', L'ᗣ' }...
73,257,382
73,257,557
Trying to enable conservative rasterization fails
I am trying to follow Sacha Willems' example on conservative rasterization. To that effect I added tried requesting the extensions when making my device: const std::vector<const char*> DEVICE_EXTENSIONS = { VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_EXT_EXTENDED_DYNAMIC_STA...
VK_KHR_get_physical_device_properties2 is an instance level extension (see the name chapter of the extension spec), but you are enabling it at the device level. That's why loading it's function pointer via vkGetInstanceProcAddr fails. You need to enable that extension at instance creation time.
73,257,461
73,257,520
Why is this function returning an empty vector?
In the code below I am trying to return an array containing the longest strings of the inputArray. However, when I use it the array outputted is empty. vector<string> solution(vector<string> inputArray) { int highestSize, add; vector<string> newArray{}; for (int i = 0; i < inputArray.size(); ++i) { ...
There are several issues in your code: highestSize and add are not initialized. In C++ variables are not default initialized to 0 as you might have expected. newArray is default constructed to have 0 elements. In this case you cannot use operator[] the way you did. operator[] can access only elements that were allocat...
73,257,667
73,257,785
Learning c++ atm and this seems like a dumb question but can someone please tell me why the guessing game i made isnt working?
while(guess!=ans1){ cout << "Enter your first guess: "; cin >> guess; } This is the loop I am using but its not working can someone please tell me how I fix this?? (I am not using an ide btw.) EDIT Full code #include <iostream> using namespace std; int main() { int ans1 = 3; int ans2 = 7;...
I offer you some alternatives: #include <iostream> int main() { using std::cout; // this allows you to only use cout instead of std::cout using std::cin; // and not import the entire namespace. Also, only within // the main function. So no global pollution. int const ans1 = 3; // t...
73,257,728
73,257,950
Vulkan extensions is listed by vulkaninfo but not by enumerateInstanceExtensions
I am trying to enable conservative rasterization. To that effect I am calling vk::enumerateExtensionProperties() to see the extensions supported on my system. That gives me this list: VK_KHR_device_group_creation VK_KHR_display VK_KHR_external_fence_capabilities VK_KHR_external_memory_capabilities VK_KHR_external_semap...
You are comparing instance extensions (on your side) with device extensions in vulkaninfo. To get a list of device extensions, you need to call vkEnumerateDeviceExtensionPropertiesinstead of vkEnumerateInstanceExtensionProperties. That should give you the same list as vulkaninfo does.
73,258,713
73,266,409
LLVM IR C++ API create anonymous global variable
How can I create an anonymous global variable in LLVM IR C++ API? I can create a named global variable as follows: GlobalVariable *createGlobalVariable( Module *module, Type *type, std::string name ) { module->getOrInsertGlobal(name, type); return module->getNamedGlobal(name); } For example: auto c...
In comment, @IlCapitano said that Pass "" as name I try auto context = new LLVMContext(); auto module = new Module("Module", *context); auto type = IntegerType::getInt32Ty(*context); auto constant = module->getOrInsertGlobal("", type); module->dump(); It generates: ; ModuleID = 'Module' source_filename = "Module" @0...
73,259,231
73,259,797
`std::stable_sort` gives wrong results when `std::execution::par`
I wrote simple algorithm for sorting rows in Eigen matrix. This should do the same as Matlab's sortrows function: template <typename D> void _sort( const D &M, Eigen::VectorX<ptrdiff_t>& idx, std::function<bool(ptrdiff_t, ptrdiff_t)> cmp_fun) { // initialize original index locations idx = Eigen::ArrayX<...
Here is my implementation of rowsort. I find the documentation of rowsort somewhat confusing. I work under the assumption that it is just a lexicographical sort. Note that your code can probably be fixed just by making a col variable local to your lambda instead of having it as a shared reference. template<class Derive...
73,259,322
73,259,464
Is there any way to check, from a .hpp file, if C stdio functions are used in the corresponding .cpp file?
I have the following question. Supposing I have an header file header.hpp which is include in a test.cpp file. Is it possible to add instructions to the header.hpp file in order to check (maybe at compile time) if some C stdio functions are used in the test.cpp file and in positive case do something specific? For examp...
No, this is not possible. Neither C++, nor C, work like this, on a fundamental level. An #include is logically equivalent to physically inserting the contents of the included file into the including file. Doing a cut and paste of your header.hpp into the beginning of your test.cpp replacing the #include accomplishes ex...
73,259,369
73,262,136
Why my clangd in vscode will change my header file's order to alphabetical order when I was fomating doc?
I found my clangd plugin in VSCode will modify *.h file's order to alphabetical order. For example: before: -#include "c.h" -#include "b.h" -#include "a.h" after: +#include "a.h" +#include "b.h" +#include "c.h" And here is my clangd's settins,How do I fix this bug. "clangd.onConfigChanged": "restart", "clangd.argu...
Clangd formats your code using clang-format (or more precisely, the LibFormat library that's also used by clang-format), and respects the configuration found in the .clang-format file in the project's root directory (or a subdirectory). See https://clang.llvm.org/docs/ClangFormatStyleOptions.html for the various format...
73,259,764
73,283,608
Downcasting to furthest subclass when calling templated function
I use LuaBridge to import a large framework of classes into a Lua-accessible framework. LuaBridge uses complex template functions that maintain a list of linkages back to methods and properties of each class. The Lua language itself is loosely typed, and it does not check to see if a method or property exists until you...
Thanks to several helpful comments, the solution turns out to be a hybrid of CRTP and Double Dispatch. Here is a version of it based on my example above. I like the fact that it requires no pure virtual functions does not require templatizing the base class (for reasons specific to my code base) If I ever need to add...
73,260,357
73,260,475
Multiple Recursion Calls
#include <iostream> using namespace std; int y(int i){ cout<<i<<endl; i++; if(i==10){ return 10000000; } int left=y(i); int right=y(i)+1; return right; } int main() { cout<<y(1); return 0; } In this code after left(9) has executed shouldn't "i" come out of the stack and ...
Execution doesn't come out of the stack. Each return removes one call. so when i==9 the call in int left=y(9) will be followed by the call in int right=y(9)+1 because i==9 still. Only then will the call to y(8) return and so on through y(7),y(6) and so on down to the original call in main() of y(1). Like any stack stru...
73,260,538
73,260,833
Passing C++ lambda as argument to non templated function
As I googled std::function works slower than simple lambda function. Consider the following use case will there be std::function penalty when using stl sorting algorithms (v vector may be big enough and occupy about N*GB of data): #include <iostream> #include <functional> #include <algorithm> #include <vector> using n...
Lambdas that do not capture anything can be converted to a function pointer with the + operator: void sorter(std::vector<int>& v, bool (*cmp)(int,int)); int main() { auto const cmp = +[](int a, int b) { return a < b; }; vector<int> v{3, 2, 1}; sorter(v, cmp); } But if it does capture something, you should eithe...
73,260,680
73,260,803
How can I set value of a variable to an amount that is more than unsigned long long maximum value in C++?
I know that The maximum value for a variable of type unsigned long long in C++ is: 18,446,744,073,709,551,615 but I don't know that how can I set value of a variable to an amount that is more than 18,446,744,073,709,551,615?
maybe you can use __int128,the only problem is that you can't use cin,cout or printf but you can write a function like that: //output inline void write(__int128 x) { if(x<0) putchar('-'),x=-x; if(x>9) write(x/10); putchar(x%10+'0'); } //input inline __int128 read() { __int128 X=0,w=0; char ch=0; ...
73,261,703
73,276,722
Use NVIDIA GPUDirect RDMA with nvJPEG
Is that possible to use NVIDIA GPIDirect RDMA with NVIDIA nvJPEG? From the description of RDMA technology that should be possible but seems nvJPEG interfaces expect only host memory input.
Nvidia nvJPEG uses a hybrid approach for JPEG decoding. Some of the code is executed on the CPU, some of it on the GPU. See especially the decoupled functions https://docs.nvidia.com/cuda/nvjpeg/index.html#nvjpeg-decoupled-decode-api So, no, it is not possible.
73,261,993
73,262,033
A linear-time algorithm that rearrange negative and positive integers with zeroes in between
Problem: Array has positive, negative, and 0 integers, and values are not necessarily unique. The positive values are to the right of zeroes, and the negative values are to the left of zeroes. The positive and the negative values do not have to be sorted. However, the zeros must be in between the positive and negative...
A simple linear algorithm in two iterations can be to first push all negative numbers to the left, and in a second iteration push all positives numbers to the right. void rearrange(T a[], int n) { int next_to_place= 0; for (int i = 0; i < n; i++) { if (a[i] < 0) { std::swap(a[i], a[next_to_place++]); ...
73,262,060
73,265,079
Why is my regex C++ expression not working?
I have the following regex expression: \\(([^)]+)\\) (don't take into account the double brackets it's because of C++) and the following code: if (in_str.find("(") != string::npos) { print(to_string(countMatchInRegex(in_str, "\\([^ ]*\\.[^ ]*\\)"))); for (int i = 0; i < countMatchInRegex(in_str, "\\(([^...
I actually found the error, I don’t know why but C++ was returning different values for the two countMatchInRegex so all I did was assign it to a variable and use the variable instead every thing the function was called in the code.
73,262,668
73,262,708
Range Based Loop C++
How would you implement a class in C++ using constant time and constant space such that the following would work? for (auto &x : Range{0, 10}) { cout << x << " "; } My initial idea was to create a vector but wasn't constant space. Curious how this would be done.
For a range-based for loop to work, you need: begin() returning an iterator end() returning an iterator On the iterator, you need: operator!=() to compare at least against end() operator++() to increment the loop iterator operator*() for dereference of the iterator So you'll need to implement two classes: Range and...
73,263,172
73,272,414
fatal error LNK1104: cannot open file 'kernel32.lib' in Visual Studio 2019
I'm using Visual Studio 2019 and I got an error even my PATH has kernel32.lib path. C:\Users\googi\Desktop\CMakeProject2\out\build\x64-debug\CMakeProject2\LINK : fatal error LNK1104: cannot open file 'kernel32.lib' ninja: build stopped: subcommand failed. PATH... c:\Program Files (x86)\Windows Kits\10\Lib\10.0.19041....
About your case, I suggest you check these things below: Check if you have installed the Windows SDK for your version. Check if $(WindowsSdkDir)\lib is included in the directories list, if not, manually add it. Check if the value of WindowsSdkDir is correct.
73,263,255
73,364,675
Qt Android blank window
Problem I have a problem with Qt on Android in all my applications: after I close the QFileDialog (code below), I have a blank black window. I can't do anything in the application except close it. Here is the code I use: QFileDialog dialog(this, tr("Open Markdown File")); dialog.setMimeTypeFilters({"text/markdown"}); d...
Works well on my configuration: Samsung Note 20, Android 12, latest update, Qt 6.3.1, clang arm64-v8a, SDK 7.0, NDK 22.1.7171670. Demo: https://youtube.com/shorts/KkyrTYkTNb0?feature=share. Your app open and save file well, FileDialog works well too. So no assumptions about the reasons you see blank screen: may be ...
73,263,346
73,263,397
Can reverse iterators be used in place of forward iterator parameters?
Looking at the function parameters for std::generate() the parameters say that this function only takes forward iterators: I'm having a hard time understanding why this code is compiling: #include <iostream> #include <vector> #include <algorithm> using namespace std; void printer(int i) { cout << i << ", "; } stru...
You know what, reverse-iterators can be forward-iterators too! Specifically, the term reverse-iterator means that they go reverse to the "natural" direction. The term forward-iterator names a concept, which guarantees among others that you can make a copy of an iterator, and copy and original can be independently used ...
73,263,604
73,263,682
How to pass in a dynamically allocated array as an argument to a function
So I created a dynamically allocated array of structs pretend that structtype is the name of the struct, and arr is the array. structtype * arr; arr = new structtype[counter+15]; Then I attempted to pass that array of structs into multiple types of functions with prototypes such as: void read_info(structtype (&arr)[15...
Your array is somewhere in memory, location which is pointed by the actual variable arr the pointer. The array is therefore represented by the pointer, however the pointer carries no information about where the array ends or its size, unlike std::vector<>. So you need to pass it with the known size as in: #include <cst...
73,263,701
73,263,773
Is there a way to have a member parameter type be a pointer to a derived class
I'm writing a module system for my program, where individual modules are initialised and shutdown by a system. how this works is I call an Init() function that will initialise a static pointer of the class. this works and is fine, however: I would like to abstract this into a class so the api is easier to maintain, but...
No, you can't have a variable whose type depends on the type of this. However, you can have a variable whose type depends on a template parameter. template <typename T> class IModule { private: static T* s_instance; }; class Derived : public IModule<Derived> { // The s_instance in this class is of type Derived*. }...
73,263,739
73,263,882
Construct vector of certain size
Trying to construct a class attribute - a vector of certain size class cTest { public: std::vector<double> myTable(1900); }; main() { cTest test; return 0; } compiler says: ./src/main.cpp:43:33: error: expected identifier before numeric constant 43 | std::vector<double> myTable(1900); | ...
This: std::vector<double> myTable(1900); Looks like a member function declaration, and function declarations expect an argument list. 1900 does not satisfy that. There are a couple of ways to solve this: class cTest { public: std::vector<double> myTable = std::vector<double>(1900); }; If you want to make ...
73,263,875
73,263,887
I'm trying to calculate the area of the triangle, but keep getting area = 0
I'm trying to calculate the area of a triangle, but keep getting 0. What am I doing wrong? #include <iostream> using namespace std; int main() { int area, base, height; area = (1/2)*base*height; cout << "Enter the base: "; cin >> base; cout << "Enter the height: "; cin >> height; cout << "The area is...
You're trying to calculate the area before you know the base and height. So the answer is going to be undefined, because base and height haven't been set (depending on how your compiler does things, it may set unknown variables to 0, or it may let them be random values. Either way it won't work). Wait until after th...
73,264,027
73,264,736
ranges and temporary initializer lists
I am trying to pass what I think is a prvalue into a range adapter closure object. It won't compile unless I bind a name to the initializer list and make it an lvalue. What is happening here? #include <bits/stdc++.h> using namespace std; int main(){ //why does this compile? auto init_list = {1,2,4}; auto v = in...
When you use r | views::drop(1) to create a new view, range adaptors will automatically convert r into a view for you. This requires that the type of r must model viewable_range: template<class T> concept viewable_­range = range<T> && ((view<remove_cvref_t<T>> && constructible_­from<remove_cvref_t<T>, T>) || ...
73,264,448
73,264,739
Compare goldbolt and MSVC C++ version
I have written some code that compiles on godbolt, but does not compile in Microsoft Visual Studio. I am trying to figure out why. My first step was to compare compiler versions. On goldbolt, I am compiling the code using "x64 msvc v19.latest." I googled "how to check msvc version," and all of the directions I can find...
You can look up version numbers here: Microsoft Visual C++ - Internal version numbering. Godbolt uses _MSC_VER separated by a dot, e.g. 1914 is 19.14 on Godbolt.
73,264,873
73,264,912
error: assigning to 'subhook_t' (aka 'subhook_struct *') from incompatible type 'void *'
I've solved 6 different errors, but no matter how far I look I keep hitting a dead end with this one error in a subhook code written in c. ./subhook_x86.c:470:10: error: assigning to 'subhook_t' (aka 'subhook_struct *') from incompatible type 'void *' hook = calloc(1, sizeof(*hook)); ^~~~~~~~~~~~~~~~~~~~~~~~...
Unlike C, C++ doesn't allow automatic conversions from void * to other types. You need to use an explicit cast. hook = static_cast<subhook_t>(calloc(1, sizeof(*hook)));
73,265,141
73,265,181
Is there any restriction in returning std::function from a function within a class
If I enable line number 4 in below code then I end up in getting compilation error , while I am doing same thing (calling getFp1) outside the class and that works perfectly fine . **Compilation Error** : In member function 'std::function<void(std::__cxx11::basic_string<char>)> testClass::getFp()': Practice.cpp:23:14: e...
This is a variation on the member functions are not regular functions question we get so often. Your code can be made to work like this public : std::function<void(testClass&,std::string) > getFp(){ return &testClass::myTestFunction; } }; and to call this method testClass t ; auto fp1 = t.getFp(); fp...
73,265,199
73,265,236
Undefined symbols for architecture x86_64: referenced from subhook-9679a6.o
Error: "subhook_unprotect(void*, unsigned long)", referenced from: _subhook_new in subhook-9679a6.o ld: symbol(s) not found for architecture x86_64 Linking command: g++ -dynamiclib -fPIC -v -o finalcalling.dylib finalversion.cpp /Users/~/Desktop/c/subhook-master/subhook.c -std=c++11 After going through my code I...
If this is your code https://github.com/Zeex/subhook then it seems you are supposed to also include subhook_unix.c in your build. That file does define subhook_unprotect. So does subhook_windows.c but I'm assuming you are on a unix like platform.
73,265,364
73,265,442
If condition evaluates to false on changing the sequence of conditions. (C++)
I am trying to solve the "Find Number of Islands in a 2D matrix" problem and I am using DFS technique to count the number of adjacent 1's in the matrix. In the dfs() function, the condition - if( (arr[i][j]=='0') || i<0 || j<0 || i==r || j==c) evaluates to false when (arr[i][j] == '0') condition is written first in seq...
Operator || (and similarly operator &&) are always evaluated left to right, and evaluation stops when the result is known. So if the left hand side of || is true then the right hand side is not evaluated. This is known as short circuit evaluation. So suppose that i equals -1 in this expression (arr[i][j]=='0') || i<0 |...
73,265,397
73,267,609
How to initialize non-const member variable with const value
struct IntSlice { int* ptr_; int len_; }; std::initializer_list<int> xs = {1, 2, 3}; const IntSlice s = {xs.begin(), (int)xs.size()}; // this does not work :( It is giving me an error, that we cannot assign a const pointer to a non const pointer but I thought the declaration const IntSlice would fix that. I thin...
IntSlice is too specific. It works only with (mutable) int slices. Why not have something that works with any type of slice? template <typename T> struct Slice { T* ptr_; std::size_t len_; }; Now you can have Slice<int>, Slice<const int>, Slice<const * const double> and whatever else you fancy. std::ini...
73,265,851
73,265,893
Why C++ friendship for function inside a class does not work same as a standalone function?
I want to know why one of the following two codes compiles while the other does not. In the first code, createB is a stand alone function. In the second code the function createB is a member of class A. The first one compiles. #include <iostream> class A; class B { public: B() { std::cout << "B"; } friend B creat...
Case 1 In the first snippet, createB is a free(standalone) function and it is not mandatory that the friend declaration names an existing function. So this works and also implicitly declares a function named createB with return type of B in the global namespace, though this createB is not visible through ordinary looku...
73,265,936
73,266,010
Why my header files can't correctly index each other's declaration dependency with clangd in VSCode?
I'm now codeing C/C++ in VSCode with clangd.There are some annoying problems.For example,I defined a variable in "a.h",which also used in "b.h".But it will error in b.h with: "Unknown type name 'xxxxx'clang(unknown_typename)". Actually it doesn't affect the compliling results,But always lots of annoying red waves the...
This has nothing to do with VScode or clangd. Instead, the problem is that in file b.h you have not included a.h and thus uint64 is unknown at the point where you're using it uint64 abc;. To solve this, you need to include a.h before using uint64: a.h #pragma once typedef unsigned long uint64; b.h #pragma once #incl...
73,266,301
73,267,217
noexcept, third party and STL calls
I'm trying to understand when I should use noexcept and when I should not. In my library, I have many methods. Some are using methods from third party, some are using the STL. Some use throw, some don't. I can put noexcept statements on all my methods, the compiler just do not complain at all. But I do. I can check my ...
You don't have to chase down anything. If you aren't sure about exceptions being thrown, then your method is "potentially throwing". That's the term used by the standard for operations that are not noexcept. So don't mark your method if you aren't sure, it's only honest (lack of) advertisement. That's not to say you sh...
73,266,969
73,267,216
Spinning words, but cannot return result in correct order
I'm writing a function that takes a string, and reverses all the space-separated words that are longer than 5 characters. e.g. the expected output for an input string "Hey fellow warriors" should be "Hey wollef sroirraw" Currently with my code I'm getting the result "sroirraw Hey wollef" which spins the words tha...
Here is some problems with your approach. You probably don't want to consider spaces as part of words, so you should't add current symbol when it is ' ': if (str[i] == ' ') { //... } else // move it to else block { x = x + str[i]; } Following your logic, you forgot to add the last word to your collection, i...
73,267,101
73,339,980
Why can't I check for a constraints on a type using requires?
I'm trying to understand how to use Concepts to do interface checks on a type (duck typing?), and produce the most readable code. I have the following concept: template <typename T> concept Shape = requires(const T& t) { { t.area() } -> std::convertible_to<float>; }; And then use it as follows template <typename T...
CRTP is amazing, but doesn't solve every problem. CRTP is not the right tool here. The test you need to do has to happen after the type is fully defined. You have hacked it by putting a static assert in the constructor. Here I simply put the static assert right after the class definition, when it is complete. struct C...
73,268,160
73,561,295
Large global array of vectors causing compilation error
I have a very simple C++ code (it was a large one, but I stripped it to the essentials), but it's failing to compile. I'm providing all the details below. The code #include <vector> const int SIZE = 43691; std::vector<int> v[SIZE]; int main() { return 0; } Compilation command: g++ -std=c++17 code.cpp -o code Compil...
It does seem to be an M1 / M1 Pro issue. I tested your code on two seperate M1 Pro machine with the same result as yours. One workaround I found is to use the x86_64 version of gcc under rosetta, which doesn't have these allocation problems.
73,268,326
73,268,393
How can I check if the type `T` is `std::pair<?, bool>` in C++?
We can define a function to insert multiple values to a set like this: template <typename T, typename... U> bool insert_all(T& to, const U... arguments) { return (to.insert(arguments).second && ...); } So this code can insert 4, 5 and 6 to the set: std::set set { 1, 2, 3 }; insert_all(set, 4, 5, 6); Obviously, t...
It's not much different than the technique you already coded: #include <tuple> #include <type_traits> template<typename T> struct is_pair_t_and_bool : std::false_type {}; template<typename T> struct is_pair_t_and_bool<std::pair<T, bool>> : std::true_type {}; static_assert( is_pair_t_and_bool<std::pair<char, bool>>::...
73,269,540
73,269,939
std::move between unique_ptr and another that it owns
Consider some class/struct struct Foo{ int val = 0; std::unique_ptr<Foo> child_a = NULL; std::unique_ptr<Foo> child_b = NULL; Foo(int val_):val(val_){} ~Foo(){std::cout<<"Deleting foo "<<val<<std::endl;} }; as you might construct in a doubly linked list/binary tree or similar. Now, consider that i...
from cppreference std::unique_ptr<T,Deleter>::reset void reset( pointer ptr = pointer() ) noexcept; Given current_ptr, the pointer that was managed by *this, performs the following actions, in this order: Saves a copy of the current pointer old_ptr = current_ptr Overwrites the current pointer with the argument curren...
73,269,698
73,270,672
Problems implementing vector as a data container C++
I need to read data from a file and send it to a vector to perform some calculations with them. The data looks like this: 0 524 36 12 8 7 96 0 2 1 11 22 55 77 88 88 96 15 78 45 65 32 78 98 65 54 12 I managed to put the data in a "istringstream", it change with each iteration as it should, but I cannot put the data in...
it keeps adding just the first line of the file That's because it is the only one it has. You seem to be of the impression that the str setter of std::istringstream resets the stream state from its prior error/eof condition. It doesn't. Since you're reusing the same strData member on each for-loop iteration, only the...
73,269,744
73,273,125
Adding vertices on mouse click in DirectX 12
I'm trying to implement a functionality where a vertex is added whenever the user clicks on the viewport. So far I've managed to draw vertices with the mouse using D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, but the working implementation simply creates a new vertex buffer every click^^ That's how I came to my new implementation...
Resources allocated from the D3D12_HEAP_TYPE_DEFAULT heap are placed in memory where the GPU can access them. There's no guarantee that the CPU can access it at all. In some architectures, there's no difference and all memory can be accessed by both at all times (Unified Memory Architecture such as the Xbox). In other...
73,269,925
73,270,217
C++ CUDA Gridsize meaning clarification
I am new to CUDA programming. I am currently in the process of doing Monte Carlo Simulations on a high number of large data samples. Im trying to dynamically maximize and calculate the number of Blocks to submit to the GPU. The issue i have is that i am unclear on how to calculate the maximum number of blocks i can sub...
On Nvidia CUDA the grid size signifies the number of blocks (not the number of threads), which are sent to the GPU in one kernel invocation. The maximum grid size can be and is huge, as the CUDA programming model does not (normally) give any guarantee that blocks run at the same time. This helps to run the same kernels...
73,270,155
73,270,298
C++: Using sizeof() division to find the size of a vector
I am trying to get the size of a vector as a number so that I can use it as a constexpr. The vector.size() returns a size type that is not a constant expression. Therefore, I thought to use sizeof(vector) / sizeof(vector[0]) to get an integer value which I can manually use in a constexpr initialization. const vector<in...
The reason why vector.size() isn't constexpr is that std::vector grows as you add data to it; it has a variable size that is not known at compile time. (That's what constexpr means, that the value of the expression is known at compile time.) What sizeof (vector) gets you is the size of the in-memory representation of t...
73,270,156
73,270,247
Does placement new start object's lifetime?
The following code example is from cppreference on std::launder: alignas(Y) std::byte s[sizeof(Y)]; Y* q = new(&s) Y{2}; const int f = reinterpret_cast<Y*>(&s)->z; // Class member access is undefined behavior It seems to me that third line will result in undefined behaviour because of [basic.life]/6 in the standard: ...
The placement-new did start the lifetime of the Y object (and its subobjects). But object lifetime is not what std::launder is about. std::launder can't be used to start the lifetime of objects. std::launder is used when you have a pointer which points to an object of a type different than the pointer's type, which hap...
73,270,169
73,270,233
Dereferencing iterators to int and int& in C++
int main() { vector<int> v={1,2,4}; int &a=*v.begin(); cout<<a; return 0; } In the above code segment, the dereferenced value of the iterator v.begin() assigned to &a. Printing a displays 1 int main() { vector<int> v={1,2,4}; int a=*v.begin(); cout<<a; return 0; } Here, the iterator is deferenced and the valu...
int& a = *v.begin(); makes a a reference to the first element in the vector so anything you do to that reference is reflected upon the referenced element. Example: #include <vector> #include <iostream> int main() { std::vector<int> v = {1, 2, 4}; int &a = *v.begin(); a = 100; std::cout << v[0]; // prin...
73,270,664
73,270,667
C++ passing a value by reference that is created in the function call (inline)
I want to understand why C++20 complains when I try do the following, perhaps someone can help. I have a method defined, like so: void doStuff(Point& dest) { ... } When I try to do the following: doStuff(Point(x,y)); I get the error: C++ initial value of reference to non-const must be an lvalue This goes away whe...
you can accept (overload with) rvalue references void doStuff(Point&& dest) side note: you can pass it directly to lvalue reference version if that's what you want. void doStuff(Point& dest); inline void doStuff(Point&& dest) { doStuff(dest); }
73,270,933
73,271,038
Delphi interface to C++ Builder
I am trying to use a Delphi component and the callback function needs to be implemented as a typedef System::DelphiInterface<TButtonCallBack> _di_TButtonCallBack; which is defined in the C++ header file as: __interface TButtonCallBack : public System::IInterface { virtual void __fastcall Invoke(TConfirmButton Confir...
Ok I figured it out. For others if it is helpful, the answer is below: class TUniFSConfirmButtonInterface : public TCppInterfacedObject<TButtonCallBack> { public: void __fastcall Invoke(TConfirmButton nButton) { } }; All the best, Aggie85!
73,271,094
73,271,145
How to create a Template function that creates an instance of the class specified as a template parameter
I am trying to enumerate my I2C bus. I have a data structure that contains the I2C address range, the device name and a pointer to the function that needs to be called to "Create" that device. The Create Device functions are all very similar and I was wondering if I can create a template function, instead of creating n...
To your title question template<typename T> T create(){ return T{}; } As to you actual question. It is most of the time very tricky, sometimes bordering on impossible to make templates and inheritance play nice with each other. Also ClassName className in the argument list makes className a value. You cant do new ...
73,271,155
73,271,397
C++ include error: No such file or directory
I am using the SFML library to try and build a game (it's my first time so I'm really struggling). I have given an include path in the tasks.json file and c_cpp_properties.json file but still when I build it, it finds an error in the model.cpp file, saying 'No such file or directory' regarding the #include <SFML\Window...
Well this was a very stupid error and I've just fixed it. In the tasks.json file, the include directory had a space between -I and the file directory path: "-I C:\\Users\\wswil\\Desktop\\projects\\asteroids-game\\include" While trying to learn how to set everything up, I read that you can have the space or not, it won...
73,271,399
73,271,413
error: passing 'const obj' as 'this' argument discards qualifiers
The following code: #include <iostream> #include <string> #include <array> #include <iterator> using namespace std; class obj { public: obj() = default; obj(int i) : i_{i} {} void show() {cout << "addr = " << this << ", i_ = " << i_ << endl;} private: int i_{0}; };...
You should make it a const member function explicitly: void show() const { cout << "addr = " << this << ", i_ = " << i_ << endl; }
73,271,400
73,271,898
C++ - Visual Studio tries to link against symbols with @[num], but compiles symbols without that suffix
I'm trying to link against ZLib, which has been built by my solution with the same respective configuration type as my project (Debug|Win32). When I build my main project, I get these unresolved symbols: __imp__compress@16 __imp__compressBound@4 __imp__uncompress@16 If I had to guess, I would say that the @[num] is th...
@16 and @4 in the unresolved symbols mean __stdcall calling convention when you import those symbols. Missing sign @ in zlibd.lib means __cdecl calling convention is used while building zlib.dll. You should use the identical calling convention while exporting and importing function. Since you have not provided any deb...
73,271,879
73,271,925
Compiler error when a templated member function needs a forward declared type to be completed
I have the following code: // a.h #ifndef HEADER_A #define HEADER_A #include "b.h" #include <iostream> struct A { B b; void bar(); }; #endif // b.h #ifndef HEADER_B #define HEADER_B #include "a.h" struct A; struct B { A* a = nullptr; template <typename T> void foo() { a->bar(); ...
You may the solve circular dependencies and the invalid use of incomplete type 'struct A' by using a template class parameter. // a.h #ifndef HEADER_A #define HEADER_A #include "b.h" #include <iostream> struct A { B<A> b; void bar(); }; #endif // b.h #ifndef HEADER_B #define HEADER_B <typename U> struct B...