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
74,537,784
74,538,993
Override method for each in parameter pack
I have the following classes: enum class Group { A, B }; template <Group G> class AbstractGroupVisitor; template <Group G> class GroupMessage; class AbstractMessageVisitor; class AbstractMessage { public: virtual void accept(AbstractMessageVisitor& visitor) = 0; }; class AbstractMessageVisitor { public...
You could do some recursion based on template specialization of GroupsVisitor. The following code compiles for me: template <Group... Gs> class GroupsVisitor; template <> class GroupsVisitor<> : public AbstractMessageVisitor {}; template <Group First, Group ... Rest> class GroupsVisitor<First, Rest...> : public Abstr...
74,538,802
74,538,862
I am confused a bit in c++...(do-while)
When I compile the program below, the following answer shows up: #include <iostream> int main() { const int COUNT{0}; size_t i{0}; // Iterator declaration do{ std::cout << " I love C++" << std::endl; ++i; // Incrementation }while( i < COUNT); std::cout << "Loop done!" << std::endl...
The difference between while (condition) do { body }and do { body} while (condition) is that for the latter, the condition is evaluated after executing the body. So the body is guaranteed to execute at least once, and in your example, by the time the condition is checked, i has already been incremented.
74,539,336
74,539,526
Infinite loop from access of improperly created variables
Why does this go into an infinite loop and why does it dump char 0x20? #include <iostream> struct Outer { Outer(std::string &outerString, std::string &superfluousString1, std::string &superfluousString2) : outerString(outerString), inner(*this) {} struct Inner { ...
I do know that I should not be using the fields of Outer before it has been properly created Not necessarily. You cannot use members before they are initialised, but you can use members that are already initialised to initialise other members. The catch is that the members are initialised in order of declaration, not...
74,539,437
74,539,915
Is it possible to enumerate/scan available USB ports with Boost Asio C++ library
I want to use Boost Asio library to connect my USB device. It works. Now I want to enumerate/scan all possible USB devices to see which one can be used. Is that possible in Boost Asio library? I haven't found any function nor information about that. This is the most closed scenario to find USB ports. But not sure if it...
That's not a feature of the library. Since you are looking for windows, consider using WMI interface to enumerate serial ports. E.g. in C# code: try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName"); foreach (ManagementObject quer...
74,539,774
74,540,289
How to optimize this code for speed and get rid of the nested loop?
I was trying to solve This problem, but I keep getting Time limit exceeded, when the input is 100000. I need to optimize the nested loop somehow. #include <iostream> using namespace std; int main(){ int arr[100000]; int n, x, q, m; cin >> n; //number of shops that sell the drink for (int i = 0; i < n; i...
It actually appears that your second solution CAN be optimized, by sorting your arr only once, before going into a loop.
74,539,849
74,594,851
Unreal engine Abstract class example c++
i have been looking for quite some time online for a good Abstract class (UCLASS(Abstract)) example but haven't came accross a good one yet. Is there anyone with a good Link i can goto or Anyone who could show me a simple example, i would appreciate alot. WeaponBase.h UCLASS(Abstract, Blueprintable) class FPS_API AWeap...
All class definitions must have ; after last } Like this: UCLASS(Abstract) class UAnimalBase : public UObject { GENERATED_BODY() public: UAnimalBase(const FObjectInitializer& ObjectInitializer); }; You need to add a declaration of an overridden function to your Weapon_Assault.h UCLASS() class FPS_API AWea...
74,540,529
74,540,549
Undefined reference when building AzerothCore module
I followed the steps on how to install azerothcore. I remembered I could add Modules, so I went in the website of azerothcore and downloaded a few modules. Before I downloaded them I checked and saw it says that it's building on master core, but for some reason I have the following error: /usr/bin/ld: ../../../modules/...
Remove _master from all module subdirectories. You can avoid this error by using git clone or cloning the modules in general with a git interface, instead of downloading a .zip file.
74,540,793
74,540,870
How to create vector to store addresses of all children?
I am trying to create a basic game engine in C++ and I want an Engine object to be able to loop through all the GameObject children to run their update methods, to do this I want to use a vector of all children within the Engine class. For example: This is similar to what I have been trying to do: Parent Engine Class c...
There are a few issues here. First, your vector needs to be a vector of references or pointers, otherwise GameObjects.push_back(obj); makes a copy of obj to place into the vector (unless you move it) and polymorphism won't work (you can't hold subclasses of GameObject). How you approach this depends on which object you...
74,541,494
74,541,566
std::swap of std::priority_queue with lambda comparator compiles under C++20 but not C++17: "error: object of type value_compare cannot be assigned"
The following code, which std::swaps two std::priority_queue<int, std::vector<int>, decltype(some lambda)>s, results in a compiler error in C++17, but not in C++20. #include <queue> int main() { auto cmp = [](int x, int y) {return x > y;}; std::priority_queue<int, std::vector<int>, decltype(cmp)> pq1(cmp), pq2...
"seems to be with copy-constructing": No, as the error message says it is with copy-assigning. Swapping requires reassignment between the two objects, not only construction, because the two objects are not replaced by new ones. Only their values are exchanged. Before C++20 lambdas were not assignable at all and so this...
74,541,783
74,542,054
Singly linked list with unique_ptr
I am trying to use smart pointers (std::unique_ptr) to create a singly linked list. Here is an example of a singly linked list with raw pointer. struct Node { int data; Node *next = nullptr; Node(int data) : data{data}, next{nullptr} {} ~Node() { std::cout << "Destroy node with data: " << data << '\n'; } }; vo...
First thing, there is a problem with your print_list implementation(for both version for unique_ptr only). With your print_list, every time you assign head with a different uniq_ptr, you are actually deallocating the only Node in head, which is not desired. Instead, in your print_list, you should first create a tempora...
74,542,479
74,542,782
i made c++ code where its need to pass structure pointer in a function
i got confused about the structure when i need to to pass the value in a function #include <iostream> using namespace std; struct student { int studentID; char studentName[30]; char nickname[10]; }; void read_student(struct student *); void display_student(struct student *); int main() { student *s;...
You are suffering from some leftovers from your C-Language time. And, you have still not understood, how pointer work. A pointer (as its name says) points to something. In your main, you define a student pointer. But it is not initialized. It points to somewhere. If you read data from somewhere, then it is undefined be...
74,542,563
74,542,644
How to write a multicharacter literal to a file in C++?
I have a structure defined array of objects with different data types, I'm trying to write the contents to a file but one of the char values is more than one character, and it's only writing the last character in the multicharacter literal to the file. The value in the char is 'A-', but only - is getting written. Is it...
It is not possible to fit two characters in a single byte char. The simplest solution is to modify the data structure: struct studentInfo { . . char Grade[3]; // +1 for a null-terminator }; Then, you have to place A- in double-quotes like this: studentInfo students[NUM_STUDENTS] = { { "Jake", 23, 3.45,...
74,543,012
74,543,868
C++, std::remove_if with std::string. Resize string by popping it's end in lambda
Since std::remove() does not resize std::string, I've came up with an idea how to solve this: std::string s{"aabcdef"}; std::remove_if(s.begin(), s.end(), [&s](char a) { if (a == 'a') { s.pop_back(); return true; } return false; }); Excepted output: bcd...
Note the function/lambda you passed to std::remove_if isn't about what happened to the character you want to remove. It is about how to determine which character need to be removed. What that means is whatever happens within the lambda will happen before std::remove_if starting its removal algorithm. In your case, sinc...
74,543,174
74,543,320
How to recive second command while last command not completed?
How to recive second command while last command not completed? I have a application that receive command from message queue and process parser command to do something. But if last command is "start" and it need some time to completed, like 1 minute in the while loop. In the same time, another command "stop" incoming, h...
If you want to do two things at the same time, such as executing one message and simultaneously checking if you have received another, then the easiest solution would probably be starting a thread. However, be aware that you cannot poke a thread and tell it to just stop. If you want to be able to stop your "execute com...
74,544,973
74,546,521
How to change QGraphicsLineItem programmatically
I'm working on resizeable and moveable overlay items, at the moment on a cross-hair. To make it resizeable I need to change parameters of my two QGraphicsLineItems, my cross-hair consists of. But calling the functions like setLength(), setP1(), setP2() or setLine() of the two lines do not show any effect. Please consid...
Use QGraphicsLineItem::setLine instead: //... line1->setLine(0, 55, 110, 55); line2->setLine(55, 0, 55, 110);
74,545,075
74,549,840
How do I represent a 24-hour clock with the STL?
I'm looking for a solution from the STL, for dealing with "time of day". I am working on a simple unit test exercise, with behavior depending on whether current time is in the morning, evening or night. For a first iteration I used a humble integer as a stand-in for some "time object": using TimeOfDay = int; constexpr ...
I'm going to start with the assumption that you're looking for the local time of day. chrono::system_clock represents UTC. So I recommend a helper function that takes std::chrono::system_clock::time_point and returns a std::chrono::system_clock::duration which represents the time elapsed since the most recent local m...
74,545,491
74,545,705
I am here to ask on how can I store the calculation history of my calculator in c++
I am new to the coding community and I am here to ask on how can I store the calculations that have been done in my calculator. I am currently new in this space and I am currently looking for answers T-T. my code goes like this thank you everyone! T-T pls be gentle on me. #include<iostream> #include<stdlib.h> using na...
You want to #include <vector> and make a history std::vector, that holds strings: std::vector<std::string> history; When you do the calculcation, don't output to cout, but to a std::ostringstream first (located in <sstream>): std::ostringstream caclulation_stream; switch (op) { case '+': sum = x + y; caclulati...
74,545,953
74,546,040
My VS 2022 doesn't handle over than 32 bit bitset
I am trying to convert 45 bit binary number into a hex number but when compiling, I get overflow error, but when applying the code on online C++ compiler, it works. My platform is X64. Any help please. int main() { stringstream ss; string binary_str("111000000100010010100000110101001000100011000"); bitset<4...
unsigned long is 32bit with MSVC. Also when compiling for x64. You need unsigned long long to get a 64bit integer, so in this case you can use to_ullong: ss << hex << n.to_ullong() << endl;
74,546,017
74,546,575
using enum as semantic type in Bison C++
How can I use an enum as type as shown below %type <order_direction> ordering_direction opt_ordering_direction when i have defined order_direction in a separate header file as enum enum_order : int { ORDER_NOT_RELEVANT = 1, ORDER_ASC, ORDER_DESC }; enum_order order_direction; which i include in the Bison file? When i...
The problem is that enum_direction is an enumerator and not an enumaration type. This means enum_direction cannot be used as a type. To solve this, you must use a type where a type is required. This means you can use enum_order as the type of the function parameter instead of enum_direction( as the former is a type).
74,546,189
74,546,766
std::transform applied to data member of sequence's element
Please help me to find a more elegant way to rewrite this snippet using std::transform or similar algorithm: for (auto& warning : warnings) { NormalizePath(warning.path, GetParsedPathLength(warning.path), longestPathLength); }; Where warning is a struct. This is what I came up with: std::transform(begin(warnings),...
With ranges (C++20), you might "shorter" first version to: for (auto& path : warnings | std::views::transform(&Warning::path)) { NormalizePath(path, GetParsedPathLength(path), longestPathLength); }
74,546,904
74,548,211
Somewhat inconsistent need for template disambiguator
In the example below, I need to use the template disambiguator in the line marked as #1, while it appears to be unnecessary in the other occurrence of a similar pattern. What does it make the difference? #include <cstdint> #include <utility> #include <array> #include <vector> #include <ranges> template<std::size_t n, ...
Here's a minimal way to reproduce your error: #include <utility> class TFace { public: template<int i> void GetVertex() const {} }; template<typename> void f1() { auto const &[_, Face2] = std::pair<int, TFace>{}; Face2.GetVertex<0>(); // #1 } Since this compiles on clang, I'm thinking that this is a GCC ...
74,546,962
74,547,037
How to pass generic arguments to the nested generic classes in C++
I have a class and a nested class in C++ and they are both generic classes. #define GENERIC template<typename T> GENERIC class Class1 final{ private: GENERIC class Class2 final{ private: T class2Field{}; }; T class1Field{}; }; I want to pass the type parameter T that is passed to Clas...
Class2 can see the declaration of Class1, therefore will use Class1's T when not declared a templated class: template<typename T> class Class1 final { private: class Class2 final { private: T class2Field{}; }; T class1Field{}; }; so Class1<int>::Class2::class2Field will be of type int. If you...
74,547,165
74,548,361
how to create derive class from base class
I have base class like this: class Base{ public: virtual Base *createNew(){ auto newItem = new Base(); setNew(newItem); return newItem; }; void setNew(Base *item){ item->value = value; }; private: int value; }; A number of derived classes are shown below, each of w...
Supposedly you want to use the Curiously Recurring Template Pattern (CRTP) for this. Here is an example where we introduce template class BaseT that inherits from Base. Note how each derived class inherits from BaseT passing itself as template parameter. class Base { public: virtual Base* createNew() = 0; virtual ~...
74,547,236
74,549,572
How to reassign a time_point from clock::now()?
Given a std::chrono::sys_seconds time, one might expect to reassign time from its clock with something like: time = decltype(time)::clock::now(); However, this would likely fail, because decltype(time)::clock::duration has nothing to do with decltype(time). Instead it is a predefined unit(likely finer than seconds), s...
an obvious solution is just write your own function template<typename Clock, typename Duration> void SetNow(std::chrono::time_point<Clock,Duration>& time){ time = std::chrono::time_point_cast<Duration>(Clock::now()); } // use void foo(){ auto time = std::chrono::system_clock::now(); SetNow(time); } you c...
74,547,781
74,547,904
C++ Is there a performance difference when assigning a new value to a variable vs assigning them via methods
I've been mostly using private variables when writing a class and using methods to set the variable's value. Especially when it comes array, indexing them would be just using the operator[]. But what if I were to put them inside a method like getIndex(int x), and calling that method. Would that have any impact to the p...
That really depends on whether the compiler can inline the calls to these getters/setters. It can inline them if either: Each translation unit has access to their definitions - in practice if they are in the header file of the class. Either inlined into the class definition or inline-defined after it. You enable link-...
74,547,838
74,576,185
C++ Linked list problem. i want to know why my output is correct. i think i didn't connect first node yet
here is my code. list of problems 1.if i write "std::cout << this->first->new_data << std::endl;" in function void printout it will get an error you can look in my code i comment it already BUT in while loop it can show output and it correct WHY??? 2.I haven't connected to the first node yet but the output is correct.W...
Ok now i have solved the problem. Thank you for your comments and advice. I have studied about pointer and I quite understand. here is my code that i fixed. It might not be good but i think it is the best for me now. #include <iostream> class Node { //this class create node public: int new_data; //set default val...
74,547,903
74,552,472
Algorithm too slow on large scale input case, and dynamic programming optimization
Problems I found My code works on short input but not on long input (test cases 1, and 2 work, but 3 takes too much time) I believe code can be optimized (by dynamic programming), but how? Guess recursion limit problem(call stack limit) can occur in large scale input Preconditions the array is sorted in ascending ...
This problem looks like a harder version of the LeetCode program "frog jump". Forget about the array or dynamic programming for a while and look at it conceptually. A state S is (n,k) where n is an element of the input array, and k the difference to the previous number. The initial state S0 is (0, 1). Successor states ...
74,548,280
74,581,323
Executing external python file from inside ns3
I have a python file, containing a pre-trained model. How can I execute this file from inside ns-3 code? The python file will start execution when enough amount of data is gerenerated by the ns-3, which will be given to the pre-trained model. Later, the model predicts one value and it is used in ns-3 during simulation....
In my case, I have tried the following piece of code in a function where I was required to execute the external python file from ns-3. This specific example is for the Ubuntu environment. system("/[path_to_your_python]/anaconda3/bin/python /[path_to_your_inference_file]/inference.py"); Note: The inference.py file will...
74,548,284
74,548,515
How to overload class method with two template parameters, so I can use std::function as one of them?
I need some help with working with templates. I have code like this, it's class holding two vectors of std::function object, and a method that pushes some function (bind, lambda, or functor) in one of them: typedef std::function<int(int)> unFuncPtr; typedef std::function<int(int, int)> binFuncPtr; class Operations { p...
First, you have a typo here: std::vector<unFuncPtr> m_binaryOperations; std::vector<binFuncPtr> m_unaryOperations; It should be: std::vector<unFuncPtr> m_unaryOperations; std::vector<binFuncPtr> m_binaryOperations; Second, even then it wouldn't compile, since with "ordinary" if, both branches needs to be compilable. ...
74,549,189
74,549,327
Why CMake does not propagate the PUBLIC include directories between libraries?
I have a C++ project with three shared libraries, let's call them libA, libB and libC. libA is dependant to both libB and libC. All of these three libraries are located inside a folder called utilities. Here is what I have: Root CMakeLists.txt file: cmake_minimum_required (VERSION 3.20) # Required because of policy CMP...
Instead of the following: target_link_directories(libA PUBLIC libB PUBLIC libC ) You should use target_link_libraries(). target_link_libraries(libA PUBLIC libB PUBLIC libC ) This will setup a dependency between the libraries which sets the include path, compiler settings, additional link directories, and ...
74,549,582
74,602,211
Fail to import QML module using CMake
I'm currently building a minimalist app following this CMake architecture: -root --QmlModule ---Component1.qml ---Component2.qml --App1 ---main.cpp ---main.qml --App2 ---main.cpp ---main.qml I use "qt6_add_qml_module" to create a QML module at "QmlModule" level as a STATIC library. qt_add_library(myComponentTarget STAT...
CMake itself was fine, this was a runtime error and not a link error. This issue was raised because the QQmlApplicationEngine wasn't finding path towards my module's QMLDIR. In the end, the only thing missing was an additional import path ":/" in QQmlEngine: QQmlApplicationEngine engine; engine.addImportPath(":/");
74,549,928
74,550,353
Concept for constraining parameter pack to string-like types or types convertible to string
I'm piecing together a C++20 puzzle. Here's what I want to do: Function append_params will concatenate the url together with additional query parameters. To make design this in a dynamic and extensible way, I wanted to write a concept such that it allows types that an std::string can be constructed from it allows typ...
When developing a concept, always start with the template code you want to constrain. You may adjust that code at some point, but you always want to start with that code (unconstrained). So what you want is something like this: template<typename... Ts> auto append_params(std::string &url, Ts... &&args) { return ...
74,550,010
74,551,754
error C2660: 'std::pair<a,b>::pair': function does not take 2 arguments
I am trying to create a structure and insert that a map as following: struct Queue_ctx { std::mutex qu_mutex; std::condition_variable qu_cv; std::queue<std::vector<std::byte>> qu; }; std::map<std::string, Queue_ctx> incoming_q_map; Queue_ctx qctx; std::vector<std::byte> vect(100);...
Anyway to fix this problem you need customize copy constructor and assignment operator. Also mutex suggest some synchronization of qu in all scenerios, so all fields should be private (so struct should be changed to class). class Queue_ctx { mutable std::mutex qu_mutex; std::condition_variable qu_cv; std::q...
74,550,744
74,552,124
How does `std::is_const` work on non-static member method types?
Question: How does std::is_const work on non-static member method types? Is a const member method not a const-qualified type? Example: class D {}; We will have std::is_const_v<void (D::*)() const> == false Follow-up: Can the constness of a member non-static method be determined (at compile/run time)?
In C++, functions are not first-class citizens: you can't have objects with function type (you can have function objects, but that's a different concept). void (D::*)() const is a pointer type. std::is_const will tell you whether the pointer is const or not, so: std::is_const_v<void (D::*)() const> == false; std::is_c...
74,551,228
74,551,310
Correct interface for a function on a base class and inherited class?
I have defined a base class DiGraph and a inherited class UnGraph as: class DiGraph { protected: long V; // No. of vertices; Vertices are labelled from 0, 1, ... V-1. vector<list<long>> adj; // Adjacency List of graph public: DiGraph(long V); // Constructor, initialize ...
As long as you provide a constructor for UnGraph that accepts a long, e.g. UnGraph(long V) : DiGraph(V) {} you can implement Kn as a template function taking GraphType as template parameter (e.g. DiGraph or UnGraph): template <typename GraphType> GraphType Kn (long n) { GraphType G(n); for (long i = 0; i < n ; i++...
74,551,508
74,551,566
Determine the return type of a callable passed to a template
I have a simple wrapper template that allows free functions (e.g. open() close() etc) to passed as template parameters. The code is as follows: template <auto fn, typename ReturnType=void> struct func_wrapper { template<typename... Args> constexpr ReturnType operator()(Args&&... args) const { if conste...
template <auto fn> struct func_wrapper { template<typename... Args> constexpr decltype(auto) operator()(Args&&... args) const { return fn(std::forward<Args>(args)...); } }; have you tried this? I think that works in c++17. Definitely in c++20. The return type of a callable cannot be determined unles...
74,551,553
74,576,258
CMAKE SFML found but depencencies missing
I know this question has been asked before but following the answer or other online resources I came across yielded nothing. I've built SFML from source for Windows using CMAKE GUI and mingw32-make. I've changed it from making shared to static libraries. On the SFML site, it states that the dependencies are included un...
The issue was that after building it and moving it over to the project I placed the files in the wrong place. So it could not find them. Here is how I did it. I built it using CMake and mingw32-make from the source, changing the settings from dynamic to static built. After this, I moved the files to a folder in my proj...
74,551,793
74,616,018
Pointer offset is incorrect when using multiple inheritance
I am encountering a bug in some code which uses multiple inheritance when accessing a member variable. Unfortunately, I cannot provide a minimum reproducible example that you can run, but I can provide a bunch of information as to what I am seeing. My code is compiled using GCC for ARM. To give the rough idea, this i...
For anyone else experiencing a problem like this, it cam down to a violation of the "One Definition Rule" caused by differing #define values in translation units. For example, if the class definition was: Foo.hpp: class Foo { private: std::array<uint8_t, MAX_BUFFER_SIZE> _buffer; int _foo; }; File A.cpp had MA...
74,552,485
74,553,107
Initialize deprecated field without tripping warning
I have a struct with a static field I want to deprecate. However, for now I still want to initialize it. The following snippet produces a warning under MSVC and GCC (but not Clang): struct A { ~A(); }; struct B { [[deprecated]] static A X; }; A B::X; //warning C4996: 'B::X': was declared deprecated Interesti...
The warning disappears when you remove the destructor because then A can be trivially destructed (and also constructed), meaning that the compiler doesn't need to emit actual code to initialize anything, and thus does not generate code that references B::X. Therefore, there is no trigger to emit the warning. This also ...
74,553,216
74,553,360
Hello! My algorithm does not work for n>7 and I don't know why
I built a perfectly balaced tree using BUILD_TREE and printed it inOrder and using a PRETTY_PRINT. The keys for my tree are in a sorted array named arr and I use n as the number of keys. If I give n a value bigger that 7 it does not print anything and I don't understand why. I need it to work for n=11. #include <stdio....
Running your program in a debugger should instantly identify the problem as this line in BUILD_TREE: else node->size = node->left->size + node->right->size + 1; The issue is that the left or right pointers can be NULL. If they are, you will most likely crash. Dereferencing a NULL pointer and reading (or writing) to th...
74,553,352
74,553,573
"expression is not assignable" when trying to assign a value to an element of an array of arrays
I created the following: //main.cpp const int size = 3; int field[size][size] = {{0}}; int (*pfield)[size] = field; A class of mine wants to set a value within a function: //userInputs.cpp int UserInputs::setValue(int (*field)[3], int x, int y) { ... ((*field)[x] + y) = value; ... } And it causes the followin...
If you break down ((*field)[x])+y you can see why it's unassignable. C expressions are roughly read inside out so we start with (*field), which is the same as field[0], then tack on [x] and you have field[0][x], which is still an l-value (assignable, i.e., can be on the left hand side of an =). Then tack on the + y an...
74,553,543
74,566,441
How to declare function using reference?
I am making this program to check the alphabetic and numeric characters of a C-type string. I am using C-type strings because it is for an assignment, otherwise I would opt to use std::string. How do I declare the function? In my case, I want str, SAlpha and SNum, to be stored in the function as s, alpha, num. That's w...
You are getting an "undefined" error because you have only declared the seperate() function but have not implemented it yet, eg: #include <iostream> #include <cstring> #include <cctype> using namespace std; // THIS IS JUST A DECLARATION!!! void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100]); int main(...
74,553,866
74,553,911
"Class template has already been defined" when making similar but different specializations
I have two class specializations. I want one of them to be used when T::A exists and the other to be used when T::B exists, which should be multually exclusive in practice. I am using std::void_t< decltype( ... ) > to test for existence. I expect that expression to fail to evaluate for either one or the other specializ...
Clang also rejects this code, but not GCC. This is not the first time I'm seeing problems with std::void_t. I would stay away from it, and prefer decltype(void(T::A)). Or you can define your own robust void_t (code taken from cppreference): template<typename... Ts> struct make_void { typedef void type; }; template<type...
74,554,333
74,554,813
How to clear std::ofstream file buffer?
I am making a console text editor that continuously saves its content to a text file as text is being written to the editor. FileEditor editor("C://temp/test.txt"); while (true) { if (_kbhit()) { editor.keypress(_getche()); system("cls"); std::cout << editor.content(); editor.save(...
The problem is when I write multiple characters into the console, for example the string abcd, it will write a to the file, then aab, adding ab to the current buffer content, then aababc, and so on. Your problem has nothing to do with the file buffer. You are not clearing the editor buffer after writing it to the fi...
74,554,343
74,555,355
The correct variant of implementation of the server-client in one application? Qt6
I am creating simple online chat with server and client in one application. I wrote client-side, but i don't know how will be correct use QTcpServer. Need i create QTcpServer in new thread? So that I can connect to it as a client from this application. If yes, how do it? Or it's useless and not needed idea? Need i cre...
Assuming you are using Qt's networking APIs, you don't need to use multiple threads. The reason is that Qt's APIs are designed around a non-blocking event-loop model, so it is expected that no function-call should ever take more than a negligible amount of time (e.g. a few milliseconds) to return, after which the main...
74,554,719
74,554,816
Boost asio:async_read() using boost::asio::use_future
When calling asio::async_read() using a future, is there a way to get the number of bytes transferred when a boost:asio::error::eof exception occurs? It would seem that there are many cases when one would want to get the data transferred even if the peer disconnects. For example: namespace ba = boost::asio; int32_t S...
It's an implementation limitation of futures. Modern async_result<> specializations (that use the initiate member approach) can be used together with as_tuple, e.g.: ba::awaitable<std::tuple<boost::system::error_code, size_t>> a = ba::async_read(m_socket, buffer, ba::as_tuple(ba::use_awaitable)); Or, more typical:...
74,554,795
74,554,950
How do I pass a variable through Python using C++ in Python.h
I wanted to try out embedding Python into C++. I was able to get that to work but I wanted to start writing prints with variables which are in declared in c++. For example: (C++) int num = 43; PyRun_SimpleString("print("+num+")"); char g; std::cin>>g; PyRun_SimpleString("print("+g+")"); I tried to figure out how to u...
To pass char, Python script: def test(person): return "Hello " + person; C++: PyObject *pName, *pModule, *pFunc, *pArgs, *pValue; pName = PyUnicode_FromString((char*)"script"); pModule = PyImport_Import(pName); pFunc = PyObject_GetAttrString(pModule, (char*)"test"); pArgs = PyTuple_Pack(1, PyUnicode_FromString((ch...
74,555,147
74,555,257
I need help in the variables in the Void
It doesn't accept my string and variables just in that part and I don't know why, I can't properly make my variables in the void part like matricula=_matricula because it doesn't detect it and says its undefined #include <iostream> using namespace std; class Alumnos{ private: string matricula; st...
You have missed spaces in the arguments (not string_matricula, it is string _matricula). Also while passing the arguments pass them as string inside " ". And main must return only int, it cannot return string. #include <iostream> using namespace std; class Alumnos{ private: string matricula; string...
74,555,448
74,568,133
How to include external library in C++ from GitHub using CLion and CMake on Windows?
I have an assignment to create a C++ program, and one of the libraries we are encouraged to use is GLM, found on this GitHub link here: https://github.com/g-truc/glm. I've been trying to figure out how to include this library in my program but I can't make heads or tails of the process. I am new to C++ and CMake, and e...
With the help of a friend, I managed to solve it! For posterity, here's the setup that worked for me. I downloaded the library from GitHub using the releases page on the right sidebar: I extracted the downloaded .zip, and placed the entire resulting folder in my project structure. For that, I made a "lib" folder (thou...
74,555,610
74,556,160
What does the parameter assigned to an unordered_map<> name hold?
I was going through a great article on LZW compression algorithm by Mark Nelson, and found something in the code I haven't yet encountered. In the code, he used unordered_map to store strings and their corresponding frequency. The declaration of the map was: std::unordered_map<std::string, unsigned int> codes( (max_cod...
The std::unordered_map type template has a number of constructors that accept a size_type; typically std::size_t, which is an unsigned integer. This value is related to the semantics, or rather the typical implementation, of an unordered map as a hash-set. From the link above: explicit unordered_map(size_type bucket_co...
74,555,908
74,555,942
Scope of variables in Qt vs vanilla c++
Disclaimer: I am total newbie to Qt. Let's assume we have a byte array returned from a function innerFunc that is later used in another function outerFunc. QByteArray innerFunc(){ QProcess ls; ls.start("ls", QStringList() << "-1"); return ls.readAll(); } void outerFunc(){ QByteArray gotcha = innerFunc(); . . . }...
The code you have looks fine. QByteArray is like std::vector<uint8_t> or std::string and not like a pointer. It manages its own memory. It's fine to return it from a function or pass it to a function by value. The compiler will take care of copying and/or moving the data from one object to another as appropriate, u...
74,556,155
74,556,257
Is Q_PROPERTY a function-like macro in C++?
In my opinion,the using of a function-like macro in C++ is similar to the using of a common function. It seems to be like this: macroFunctionName(arg1, arg2, arg3); However, the using of Q_PROPERTY usually looks like this: Q_PROPERTY(Qt::WindowModality windowModality READ windowModality WRITE setWindowModality) As we c...
I looked in Qt's ./src/corelib/kernel/qobjectdefs.h file for the definition, and it looks like this: #define Q_PROPERTY(...) QT_ANNOTATE_CLASS(qt_property, __VA_ARGS__) ... which would make Q_PROPERTY a variadic macro. Of course all it does is expand out to QT_ANNOTATE_CLASS, which is a different macro, one that Qt's...
74,556,481
74,556,567
C++ template placeholders not permitted in function arguments
In the following C++ code, a template placeholder in argument of function fun1, and in the return type of function ret1, does not compile: template <typename T = int> class type { T data; }; void fun1(type arg); // Error: template placeholder not permitted in this context void fun2(type<> arg); // Ok void...
var1 benefits from CTAD, where all non-defaulted template arguments (i.e. none) can be deduced from the initialisation. Both function declarations however, are not candidates for CTAD, so the template argument list must be supplied even if that list is empty. Deduction for class templates Implicitly-generated deductio...
74,556,894
74,556,923
Populating protobuf fields in C++
In a codebase I see some protobuf definition as message Foo { repeated FooData foo_data = 1; } Later on these protobufs are used in a C++ method in the following way auto& bar = *protobuf_foo.add_foo_data(); but I don't see add_foo_data() defined anywhere. Is this a protobuf property that prepending add_ and adding ...
This method comes from c++ code generated from protobuf definitions. https://developers.google.com/protocol-buffers/docs/reference/cpp-generated
74,556,971
74,556,996
class member values doesn't get changed by function... "noob question"
I am trying to update the particles positions by calling a function for the class.. The values for v_x, v_y, a_x, a_y doesnt keep its new value after the function. I thought this would work because update_pos is a member function of the class. what am i doing wrong here? class particle : public sf::CircleShape { fl...
This code for (particle p : particles) copies every particle in your vector, p is a copy. So you are changing copies of the particles in your vector, not the originals. To avoid the copy you need a reference for (particle& p : particles) For a largish class like particle a reference is desirable anyway, just for effi...
74,557,018
74,582,963
Why does nvmlDeviceGetTemperature only work in debug mode?
Using VS2022 the following code snippet works in debug mode but not in release mode: nvmlInit(); nvmlDevice_t devH; auto ret = nvmlDeviceGetHandleByIndex_v2(0, &devH); if (ret != NVML_SUCCESS) DPrint("ERROR!"); u32 tt{}; ret = nvmlDeviceGetTemperature(devH, NVML_TEMPERATURE_GPU, &tt); if (ret != NVML_SUCCESS) DPrint...
Turns out the release build was loading a different version of nvml.dll. Fixed it and now it works!
74,558,080
74,558,156
call an immediate parent in c++
This is a true story of evolving code. We began with many classes based on this structure: class Base { public: virtual void doSomething() {} }; class Derived : public Base { public: void doSomething() override { Base::doSomething(); // Do the basics // Do other derived things } }; A...
What I can suggest is parent typedef in Derived: class Base { public: virtual void doSomething() {} }; class Derived : public Base { private: typedef Base parent; public: void doSomething() override { parent::doSomething(); // Do the basics // Do other derived things } }; Then af...
74,558,405
74,597,755
Creating c++ library using cmake
Dear cmake / c++ experts, I created a small library for display and input on the console. Now I would like to use it in another project. Unfortunately, even after quite some time spent in the cmake documents, I cannot get it to work. The library is here: https://github.com/HEIGVD-PRG1-F-2022/prg1f-io and uses the follo...
Thanks to @Tsyvarev, I can now rest in peace: The CMakeLists.txt of the library: cmake_minimum_required(VERSION 3.23) project(prg1f-io VERSION 0.1 DESCRIPTION "Input and display methods for PRG1-F") set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") add_library(prg1f-io STATIC src/display.cpp)...
74,558,965
74,559,285
How to make begin and end functions rvalue qualified
I am writing a file parser. Since the user can pass through the file only once I want the iterator to be accessible only from rvalue reference. MyParser parser("/path/to/file"); for(auto it : std::move(parser)){ // example for(auto & [key, value]: it){ std::court << key << '\t' << value << std::endl; } }...
A range-based for is basically syntax sugar. Your loop of: for (auto it : std::move(parser)) { statements; } is equivalent to: { auto && __range = std::move(parser); for (auto __begin = __range.begin(), end = __range.end(); __begin != __end; ++__begin) { auto it = *__begin; { st...
74,560,021
74,560,150
Should I precautionary move callables (e.g. lambdas?)
I have this striped-down example of a timer that I'd like to be instantiable with any kind of callable. Is it advisable to precautionary move the callable into a data member for efficiency? #include <concepts> #include <cstdio> #include <string> #include <utility> template <std::invocable Cb> class timer { public: ...
Your lambda has only reference captures. Moving an lvalue-reference does exactly the same as copying it. If you had [=] captures, the move would actually do something. The answer to whether or not to do this in general is: "it depends on the situation." W.r.t. performance: measure.
74,561,478
74,561,612
Why doesn't "Guaranteed Copy Elision" mean that push_back({arg1, arg2}) is the same as emplace_back(arg1, arg2)?
Firstly, I've heard that Guaranteed Copy Elision is a misnomer (as, I currently understand, it's more about fundamentally redefining the fundamental value categories, r/l-values to l/x/pr-values, which fundamentally changes the meaning and requirements of a copy), but as that's what it's commonly referred as, I will to...
but that {arg1, arg2} in push_back({arg1, arg2}) would be a prvalue (as it's unnamed) and so would be an initiliser for the vector object without being initialised itself. I assume that with "vector object" you mean here the vector element, the object that will be stored in the storage managed by the vector and which...
74,562,129
74,562,340
VSCode Debugger not Launching
I am writing a C++ program in VSCode. However, when I press F5, all it does is build the project. I tried making another simple project in VSCode to see if it works, but no luck. Here is my mini-program launch.json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existi...
Instead, the debugger for C++ isn't launching at all. Because you are missing the debugger's path in your launch.json. Add a path to the debugger within the miDebuggerPath. { "version": "0.2.0", "configurations": [ { "name": "C/C++: clang++ build and debug active file", . . "miDebugger...
74,564,118
74,567,981
prevent initializing std::optional<std::reference_wrapper<const T>> with rvalue std::optional<T>
std::reference_wrapper cannot be bound to rvalue reference to prevent dangling pointer. However, with combination of std::optional, it seems that rvalue could be bound. That is, std::is_constructible_v<std::reference_wrapper<const int>, int&&>) is false but std::is_constructible_v<std::optional<std::reference_wrapper<c...
@Jarod42 already pointed out the core reason why this code compiles, but I will elaborate a bit. The following two constructor templates for std::optional<T> are relevant to this question: template <class U> constexpr optional(const optional<U>& other) requires std::is_constructible_v<T, const U&>; // 1 template <cla...
74,564,251
74,599,531
How to build an osx universal binary with different code for intel and arm architecture
My goal is to create a universal/fat binary of my app, my understanding is that means xcode will create an intel/x86_64 build and an M1/arm build and package them together. My code uses intel intrinsics which I can replace with NEON in the arm build but to do so I need a way to create a conditional block at compile tim...
I found the solution, with help from the comments (thank you!) I was misusing the definitions, all these are defined in the header but only the relevant ones are set to 1, changing my "#ifdef x" to "#if x == 1" was the solution. #if (TARGET_CPU_ARM64 == 1) #include <sse2neon.h> #elif (TARGET_CPU_X86_64 == 1) #i...
74,564,331
74,569,538
CGAL: read off file results in 0 vertices and 0 faces
Problem Here's a simple CGAL .off read application. I was trying to read ModelNet40/airplane/train/airplane_0001.off and ModelNet40/airplane/train/airplane_0002.off respectively, but ModelNet40/airplane/train/airplane_0002.off gives a surface_mesh with 0 vertices and 0 faces. Those two off file are from ModelNet40 with...
You cannot just use operator>>() because your mesh has isolated vertices and non-manifold edges. You must instead read a polygon soup, orient the triangles and if necessary duplicate edges so that you obtain a 2-manifold, potentially wirh border edges. Have a look at this example in the User Manual. Or use directly r...
74,564,381
74,564,604
Using `std::experimental::propagate_const` for arrays
The question is simple: why can't I use propagate_const for arrays? The following line gives errors: std::experimental::propagate_const<std::unique_ptr<int[]>> ptr = std::make_unique<int[]>(1); The errors (gcc version 13.0): /usr/local/include/c++/13.0.0/experimental/propagate_const: In Instanziierung von »struct std:...
unique_ptr<T[]> is neither a pointer nor a pointer-like type. It's an array-like type. That's why it has operator[] but not operator*. It makes little sense to use *ptr on an array (for language arrays, this accesses the first element, but using ptr[0] makes it much more clear what's going on). So unique_ptr<T[]> provi...
74,564,401
74,564,559
Is it possible to define a constructor taking a universal reference with defaulted value?
When I try to define a constructor taking a universal reference with a defaulted value as a parameter like this: struct S { int x; // I know that universal ref is useless for int, but it's here for simplicity template<class T> S(const T&& arg = 123) : x(std::forward(arg)) { } // S(const auto&& arg...
You still need to specify a default argument for the template parameter. It will not be deduced from the function parameter's default argument: template<class T = int> You also are misusing std::forward. It always requires a type template argument that should be the template parameter used in the forwarding reference ...
74,565,192
74,605,440
Recommended way of wrapping a third party library c function with void* arguments in c++?
I have a third party closed source c library that interfaces with hardware. The library has some api functions that accept void * arguments to read/write and configure some io, like so: int iocall(int cmd, void * args); int iorw(int cmd, void * buff, size_t buff_size); I want to wrap these in a c++ class to be able t...
Thank you all for your suggestions and comments. I have chosen to implement the calls as seperate functions as suggested.Since they do depend on the cmd value, I used that field for dedicated naming of the functions + the appropriate struct. I wrote a small python script to automate the code creation. Again, thank you ...
74,565,979
74,566,074
Function & array [Getting Max Number]
#include <iostream> using namespace std; int getMax(numbers[], int size){ int max = numbers[0]; for(i=1; i<size; i++){ if(numbers[i] > max) max = numbers[i]; } return max; } int main(){ int numbers[6] = {31,23,45,6,7,-2}; cout << getMax(numbers, 6) << endl; ...
The only thing I see wrong with this program are syntax errors. Compiling yields this: error: 'numbers' was not declared in this scope 6 | int getMax(numbers[], int size){ | ^~~~~~~ That's because you forgot to specify the type of the variable numbers. It is an integer array. You can fix this by w...
74,566,265
74,569,293
Defining default constructor results in C2600 {cannot define a compiler-generated special member function (must be declared in the class first)
I'm learning 'modern' C++ and I'm having a really hard time discerning the issue with this code. Ball.h: #ifndef BALL_H #define BALL_H #include <string> #include <string_view> namespace ball { class Ball { std::string _color{}; double _radius{}; public: Ball() = default; B...
The particular error message you are referencing seems to be generated only by older MSVC versions (<= v19.31). It clearly looks like a bug in the compiler to me that has been fixed in later versions. When determining which in-class declaration the out-of-class definition matches, the parameter types should be compared...
74,566,292
74,582,423
Matching multiple objects in a MOCK_METHOD
I am trying to mock a method Handler::Foo to throw an exception that takes in two objects as parameters i.e SomeStruct, SomeClass. The former is created Source::Bar on the fly whereas SomeClass is passed from main. I used MATCHER but it returns a single object which doesn't match with what Foo expects (2 parameters), h...
The matcher is meant to test some conditions for a single argument, so you would need to use a separate matcher for each one. It's not really clear what you want to test here, but one way of doing what your example shows would be: class SomeClass { public: bool operator==(const SomeClass &) const = default; ...
74,566,750
74,566,778
std::equal not working when using vectors returned by a getter
While learning about how std::equal works, I was writing some test code and ran into this problem: #include <iostream> #include <vector> #include <algorithm> class Foo { public: std::vector<int> vec; Foo(std::vector<int> _vec) { vec = _vec; } std::vector<int> get() { return vec; ...
First, return by const reference const std::vector<int>& get() const { return vec; } that solves the problem. An alternative would be to have two getters returning the begin and end iterator, instead of returning the vector itself. Second, the reason for the problem is that your version of the getter copies the ve...
74,567,735
74,567,836
Using set containing strings, How do I pass in each string into function?
I am getting one error in this code where I have commented ERROR LINE. I have a strings containing set called possibleList in the function called wordle and I am trying to pass in each and every string from that set into the wordle function (to recurse) but it gives me an error about rvalue / lvalue and I am not sure h...
how to fix auto S = *itr; //copy of *iter wordle(S, floating, dict); //use S Because non-const reference can not receive temporary object (as decribed in the error message). For example: //this is error std::string &r = std::string( "xxx" ); //this is ok const std::string &cr = std::string( "xxx" ); //this is ok ...
74,568,043
74,568,529
I have a question about printf() function
I want to know why the second print function can print a? and the third print function not print a? #include <stdio.h> int main() { int i = 97; // a printf(&i); // a:print content in address &i printf("\n%s\n", &i); // why print a? printf("%c\n", &i); // why not print a? } I want to understand prin...
It depends on what is 'expected'. If it's an address (%s), it will go to and read the contents of that address. If it's a value (%c), it won't go anywhere and take it literally.
74,568,065
74,623,165
how to insert a class instance into RTTR sequential view without getting its wrapped value?
All I am creating a generic binary serializer and got block on how to insert a class instance into a sequential view. Here is the example code: #include <iostream> #include <rttr/type> #include <rttr/registration.h> using namespace rttr; struct Item { int i ; }; struct MyTestClass { std::vector<Item> seq; }; ...
Ok. I finally find the solutions as following: registration::class_<Item>("Item") .constructor<>()(policy::ctor::as_object) .property("item", &Item::i); Remember to add the RTTR_DLL in Project Properties - C/C++-preprocessor -preprocessor definition to avoid the LNK2001 error
74,568,332
74,568,660
print all possible 5 letter words using recursion
I pass in a string, "--pl-" into the function, wordle. I would like the function to return a set of strings with all possible 5 letter words with 'p' as 3rd letter and 'l' as 4th letter. This would mean that the set would return 26^3 different strings. I am trying to use recursion to do this but am not sure how to. #...
The problem in your code is that you do not use the results of the nested recursive call in wordle. In other words, when you fill the possibleList at "level 0", you then have nested calls of wordle, but it is useless currently, cause eveything it does - it does just inside it. That's why you get the result you describe...
74,568,366
74,574,192
How to get serial number in digital persona finger print sdk in c++
I downloaded and run a C++ project for Digital-persona-sdk https://github.com/iamonuwa/Digital-Persona-SDK/ finger print project.That have two projects in after install the sdk. That project only Capture and Verification function only written.Not written for get serial number. Does anyone have an sample program for sol...
Two minutes of reading the provided documentation tells you everything you need to know: Use DFPEnumerateDevices to get all device GUIDs Call DPFPGetDeviceInfo to get device info for each device in turn. Serial number is embedded in the device info as devInfo->HwInfo.szSerialNb.
74,569,082
74,569,166
How to know which header file to include for a documented function while developing for MacOS?
I'm new to macOS development, so pardon my simplistic question. Say, if I have a function. Let's take SCError for example. From the documentation I can see that I need to add: System Configuration framework But how do I know which header file to add, so that I don't get Use of undeclared identifier 'SCError'? PS. I'l...
Let Xcode help. You know the framework is "System Configuration" by looking at the documentation. So in your source file start typing: #import <Sy and Xcode will start offering suggestions. And the first one you see after entering the above just happens to be for what you need: #import <SystemConfiguration/SystemConfi...
74,569,775
74,577,159
Handling curly braces in curl/libcurl
From the command line, I have a curl request with two query parameters that use curly braces. However, one only works when URL-encoded and the other only works when it is not URL-encoded. Here's an example of a request that (weirdly) works from the command line and returns data for 3 IDs. I wouldn't expect it to work b...
These are your 4 query strings after being url decoded. TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3} TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3} TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID=1&P_ID=2&P_ID=3 TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID=1&P_ID=2&P_ID=3 None of...
74,570,656
74,570,867
A question about c++ threads exception handling
Demo code: #include <exception> #include <future> #include <iostream> #include <stdexcept> #include <thread> void func1() { std::cout << "Hello func1\n"; throw std::runtime_error("func1 error"); } int main() { try { std::future<void> result1 = std::async(func1); result1.get(); } catch (const std::exce...
First things first, std::async and std::thread are not the same thing at all. Moreover, std::async is not required to execute the callable into another thread, it depends on the launch policy you used. I would suggest you to read the documentation about std::async. But either way, any thrown exception are already handl...
74,570,683
74,574,688
Use pthread_cancel in QNX system has a memory leak, but it does not exist on the Linux system
I have a code, main thread create 2 thread(thread_1 and thread_2), I use pthread_cancel to cancel thread_1 in thread_2, but the data that I create in thread_1 will not be destructored when I run it in QNX system, but there is no problem in Linux system. It my test code, when I run it in QNX system,MyClass and MyClass2 ...
pthread_cancel is outside the scope of the C++ specification. C++ does not specify its behavior, nor inherit it from C or POSIX. The difference is simply because QNX and Linux have implemented pthread_cancel differently in a C++ environment. There is literally nothing more to it than that. I imagine that the QNX impl...
74,570,742
74,570,837
Access element from nlohmann::json?
I want to access element from a json which is the response from one query. The json structure is : json = { "result": { "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [ 20964, 347474, 347475 ], "12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6...
json.begin() will give you an iterator pointing to the first element. Then you can access its' key and value using: auto key = json.begin().key(); auto value = json.begin().value();
74,570,952
74,571,195
Initialize a character array from a constexpr string
I had code similar to this: #define STR "ABC" // ... char s[] = STR; puts(s); s[2] = '!'; puts(s); And I tried to modernize it with constexpr: constexpr char STR[] = "ABC" // ... char s[] = STR; puts(s); s[2] = '!'; puts(s); But it no longer compiles. How can I initialize a string on the stack from a constexpr consta...
C-style arrays can only be initialized by literals, not by another array or const char*. You can switch to std::array constexpr std::array<char,4> STR{"ABC"}; int main() { std::array s{STR}; // OR: auto s{STR}; } Unfortunately, it requires specifying the length of the string literal in STR, if you have C++20, you can ...
74,571,491
74,571,838
Importing text from a .txt file into a 2D array of strings
I've been trying to import text from a .txt file into a 2D array of string, but it doesn't seem to be working. Each row in the .txt file has three values/elements separated that I need to copy. This is the code: // i am only allowed to use these libraries. #include <iostream> #include <fstream> #include <string> #inclu...
One of the problems with your code is that you are only looking for , as a delimiter and not handling line breaks between the rows at all. Normally, I would suggest reading each row into a std::istringstream and then use std::getline(',') to parse each stream, but you say that you are not allowed to use <sstream>, so ...
74,571,883
74,574,807
For loop and Arrays [C++ Simple ATM system]
So I am trying to create a ATM system that lets user to input value such as Account number, account name and amount. But I can't figure out what exactly I have to do int AccNum[2]; string AccName[2]; float AccBal[2]; cout << "********** ENTER ACCOUNT **********"<<endl; for(int num = 0; num < 2; num++){ cout <...
So the code you wrote is nearly good. Too many loops in my opinion int AccNum[2]; string AccName[2]; float AccBal[2]; cout << "********** ENTER ACCOUNT **********"<<endl; for(int num = 0; num < 2; num++){ // lets call this loop a. happens 2 times cout << "Enter Account number: "; cin >> AccNum[num]; ...
74,572,355
74,640,847
What happened with TensorFlow Lite documentation for the Interpreter class
I started working on a project using TensorFlow Lite in C++. I have often looked up information about the API in the official reference. Almost all of the methods are used were listed in the Interpreter class. However, a few days ago I noticed, that the Interpreter class has been completely removed from the documentati...
I turns out it was just a temporary bug, everything works now, thanks Karim for pointing it out.
74,572,508
74,572,632
How can I change an object's attributes with function?
Forgive me if the title isn't specific enough. Let's say I want to make an RPG. I make a class for the characters. I then make an array that function as a party of characters. Then I have a function that reduced the HP of the first member of a party. ` #include <iostream> #include <string> class Chara { public...
You have two separate problems caused by C++ passing structs by copy. First, the line Chara Player[2] = {Final, Fantasy}; creates an array of Chara and initializes the members with copies of the mentioned variables. That means that the final line will not see any modifications made to elements of Player. Instead, you s...
74,573,540
74,573,619
Why can this C++ child class be constructed by objects of parent class type
class AAA { int m_Int; public: AAA() : m_Int{12} {} }; class BBB { int m_Int1; public: BBB() : m_Int1{12} {} }; class CCC : public AAA, public BBB {}; AAA a; BBB b; CCC c{ a, b }; Why can object c be constructed by parent class object? I tried to find out which standard support this syntax. I wrote...
This is aggregate initialization. Since C++17, CCC is an aggregate, where one of the requirements was relaxed from "no base classes" to "no virtual, private, or protected base classes".
74,573,922
74,573,997
What does the expression std::string {} = "..." mean?
In this code: #include <iostream> int main(void) { std::string {} = "hi"; return 0; } This type of declaration is valid in C++. See in Godbolt. What does it mean? How is it valid? For information, I tested this program from c++11 to c++20 flags as extended initializers are available from c++11 onwards.
std::string::operator=(const char*) is not &-qualified, meaning it allows assignment to lvalues as well as rvalues. Some argue(1) that assignment operators should be &-qualified to ban assignment to rvalues: (1) E.g. the High Integrity C++ standard intended for safety-critical C++ development, particularly rule 12.5.7 ...
74,574,238
74,574,293
Is it possible to do a two-step initialization of a non-movable object in the member initializer list?
Is it possible to do a two-step initialization of a non-movable object in the member initializer list using C++17? Here is the legacy API I’m working with (and yes I know it’s bad but I can’t change it) class A { public: A(int some_param); // no default, move or copy constructor nor assignment A() = delet...
You might still abuse of comma operator: C::C() : m_a{ 0xdeadbeef }, m_b((m_a.init(42), m_a)) {}
74,574,468
74,574,631
How is that possible that these two pieces of code have the same memory usage?
First case: #include <vector> int main() { const int iterations = 1'000'000; std::vector<const char *> c; for (int i = 0; i < iterations; i++) { c.push_back("qwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiop"); } } Second case: #include <vector> int main() { const int iterations = 1'000'...
A pointer takes up (usually) 8 bytes. In both cases you create a vector with a million identical pointers. So that's 8 million bytes for the vector data. Total memory usage depends on more things, like how much empty space is in the vector, and how much memory is used by the rest of the process. Both programs only incl...
74,575,199
74,576,151
Data races resolution C++
I wanted to ask for some help in solving the data races in my program. I started with a simulation of how things should work if I were using multithreading and then modified the code so that I can check if I really obtain those results but I don't know how to resolve the data races in the code. Can someone help me plea...
I don't know how to resolve the data races in the code. Then stop using std::thread, and especially stop passing references to functions on those threads. Here is one way you could avoid passing any references between threads: #include <cstdlib> #include <iostream> #include <random> #include <future> #include <algori...
74,575,308
74,575,409
waiting threads status while mutex gets released at the end of a loop in wait_for function in C++
Suppose we have four threads in this order (D, C, B, A) waiting in a queue, and 'r.cv.notify_all()' just gets invoked, and suppose thread A (first thread in the queue) locks the mutex and the lambda returns true, after thread A reaches the end of the while loop, the lock is going to be released as it follows the RAII r...
after thread A reaches the end of the while loop, the lock is going to be released ... ... and, that's it. That's the end of the story. The lock is released. We're outta here. ... or still the lock belongs to thread A No, it does not belong to any thread. We've just determined that the lock is released. A released ...
74,575,620
74,584,466
How to make an overloaded function a dependent name, so two-phase lookup finds it?
Look at this example: template <typename TYPE> struct Foo { static constexpr auto a = bar(TYPE()); static constexpr auto b = static_cast<int (*)(TYPE)>(bar); }; struct Bar {}; constexpr int bar(Bar) { return 42; } int main() { auto a = Foo<Bar>::a; auto b = Foo<Bar>::b; } At the definition of Fo...
You can’t, unfortunately: even if bar were somehow dependent, ADL would never be performed for it since it isn’t a function being called. (Put differently, unqualified names that aren’t the function name in a dependent call are always looked up in the template definition.) The closest you can do is to use (and specia...
74,576,092
74,576,300
How to get my pi generating code to cut off at 300?
I am trying to write a program that allows for pi to be gernated to the 300th digit, but I cannot seem to figure out how to cut it off at the 300th digit. As of right now the code was ran forever and any other method I have tried has not worked like cutting off at a specfiec time, however this is not what I need to hap...
You are stating that you generating 300 digits, however this for-loop is broken: for(300;) It is not valid C++ code, as a for-loop is structured like this: for ( declaration ; expression ; increment) While all 3 segments are optional, you do need at least two semicolons (;) for a valid syntax. To achieve a for loop ...
74,576,426
74,576,635
Iterate using iterators on nlohmann::json? Error: invalid_iterator
Continuing my previous question here, Now I want to insert the keys and values present in the below json into a std::vector<std::pair<std::string, std::vector<uint64_t>>> vec; Keys here are this strings: 12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq , 12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT values corresponding the...
I think you're over complicating this. You can iterate over a json object the same way you would any other container using a for loop: #include "nlohmann/json.hpp" #include <iostream> int main() { nlohmann::json j = nlohmann::json::parse(R"({ "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [ ...
74,576,589
74,576,943
Force decay of string literals (const char array) to ptr
In the following example I try to emplace_back() a string literal and a string_view into an std::pair of string_views. However, my problem is that emplace_back() takes up the string literal as a const char array and doesn't decay it to a pointer. The consequence is that emplace_back() can't find std::string_view's cons...
A std::piecewise_construct constructor (as you are trying to use here for the std::pair construction) expects the rest of the arguments to be std::tuples with each tuple holding the arguments to construct one of the pieces (e.g. pair elements). You are not passing tuples as second and third parameter, so it can't work....
74,577,005
74,577,557
c++17: function template lambda specialization
Motivation: one has a function that accepts either a lambda or a value (for simplicity it can be either const char * or std::string) like following template <typename LambdaOrValue> void Function(LambdaOrValue &&lambda_or_value) { // The idea here is to have sort of a magic that // evaluates a lambda if an argument...
Since you have access to C++17, why not use std::is_invocable, if constexpr and decltype(auto) combo? template <typename T> auto Evaluate(T &&t) -> decltype(auto){ if constexpr (std::is_invocable_v<T>) return t(); else return std::forward<T>(t); }
74,578,188
74,578,940
Can't get rid of memory leak in c++
I'm trying to dynamically increase the capacity of an array but I keep getting memory leaks when running with valgrind. This is the code I'm running(nothing wrong with it shouldn't be the problem): //My struct struct ArrayList{ int size; //amount of items in a array int capacity; //the capacity of an arr...
Your doubleCapacity() function is implemented all wrong. It is creating a temporary array of the original size just to save a redundant copy of the current items. Then it creates a new array of the desired capacity and copies the temporary items into it. You don't need that temporary array at all, you can copy the orig...
74,578,963
74,579,020
Why can't constructors/destructors have alias names in C++?
Take this class: class Foo { public: using MyType = Foo; MyType* m = nullptr; //ok MyType* functor() { //ok return nullptr; } MyType() = default; //error ~MyType() = default; //error }; Why can you use alias names for members, but not for constructors or destructors?
m is a pointer to an instance of a type, which is aliased. OK. functor() returns a pointer to an instance of a type, which is aliased. OK. But a constructor/destructor is not itself a type, so you can't use a type alias for them. They must be named after the type they belong to. That is just the way the syntax works