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
66,545,235
66,545,391
Why does this pointer points to wrong object inside member's constructor during object initialization?
Following code prints the same address twice: #include <iostream> struct B { B() { std::cout << this << std::endl; } }; struct A { A() { std::cout << this << std::endl; } B b; }; int main() { A a; } Why does this pointer points to A inside B's constructor?
B is an empty class and because of that is a standard layout class. A contains only one (non static) member which is a B. It has no virtual methods. Because of that it is also a standard layout class. For standard layout classes, the standard requires the address of an object to be the same of the address of its first ...
66,545,323
66,572,117
Overloading addition operator in child class in C++
Okay guys imagine situation where I have a parent class and a successfuly overloaded + operator: class parent { public: int a; int b; friend parent& operator+(parent& mother, const parent& father) { //add stuff } } class child : public parent ...
I hope the following helps. class parent{ public: int a; int b; parent& operator+=(const parent& rhs){ this->a += + rhs.a; return *this; } parent(int aa=0, int bb=0):a{aa},b{bb}{} friend parent& operator+(parent& mother, const parent& father){ mother.a += father.a; ...
66,545,405
66,545,541
How to satisfy totally_ordered for a custom type without spaceship comparison operator (ranges::is_sorted, ranges::sort)
Consider the following code: #include <vector> #include <algorithm> #include <ranges> #include <cassert> // The type is defined in legacy code and we can not change it struct A { int a; }; bool operator <(const A &a1, const A &a2) { return a1.a < a2.a; } int main() { assert(A {} < A{}); // OK std::vector...
You need to provide an == as well as <=>. std::ranges::less requires std::totally_ordered not just std::strict_weak_order, so == is also needed. Unless defaulted, <=> doesn't synthesize ==. #include <vector> #include <algorithm> #include <ranges> #include <cassert> // The type is defined in legacy code and we can not ...
66,545,471
66,545,534
Compiler Insists on Referring to Non-existent Constructor
What I'm trying to do is construct a shadow (or enemy) based on the attributes of the Player. I have two Shadow class constructors: one that takes a player and boss parameters and one that only takes a player parameter. If boss is true, the shadow will get better stats. My code: class Player { public: ...
The code Shadow(player); // error here doesn’t do what you think it does. It’s equivalent to the following code: Shadow player; That is: you’re attempting to declare a local object player of class Shadow and default-construct it. This fails due to the missing constructor. You want to call a delegating constructor. Fo...
66,545,503
66,545,711
Derived struct with same field names
I have two structs pins1_t & pins2_t with the same field names but different values. pins2_t is derived from pins1_t namespace pins { struct pins1_t { int A = 1; int B = 2; int C = 3; int D = 4; }; struct pins2_t : pins1_t { int A = 6; int B = 7; int ...
The members in your derived class shadow the members in your base class. This is almost never what you want (since, as you noticed, it doesn’t work). Since these are just variables anyway, there’s no need to shadow the declarations in the child class. Just initialise the base class members: struct pins1_t { int A =...
66,545,585
66,555,261
Storing a matrix where every second element is 0
I have to store matrices where the non-zero elements are arranged in a "chess table"-like pattern (1,1), (1,3), (2,2), (2,4), etc. I can't store the zero elements, but I also need to implement addition and multiplication. The elements are stored in this vector: std::vector<std::vector<int>> _v; And I have size_t n,m fo...
I would strongly recommend: Storing data in a simple one-dimensional valarray or vector of integers. The size of the vector would be "width * height / 2", since you won't store every second element. Implementing your own get/set methods for accessing items. In these methods, you'll perform the transformation from x, y...
66,546,051
66,579,985
PCL not properly installed with vcpkg
I've installed the PCL with the vcpkg using ./vcpkg install pcl:x64-windows. After a while I've noticed that concave_hull.h, convex_hull.h and qhull.h are not installed with the rest of the library. Additional information of what I'm working with: vcpkg tag (2020.11.01) OS Windows 10 VS Community 16.8.3 For completi...
After a while I solved the problem by switching to the reentrant qhull version following this guide: http://www.qhull.org/html/README_r.txt. You have to copy the concave_hull code into files (hpp, h and cpp) within your own project. Fix the headers and remove the #ifdef HAVE_QHULL in every file and add this chunk of co...
66,546,257
66,546,325
In C++, can we create a class for each integer?
I need to create a class NumberModuloN. For each positive integer N, there should be a distinct class. What is the most elegant way to do this? Here are some more details: The data consists of a single integer in the range 0 to N-1. It can be modified using some public operator overloading methods like +, *, -, ++, etc...
You might use non-type parameter in template, so, something like: template <std::size_t N> struct NumberModuloN { /*..*/ };
66,546,377
66,546,483
Setting an array to a pointer value
I'm not a C++ developer but found my self doing this. What does r in the following code example represents, and what is the c# code equivalent? #include <iostream> using namespace std; int main() { cout<<"Value:\n"; uint32_t k[62]; uint32_t* r = k; *r++; cout<<*r; return 0; }
uint32_t* r = k; makes r point to the first element of the uninitialized array k. *r++; increments r to point to the second element of k, and then dereferences the value of the second element (which is undefined). The deference is a no-op because the result is not used, so the statement does the same as just r++;. (*r)...
66,546,637
66,547,159
boost::asio internal queue capacity
I was attempting to understand Boost Asio implementation and limitations. As I understand from here - https://www.boost.org/doc/libs/1_75_0/doc/html/boost_asio/overview/core/basics.html When you do an async_receive_from call on a socket, the following things happen The socket forwards the request to the I/O execution ...
There's no buffering in ASIO whatsoever; ASIO is a thin wrapper around native OS select/epoll/kqueue/IOCP (depending on OS) as well as non-blocking send/recv calls. Your question can thus be re-phased as "what happens when I don't call recv fast enough?". As it turns out, that question has already been asked before, se...
66,546,906
66,616,284
Is it defined behavior to place exotically aligned objects in the coroutine state?
Edit: Thanks for everyone's answer and replies. Language Lawyer's answer is technically the correct one so that's accepted, but Human-Compiler's answer is the only one that meets the criteria (getting 2+ points) for the bounty, or that is elaborated enough on the question's specific topic. Full question Is it defined...
From [basic.align]/3: It is implementation-defined whether any extended alignments are supported and the contexts in which they are supported. So the answer is: implementation-defined. The second part of the sentence sounds like it is possible that an implementation may support creating objects of over-aligned types ...
66,547,182
66,547,282
Is there a way to use a particular C function/symbol as output by nm
I'm trying to analyse a compiled file for cybersec learning purposes and want to use a particular function. Here is the output of nm --defined-only ./compiled_file: 0000000000200d98 d _DYNAMIC 0000000000200f88 d _GLOBAL_OFFSET_TABLE_ 0000000000000ba0 R _IO_stdin_used 0000000000000d64 r __FRAME_END__ 0000000000000bfc r ...
Yes, it is possible. The point of having exported symbols in shared libraries is to be able to use them - after all. In C, you can do this either by linking the library to the application (not really an option for python), or runtime loading the library and finding the required symbol (on linux: dlopen, dlsym). The man...
66,547,429
66,548,498
What does std::vector::insert does, if it is fed by reverse iterator?
I am populating vector keeping it ordered in the following manner vector<int>::iterator it = upper_bound(arr.begin(), arr.end(), value); arr.insert(it, value); Now I would like to keep reversed order. What if I do vector<int>::iterator it = upper_bound(arr.rbegin(), arr.rend(), value).base(); arr.insert(it, value); w...
If it2 is normal iterator, then, for example when searching for 7 in {10, 3, 1} it2 will point to 10 and insert will insert 7 BEFORE 10. Except that a reverse iterator dereferences to the value next to it's base (following from the pov of the base type, preceding from the pov of the reverse). You can observe this by ...
66,547,830
66,560,475
EEPROM protocol misconception
I am currently using a michrochip's eeprom ( 24cw160 ) connected with an stm32f4 (11RET) via i2c. The configurations and the connection seem to work as my logical analyzer prints some i2c messages (with ACK) and I can send data and receive data back. After reading the reference manual(especially pages 13 and 18 that ha...
Thanks to the comments I managed to send a byte at whatever address I want . One noticed error on the previous code is the MemAddress parameter( third parameter of HAL_I2C_Write_Mem) ,because my eeprom is 11 bit addressable I should declare to hal that it is 16 and not 8 as the 5 extra bits are ignored bits ,but less t...
66,547,904
66,548,309
How can I assign value to an structure from another structure?
I have two structs as following: struct command{ string name; int time; }; struct job{ queue<command*> tasks; int ID = 0; jobState *table = NULL; int time = 0; }; Now I want to assign values to my structures: What I have done so far is: job a; a.time = 20; a.ID = 2; My problem i...
I would recommend not to use a pointer to command as the struct is fairly simple. #include <queue> #include <string> #include <deque> struct command{ std::string name; int time; }; struct jobState {} *jobtable = nullptr; struct job{ std::queue<command> tasks; int ID = 0; jobState *table = N...
66,548,293
66,549,176
c++ program giving seperate inputs but few when applied multiple inputs
This is a codechef beginner problem. I know it can be done in much easier ways, but I thought to try recursion here. My program is giving correct answer when I give only one input at a time, but when I run given testcases it only shows output for first two. https://www.codechef.com/problems/CIELRCPT #include <iostream>...
There are few logical errors in your code, I'll try to point them one by one- 1.) Remove line 47 because when something like this happens your main function will be stopped(return 0 stops the main function and thus program) and your program will not run for rest of the test cases. You can use boolean flag for that purp...
66,548,370
66,549,644
Empty ListView when integrating C++ Models in QT
Created C++ List Model to integrate with the QML to populate list view contains a check box and text view of 100 entries as given below todomodel.cpp File #include "todomodel.h" ToDoModel::ToDoModel(QObject *parent) : QAbstractListModel(parent) { } int ToDoModel::rowCount(const QModelIndex &parent) const { if...
You are specifying that your model has 0 zero rows when the parent is invalid (the root-level). You should change return 0; with return 100;: int ToDoModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) //changed here return 0; // FIXME: Implement me! return 100; }
66,548,657
66,566,011
Quote a string using {fmt}
Is there any way to print a string as quoted using {fmt}? Here is an example code showing what I want to achieve: fmt::print("Hello {}!", "Terens"); I want the code to print Hello "Terens"! instead of just Hello Terens!. EDIT: I want to use the API for printing different data not known beforehand (I am writing this fo...
I want to use the API for printing different data not known beforehand (I am writing this for a library, so I specifically want a quoted output when the data is a std::string or std::string_view. The following code: #include <fmt/core.h> template<typename T> const T& myprint_get(const T& t) { return t; } std::st...
66,549,043
66,549,099
Scope of `using namespace` in Unnamed Namespace
Why is the using directive using namespace std; in when enclosed in an anonymous namespace behaves as if it appeared at global scope? #include <iostream> namespace x { using namespace std; void g() { cout << 1; } } int main() { cout << 1; // compiles fine if `namespace x` is replaced with `namespace` } ...
An unnamed namespace is equivalent to essentially writing: namespace __compiler_generated_unique { } using namespace __compiler_generated_unique; So it's like having a using directive at global scope. And using directives are transitive. For a normative reference, here it is from n4861 (The C++20 standard draft): [...
66,549,296
66,549,341
Return 3 elements from function C++
I want to solve a problem, which needs the largest sum of the subarray and it's position. The program's solution is in pseudocode from the book Introductions to algorithms, however it contains a returning which contains 3 elements (low,high,sum). What can I do about this? How can I return three elements? The program is...
You could write a struct containing 3 ints and return that from the function: struct data { int low, mid, high; }; data fun( /* args ... */ ) { // ... return {low, mid, high}; } Alternatively, if you don't want to name the structure explicitly, you could just return a std::tuple containing 3 ints. std::tuple<i...
66,550,005
66,552,237
Is this Visual Studio compiler error 'divide or mod by zero' a bug?
I'm on Visual Studio 2019, and when I try to compile this: #include <iostream> int main() { (-2147483647 - 1) / -1; INT_MIN / -1; } I get a compiler error in both cases: C2124 'divide or mod by zero' There's no divide or mod by zero as far as I can see.
Draft n1570 for C11 says at 6.5.5 Multiplicative operators §6 (emphasize mine): When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and...
66,550,019
66,550,320
How to concurrently write to a file in c++(in other words, whats the fastest way to write to a file)
I'm building a graphics engine, and I need to write te result image to a .bmp file. I'm storing the pixels in a vector<Color>. While also saving the width and the heigth of the image. Currently I'm writing the image as follows(I didn't write this code myself): std::ostream &img::operator<<(std::ostream &out, EasyImage ...
The fastest method to write to a file is to use hardware assist. Write your output to memory (a.k.a. buffer), then tell the hardware device to transfer from memory to the file (disk). The next fastest method is to write all the data to a buffer then block write the data to the file. If you want other tasks or threads...
66,550,642
66,550,849
Is there a way to view compiler generated code in Visual Studio?
Is there a way to view C++ compiler generated code in Visual Studio? What I mean by generated code is: compiler generated functions, function call transformations, casts during polymorphic behavior etc. and not assembly language
If you want to see the generated assembly code (and/or machine code), you can select this in the properties, either per-project or per-source file. Various levels of detail are available. Right click the project or source file in the Solution Explorer, select the "Properties" command and then, in the "C/C++" tab, selec...
66,550,866
66,553,225
Move a file that user chooses to another directory
I'm trying to make a program that moves a file (like file.txt) specified by the user to a directory that he also specifies. I tried using the move() function, however I don't quite understand it yet, so I tried with the rename() function and used this site's code as help. I've worked with the rename() function and move...
First off, don't double up on the slashes when typing them in at the command prompt at runtime, if that is what you are doing. Escaping slashes only applies to string literals in code, not runtime data. That said, you are not allocating enough memory to hold the user's input. When initialized with " ", your oldDir[] ...
66,550,871
66,639,525
Overwriting first element of a vector changes contents of last element of vector
When writing my code, I noticed that running the code returns incorrect results, it turns out something in my code is changing the vector of handles for my coroutines and narrowed it down to one line of code where I overwrite an existing element of the handle vector with a new element. Doing that also changes the conte...
It turned out that changing the return type of final_suspend() from std::suspend_never to std::suspend_always fixed the issue.
66,551,001
66,555,677
Is there any way to get the class data from the animation blueprint asset obtained from the Content Manager?
I have a custom C++ class named UHandsAnimInstance : UCLASS(transient, Blueprintable, hideCategories = AnimInstance, BlueprintType) class SENSORIALSDK_API UHandsAnimInstance : public UAnimInstance { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Fingers) bool isRight = t...
The Assets within the Content Browser are not real "instances" of those Objects. If you want to be able to select the Asset Type from the Content Browser and input it into a Property, you will be required to use a TSubclassOf<UHandsAnimInstance> type. This will give you a UClass* to the Asset Type. Keep in mind this is...
66,551,513
66,551,731
Using std:: vector with MPI_Gather crashes while c-style array works fine
I'm practising this code and it works with a C-style array but is not working with std::vector. I do not know the problem but it seems it cannot terminate the process. Does anyone know what's wrong with this implementation? #include <fstream> #include <iostream> #include <vector> #include "mpi.h" using namespace std; c...
You cannot just use the address of a std::vector where a C-style array is expected as an argument. Instead, use the data() member function: MPI_Gather(x.data(), N, MPI_INT, &single_arr, N, MPI_INT, root, MPI_COMM_WORLD); Alternatively (especially if you are using a pre-C++11 compiler), you can pass the address of ...
66,551,590
66,562,688
How to remove entire sentence if it is containing string
I need to remove the entire sentence from the string if it is containing a pattern. Here I have the pattern "Link" or "link", if it is present in the string, I need to remove the entire sentence containing it. std::string subject = "This is previous sentence. This can be any sentences. Link 2.1.19.3 [Example]. This is ...
I'd recommend std::regex redundantSee(R"(\W*\b[Ll]ink\b(?:\d+(?:\.\d+)*|[^.])*[.?!])") See its online demo. Note the raw string literal syntax, R"(...)". The string pattern can be simply put inside instead of ... without any additional escaping. Regex details: \W* - zero or more non-word chars \b - a word boundary [L...
66,551,737
66,556,138
Write and read boost into POSIX pipe (No boost.iostream)
I have a setup that uses boost's serialization to archive objects to a file. I want/need to do the same but writing to POSIX pipes instead of basic files. A simple packet: #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/serialization/base_object.hpp> #include <b...
Together, Boost Asio + Process can also do this: Using Boost Process Live On wandbox size_t write(Packet* packet) { boost::asio::streambuf sb; { std::ostream os(&sb); boost::archive::binary_oarchive oa(os); oa << packet; } boost::asio::io_context ctx; boos...
66,552,009
66,552,158
ifstream from next/new line in c++
I am having set of data stored in a file which are basically names. My task is to get all the first letters from each name. Here is the file: Jack fisher goldi jones Kane Williamson Steaven Smith I want to take out just first word from each line(ex. jack, goldi, kane, Steaven) I wrote following code for it, just to ta...
Name_file>>endl; is always wrong. Even then, you can't use >> like that, it will stop on a space, which is why when you remove endl you see the problem that first and last contain only the first line. Use std::getline to loop over your file instead and get the full names, then split the line on the first space to get t...
66,552,123
66,552,264
Is there a way to load .h file for current .cpp file in Visual Studio 2019?
I have been developing in Visual Studio 2005 for ages, finally bit the bullet and moved to Visual Studio 2019. In VS2005 I have a macro that loads .h file for current .cpp file when I press Ctrl+H. I understand that macros are not supported in 2019 internally and that there are plugins that enable them, but they lack m...
No macro nor plugin is needed. Just rightclick the editing pane within Visual Studio 2019 (while editing your .cpp source file), and select Toggle Header/Code File from the popup menu
66,552,336
66,552,734
How to generate an inline constexpr plain array of array in c++17
The question I am writing a software in c++17 for which performances are absolutely critical. I would like available in a few key functions constants in arrays themselves in arrays. It matters that both these array are accessible by a integer value in such (or similar) manner : int main() { for (int i = 0; i < size...
Just use std::array<std::span<int>, N>, which is a fixed size array of spans of different sizes. To generate this, use an std::index_sequence Header: constexpr std::size_t size_of_A = 500; extern const std::array<const std::span<const int>, size_of_A>& A; Implementation: constexpr std::size_t size_of_B_in_A(std::size...
66,552,640
66,553,980
OpenGL Application console not closing
I am using Visual Studio Community and I am trying to create OpenGL application. I am using GLFW to open a window like this: int main() { //Init stuff int width = 1920; int height = 1080; glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); ...
As mentionned in the comments, the problem comes from the destruction of your buffers : the program tries to call glDestroyX (in buffers destructors) after the OpenGL context was destroyed, which throws errors that GL_Call tries to handle using GL context so it also throws error itself and so on. To solve that, declare...
66,552,813
66,553,770
How to read file into vector of tuple?
I would like to read a text file, which contains the following data: Wogger John 2 6.2 Bilbo 111 81.3 Mary 29 154.8 The data separated by tabulator. The problem is if the string contains a space (for example: 'Wogger John'), then the program doesn't work. THe program does work if I replace string 'Wogger John'...
while (std::getline(File, name, '\t') >> a >> b) { data.push_back(std::tuple<std::string, int, double>(name, a, b)); } std::getline reads up to and including a delimiter, then discards the delimiter. It defaults to the delimiter being a newline; here we make it a tab.
66,552,976
66,838,099
Flutter C++ Memory allocation causes jank on raster thread - Android NDK Dart FFI
I have a flutter app which uses Dart ffi to connect to my custom C++ audio backend. There I allocate around 10MB of total memory for my audio buffers. Each buffer has 10MB / 84 of memory. I use 84 audio players. Here is the ffi flow: C++ bridge: extern "C" __attribute__((visibility("default"))) __attribute__((used)) vo...
The actual cause, after discussions (in the comments of the question), is not because the memory allocation is too slow, but lie somewhere else - the calculations which will be heavy if the allocation is big. For details, please refer to the comments and discussions of the question ;)
66,553,306
66,553,428
Why does my std::function have no viable conversion?
My Compressor class has field QMap<QString, std::function<DataList(Compressor&, DataList &)> &> *techniques; and static method static DataList & sndStep(DataList &l);. Their type definitions: typedef QPair<QPointF, QString> Data; typedef QList<Data> DataList; typedef QList<DataList> DataTable; I'm trying to create a Q...
Here you are about to define f as a function taking two arguments (Compressor&, Datalist&) and returning DataList: std::function<DataList(Compressor&, Datalist&)> f but that's not the signature of the lambda: [] (DataList & l) { return &Compressor::sndStep(DataList & l); }; which only takes one argume...
66,553,905
66,555,025
_mm_max_ss has different behavior between clang and gcc
I'm trying to cross compile a project using clang and gcc but I'm seeing some odd differences when using _mm_max_ss e.g. __m128 a = _mm_set_ss(std::numeric_limits<float>::quiet_NaN()); __m128 b = _mm_set_ss(2.0f); __m128 c = _mm_max_ss(a,b); __m128 d = _mm_max_ss(b,a); Now I expected std::max type behavior when NaNs a...
My understanding is that IEEE-754 requires: (NaN cmp x) to return false for all cmp operators {==, <, <=, >, >=}, except {!=} which returns true. An implementation of a max() function might be defined in terms of any of the inequality operators. So, the question is, how is _mm_max_ps implemented? With {<, <=, >, >=}, ...
66,554,061
66,554,327
Access to member function in class using pointer to other class
I have a simple class with private field and constructor with public member function to print all object names from other classes. Here is code from header file: class Class8 : public Class6, public Class7 { private: std::string object_name; public: Class8(std::string object_name_); voi...
The reason this occurs is because pointer types matter. Your pointer_to_six points to a class8 object which does contain print_all, but it is of type class6 *. So, it is dereferenced as a class6 object, and class6 does not contain a member named print_all. There are a few solutions. You may use casts to convert the poi...
66,554,116
66,554,182
How to ignore float if a comma is present?
I'm writing a program that takes a float as input (For example asking for height in cm). Is there a way to ignore the input given by the user if there is a comma instead of a dot? For example: If the user inputs 1,90 instead of 1.90 I want it to stop and say that, that is not a valid number and that the format requirem...
A clean way to do that would be to read the input as string, do all your validation and parsing, then reject/accept the input accordingly. Here's a simplified example: #include <string> #include <iostream> int main() { std::cout << "Enter value: "; std::string input; std::cin >> input; // get input // Make su...
66,554,806
66,555,943
C++ is there a way to find a memory adress from another application from its value?
How can I find a memory address that I can afterwards change/read by just using that memory address' value using C++? For example like how you can find the memory adress of something by just searching up a value in Cheat Engine. I searched it on Google for about an hour now but I still couldn't find anything that would...
For example like how you can find the memory adress of something by just searching up a value in Cheat Engine. So what you want is to know the memory address at which something can be found in a process. For example, let's say that notepad.exe has the bytes 68 65 6c 6c 6f somewhere in memory and we want to figure out...
66,555,338
66,559,706
A good way to print array of each rank after using MPI_Scather
I want to print the array of each rank in a proper way. First, the problem with this code is that output is not ordered, and second, I just want to eliminate the use of if the condition for printing the data of each rank. Is it possible? #include <fstream> #include <iostream> #include <vector> #include "mpi.h" using na...
First, the problem with this code is that output is not ordered, and second, I just want to eliminate the use of if the condition for printing the data of each rank. Is it possible? This is not how MPI is meant to be used, actually parallelism in general IMO. The coordination of printing the output to the console amo...
66,555,344
66,555,465
Calling the release/debug mode with "true/false" in command line
I'm currently working on a C++ program with lots of .cpp and .h files that requires creating a Makefile. Now, I've been asked to accept two command line parameters in order to run the program (eg.. ./huntwumpus false). The first one has to be the name of the program such as: huntwumpus and the second command line has t...
Given you are required to pass it in the command line, this means you need a runtime debug mode. Thus no changes in the Makefile needed. The easy solution is to simply have a global variable with the setting: bool debug = false; And then parse the arguments in your main(): int main(int argc, char *argv[]) { if (ar...
66,555,775
66,557,144
C++ Creating a Menu and passing Args
So i want to basically call a void and store my menu, Menu Number, Text, and the function(void) im defiently doing this wrong however i can't figure it out. void AddMenu(char* text, int Menu, void* func) { nMenu[Menu] = Menu; sMenu[Menu] = text; fMenu[Menu]* func; } So the idea would be void Ad...
Try something more like this: typedef void (*menuFunc)(); int nMenu[32]; const char* sMenu[32]; menuFunc fMenu[32]; void AddMenu(const char* text, int Menu, menuFunc func) { nMenu[Menu] = Menu; sMenu[Menu] = text; fMenu[Menu] = func; } void SomeVoid() { ... } void AddMenu("Main Menu", 0, NULL); void...
66,556,076
66,556,373
how can i go about using a comboBox value in an object to do a calculation
I'm making a game based on Marcus Du Sautoy's book "Number Mysteries" in which they describe a game where a team of three football players with prime numbers on their shirt use the prime numbers to see whether they beat the opposing side. Basically, I want to set these three prime numbers on a "Player Selection Screen"...
The PlayerSelection object should have signals for every value change it provides, and then the Player object should have a slot that is used to receive that value and update its internal state appropriately. The PlayerSelection object would need a state variable that describes whether any of the selections were made. ...
66,556,184
66,556,739
Efficient substitute for std::map::insert_or_assign with hint
I'm trying to write a substitute for std::map::insert_or_assign that takes the hint parameter, for build environments that don't support C++17. I'd like for this substitute to be just as efficient, and not require that the mapped type be DefaultConstructible. The latter requirement rules out map[key] = value. I've come...
As per NathanOliver's comment, where he cited the cppreference documentation for std::map::emplace: The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately. If we assume the same applies for std::map::e...
66,556,199
72,383,745
Why do I get an EntryPointNotFoundException error when using .NET 6.0, but not when using 4.7.1?
I am creating a DLL using C++ and importing it using C#. I have no problem compiling the DLL, and it works fine when calling it from .NET 4.7.1. However, when I try to call it from .NET 6.0, I get an EntryPointNotFoundException error: Unhandled exception. System.EntryPointNotFoundException: Unable to find an entry poi...
I could reproduce the issue locally with the setup your described using Visual Studio 2022. Preliminary note 1: The naming of all the .NET stuff can be quite confusing: ".NET" is not ".NET Framework". And ".NET Core" is the predecessor of ".NET". Roughly. See the documentation and this or this post. Preliminary note 2:...
66,557,887
66,558,196
Can I use C++ templates to implement two classes which only differ by one field type?
I am trying to implement a Controller class for two systems. Each Controller uses a Solver class instance. I already have two Solver class implementations: class AbstractSolver { virtual void func() = 0; }; class System1Solver : AbstractSolver { void func() override; }; class System2Solver : AbstractSolver { void func(...
Another option is to use polymorphism: keep a pointer to your AbstractSolver in the single Controller class, and pass appropriate concrete solver to the controller's constructor.
66,558,148
66,558,189
Move assignment operator is not moving my shared_ptr
I'm having some trouble with my move assignment operator, and maybe I'm just misunderstanding what's going on. My SignalHolder object below is meant to hold a shared pointer to a Signal object and call its detach() method as soon as the SignalHolder is destroyed. Since destroying the object automatically causes the s...
Parameter c is declared as const, it can't be moved. Move operation is supposed to perform modification on the object to be moved. In _target = std::move(c._target);, the copy assignment operator but not move assignment operator of std::shared_ptr gets called. (The move assignment operator of std::shared_ptr takes rval...
66,558,326
66,559,256
Issue with C++ Vector implementation
So I have an interesting issue with some code that I copied from my text book for notes. I like to type out these little example programs and run them to help myself understand them. With that said, I actually typed this program out word for word but I am getting an error after hitting compile and run. I am not sure if...
My IDE was outdated as stated by @yzt and @Stephen Newell. After updated to a newer version the code is performing as expected. Furthermore, the () needed to go back to their original {} as stated by @Jerry Jeremiah and @Stephen Newell. My understanding of the outdated IDE is a direct contribution from @yzt's comment. ...
66,558,785
66,561,645
Using QT and VS run CGAL5.2's official examples
I downloaded the official example which is CGAL-5.2\examples\Triangulation_2 from the website CGAL.org. I successfully cmake the examples. Then I opened Triangulation_2_Examples.sln from G:\MyCGAL_code\code_1\Triangulation_2\build by VS2017. I also successfully built all projects (without errors). I then click the deb...
The program draw_triangulation_2 takes a filename as input (the file must contains a set of 2D points). Without parameter, it takes data/triangulation_prog1.cin by default. Thus the working directory must contains a directory data and this directory must contains a file triangulation_prog1.cin. Otherwise, the triangula...
66,559,012
66,591,204
How to overlap nonblocking communication
I know that Nonblocking communication is not blocking the code, such as MPI_Isend will send the data immediately. But when we have some all-to-all communication and we need to read this data we need to use MPI_Wait to get the data first. for all-to-all communication the first thing that is coming in my mind is somethin...
I know that None-blocking communication is not blocking the code, such as MPI_Isend will send the data immediately. This is not accurate the data is not send immediately. Let me explain in more detail: MPI_Irecv and MPI_Isend are nonblocking communication routines, therefore one needs to use the MPI_Wait (or use MPI_...
66,559,693
66,561,052
Finding equally spaced points given a set of points with line segments in between
I'm currently programming a map, and am trying to split street segments into equal parts. If a street segment is straight it's a simple matter of dividing the length of the street segment by whatever factor you want. However, curvy streets are much harder to divide into equal parts, as they are made up of multiple segm...
Your resulting path + will have equidistant points, but your original path o has segments of different length. You have two different things to deal with: the indices curr and next of the start and end points of the current segment and the interpolation variable t for that segment. Here's an example of curr / next va...
66,559,980
66,560,088
Problems with overloading [] operator (c++)
I'm trying to write a small class "Array", but I have a problem when I want to overload [] operator for this class. The returned value must has int value but it has Array&. There is my code: Array.h: #ifndef ARRAY_H #define ARRAY_H #include "QTableWidget" class Array { public: Array(); Array(int size); Ar...
My currentArr is a pointer, so I must do this: (*currentArr)[index];
66,560,489
66,561,226
Reconfiguring QML controls programatically
So, I'm developing a Qt Quick (QML) application, and I have this particular task: The app will handle different kinds of devices, and not all devices have the same characteristics. For example, since these are SDR devices, one can need one gain slider, while the other has 3 independent ones. The backend will read the d...
There's not much information to go off here, so my answer will be mostly untested pseudo-code. Updated answer after reading your comment: I would have a DeviceManager that stores a list of each device that's plugged in. A DeviceModel would listen to changes in that list, and expose a device role (you could also have a ...
66,561,007
66,561,082
enum class varidic parameter pack to expand with binary operator
There is a class template working as enum class flags container: template<typename E> requires is_enum<E>::value class flags { public: flags( E value ) noexcept : m_value( to_underlying( value ) ) {} flags operator|( const E value ) noexcept { m_value |= to_underlying( value ); } flags & opera...
Your syntax for the fold expression is incorrect; the fold expression needs to be in parentheses: void apply( flags<mode> m = ( MODES | ... ) ) {} // ^_____________^
66,561,119
66,561,265
How to access a class member variable in an object (which is also a member of the class)
Hi I want to accomplish the following. I can create a constructor in the Lower class that takes the object of Upper and in Upper I can pass its own reference to lower but that would create cyclic dependency errors. Could someone please help me with how to handle this? #include<iostream> using namespace std; class Low...
can pass its own reference to lower but that would create cyclic dependency errors. Not if you forward declare Upper and move the definition of doSomething after the definition of Upper like so: #include <iostream> class Upper; // forward declaration class Lower { public: // declaration only, reference to inc...
66,561,448
66,561,601
How to properly return in a switch case?
Let suppose the following example: int main() { int value=1; switch( value ) { case 1: { return 0; } break; default: { } } } Returning from a switch case is not structured programming, but early exit is considered by most developers as an acce...
However, removing the break sentence will trigger the question: "Is this a fallthrough? The answer to the triggered question is: No, it does not fall through because it returns out of the function and thus out of the block that is inside the function. Should return inside switch be avoided? If you care about strict...
66,562,062
66,584,400
How to disable Marble Kde tiles movement
I load in marble map a .jpg image refered by .kml file: marbleWidget->model()->addGeoDataFile(kmlpath); The image is loaded in marble map: with the mouse I can move (drag and drop) and resize the jpg into the map. How can I anchor at specified coordinate or better, disable mouse interaction? Other data like [this] (ht...
//disable Annotation rendering in order to lock ground overlay movement for (auto rp : this->renderPlugins()) { if(rp->name() == "Annotation") rp->setVisible(false); qDebug() << rp->name(); } where "this" is the instance of your class: class Yourclass: public MarbleWidget
66,562,184
66,567,277
Ad-hoc constraint requires requires requires requires?
Suppose I'm writing a class template some of whose members are constrained on the presence and value of a type template parameter static constexpr data member: template<class T> struct A { constexpr bool operator()() requires T::value { return T::value; } constexpr bool operator()() { return false; } }; #includ...
This is a clang bug (submitted #49513). It looks like clang is substituting void into T::value and deciding that because that's an invalid expression, that the constraint is invalid. But the rule, in [temp.constr.atomic] is that: To determine if an atomic constraint is satisfied, the parameter mapping and template arg...
66,562,205
66,562,331
Check if std::list iterator is at end without access to the container
In a function, I work with a std::list<Type>::const_iterator. I don't have access to the container. Is there a way to check if the iterator point to an accessible element (i.e. the iterator is not at the end of the container) ? Note: I use C++11 (I don't want solution for C++ >= 14)
No. An iterator devoid of context is useless. Usually you will have a pair of iterators, denoting the range of interest.
66,562,249
66,562,845
Use of opencv waitkey() with C++
I'm trying to display the webcam feed with a timer but it doesn't render smoothly. Here is the code : int timer = 10; VideoCapture cap(0); Mat img; while (true) { cap.read(img); if (timer == 0) { cout << "TIME'S UP !!!" << endl; } else if (timer <= 2...
You might want to use std::chrono instead, to keep calling cv::imshow() + cv::waitKey for 10s and end the loop. #include <chrono> #include <iostream> #include <opencv2/opencv.hpp> namespace ch = std::chrono; using namespace std::literals; int main() { cv::VideoCapture cap(0); cv::Mat img; auto t0 = ch::...
66,562,464
66,566,996
TColor Initialise with int works with {} but not ()
I'm using Embarcader C++Builder 10.4.2 with the Clang32 compiler in the IDE to build a VCL Windows 32-bit app. I used to use () initializers for my own TColor constants when I used the old "Classic" compiler. But the Clang32 compiler doesn't accept this. The Clang32 does accept the same initialize value, but with the C...
Direct initialization doesn't allow an enum to be initialized from int with (..). And since C++17: list_initialization allows an enum to be initialized from int with {..}: Otherwise, if T is a enumeration type that is either scoped or unscoped with fixed underlying type, and if the braced-init-list has only one initia...
66,562,558
66,575,389
How can I send multicast UDP between 2 servers connected via cross-cable?
We have 2 servers with Solarflare cards directly connected via a cable on an interface (172.16.1.1 and 172.16.1.2). Both servers have other interfaces as well. I'd like test sending UDP multicast packets from one to the other on the 172.16.1.x interface. I've tried the following on the sender: const auto send_if( "1...
It turns out the option hops 0 was set earlier, which was the cultpit of all and I didn't see that. I only need to bind() to the interface before send, without any of the other sets and it works. // cultpit // socket.set_option( boost::asio::ip::multicast::hops(0) ); socket_.set_option( boost::asio::ip::udp::socket::r...
66,562,717
66,564,005
Pass a function pointer to a class object
I need to be able to specify a function for a class to be able to run (a callback function?) as part of a menu system, my knowledge of c++ is stretched here. Obviously this won't compile but hopefully it gives an idea of what I'm trying to do - void testFunc(byte option) { Serial.print("Hello the option is: "); Ser...
Please find the below code, see if this helps,you need a constructer to take the parameter, also you can't call the function from the parameter list while its expecting a function pointer #include <iostream> using namespace std; void testFunc(int option) { std::cout<<"in fn "<<option; } typedef void (*GeneralFunct...
66,562,992
66,567,627
Do the unseq execution policy require the iterators' value_type to be Cpp17CopyAssignable?
The following snipped does not compile with GCC 10 (Compiler Explorer link): #include <vector> #include <algorithm> #include <execution> struct T { int const ID; // Not Cpp17CopyAssignable }; int f(std::vector<T> const &v) { if (v.empty()) return -1; return std::min_element(std::execution::par_unseq, v.begin...
The C++ standard doesn't require values of the sequence passed to a parallel algorithm to be assignable (nor copy-constructible, nor default-constructible) unless required by the non-parallel counterpart. An implementation that doesn't accept such values is non-conforming. [algorithms.parallel.defns]/2 Parallel algori...
66,563,201
67,117,252
Why am I getting weird crashes with Qt5 depending on how I create the application instance?
Here is a reduced version of my code: #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> class MainView : public QMainWindow { public: static MainView *Initialise(int argc, char **argv); int Run() { return qApp->exec(); } private: MainView() { } virtual ~MainV...
There's a subtle difference between your invocation of the QApplication constructor in main() and the invocation in MainView::Initialise(). The documentation for the QApplication constructor says: QApplication::QApplication(int &argc, char **argv) < ... > Note: argc and argv might be changed as Qt removes command line...
66,563,393
66,563,432
Why does my if statement not run even if the condition is met?
I tried to make a simple program that asks the user a question and if the user answers correctly, it tells them that they are correct, but if they don't, it tells them to try again, and the code runs again. I did this using a while loop, if they answer correctly it breaks out of the while loop. But when i tested it eve...
Because the get function returns a character. There is no existing encoding where the character '8' is equal to the integer 8. Either you need to convert the character to its corresponding integer: (answer - '0') == 8 Or compare against the character: answer == '8' If you really want to read integers, then I suggest...
66,563,678
66,563,980
Fully specialized overloaded method is not called when used as template default parameter
I'd like to be able to specify default non-type template parameter by calling one of overloaded fuctions (that are template with full specialization). Following code represents the problem: I expecet FieldType2 getDefaultField<FieldType2>() to be printed, but Called getDefaultField() ! is printed. #include <iostream> ...
decltype(FieldDescr::fieldType) is const FieldType2 not FieldType2. So your specialisation doesn't match and primary template is used. You might use std::decay_t: getDefaultField<std::decay_t<decltype(FieldDescr::fieldType)>>() Demo But as suggested in comment, that usage of dummy member is strange, a regular using t...
66,563,909
66,564,066
Make set of pointers to use comparison criteria of underlying injects, C++
I want std::set if shared_ptr's to compare the pointee's, not pointers. I have this example: std::shared_ptr<std::string> s(new std::string("abc")); std::shared_ptr<std::string> p(new std::string("abc")); std::set<std::shared_ptr<std::string>> S; S.insert(s); S.insert(p); std::cout << S.size(); As you can see I am put...
The second template parameter of std::set is the type of the comparator to be used (default is std::less<Key>): #include <iostream> #include <memory> #include <set> #include <string> struct deref_less { bool operator()(const auto& a, const auto& b) const { return (*a) < (*b); } using is_transparent = void; }; int...
66,564,115
66,564,429
Why do I get a 32-bit overflow when compiling in 64-bit in C++?
So, I decided to test out a new C++ turtle-style graphics library. I decided to test it out by making the fibonacci spiral. however, upon running the program, it stops in the middle. I checked what was going on, and the fibonacci value had reversed to -2147483647, as if it was compiled in 32-bit. Can someone please hel...
MinGW uses the MSVC-friendly LLP64 data model. In LLP64, int and long int are both 32 bits, regardless of platform bitness (32/64 bit). To get a 64-bit data type, use long long or int64_t. e.g. std::vector<long long>. And also here: for(long long i = 0; ...
66,564,163
66,564,668
Function with two template overloads
I have a template function: template <typename T> inline void myFunction(T variable); Now I want an overload/specialization for the case T is actually an std vector. So I also have template <typename T> inline void myFunction(std::vector<T> variable) It doens't give me any compile time or runtime warnings or errors b...
Could somebody tell me whether this would be okay? Yes, it is perfectly fine, no UB. In general, overloading is not something that triggers UB on its own.
66,564,181
66,615,560
Can't build cross compiler on Alpine targeting GNU based linux distros (eg. Debian)?
I was trying to use crosstool-ng and get it work to build a cross compiler to target a gnu-based linux distros, since alpine comes with musl-libc I guess the cross tool couldn't directly use the type declarations used in gnu's. More precisely, at the time of installation of the linux headers when building the toolchain...
After a lot of hit and trials, I was able to successfully build the toolchain. The musl-libc is smart, it defines those types itself. So the rpc headers https://code.woboq.org/userspace/glibc/sunrpc/rpc/types.h.html#77 here were conflicting with the types __u_char that GNU defines but does not define u_char and more. W...
66,564,311
66,564,403
How to make one header to not include other headers?
So, if i have 3 headers like this headers.h #pragma once #include <string> #define FRAMEWORK_API extern "C" __declspec(dllimport) class Sprite; FRAMEWORK_API Sprite* createSprite(const char* path); Event.h #pragma once #include "headers.h" class Event { public: int spriteInit(std::string path = ".\\data\\Pla...
So, the question is, how to make ClassB.h, not to see #include "headers.h", from ClassA.h? By not including headers.h into ClassA.h. Or by not including ClassA.h into ClassB.h. In other words, you must give up on one of the premises, or your desire goal. They are in contradiction. If ClassA.h depends on declarations ...
66,564,707
66,596,392
How to store int into hash table using division method and quadratic probing to avoid collision in C++
So recently I had a quiz for my Data Structure subject, and there was a question involving hash tables. My lecturer did teach the theories behind it but never taught the way to code it which was extremely frustrating. I tried to google any info on how to do it, but to no avail. Now after the quiz, I just want to know h...
The question is not asking for storing int into hash table but the value of position in hash table where key (here planet names) is stored. Quadratic probing will be implemented somewhat like this: Create hash value from key using division method If hashtable[value] is unoccupied then no need of any probing. We occup...
66,565,004
66,565,356
QSettings printout default value for specific key
Is there a way to printout what is the default value for a specific key? int v = settings.value("key", defaultValue).toInt(); qDebug() << ...
QSettings object doesn't store default values associated with the keys. According to the QSettings::value() function description if setting doesn't exist, the function returns the given default value - the one you already know and put as a function parameter.
66,565,017
66,565,214
error C3207: invalid template argument for 'T', class template expected
I am implementing a system where i have templated setter and getter functions that either take a type and convert it to some internal representation, or return the internal representation in some user-requested type. For the below code sample, this work fine with the SetValue function, but no matching template function...
Given template declaration template <template <class...> class T, class... Args>, T should be a class template (a.k.a. a template-template argument). std::tuple is a class template, std::tuple<int, int> is a type. So this is how it could be instantiated: GetValue<std::tuple, int, int>();
66,565,312
66,672,125
Boost Testing compilation error when installed with apt-get
I just installed Boost usig sudo apt-get. After that, I wrote the following code for testing one of my the functions I had declared in "first_n_follow.h" #include<iostream> #include<string.h> #include<vector> #include<algorithm> #include<set> #include<map> #include "first_n_follow.h" #define BOOST_TEST_MODULE MyTest #...
Linkage of boost unit test framework library is missing g++ -o test.o first_n_follow_test.cpp -lboost_unit_test_framework Undefined reference errors usually means missing libraries or object files during linkage stage
66,565,341
66,565,440
Static Class Function Overrides Normal Sequence
I am making two classes: one named Godfather and another named Player. Player has a data member called madeMan and Player's default constructor, which I use in the code below, has madeMan made (see what I did there) false by default. My code: class Player; class Godfather { std::string family; public: ...
You forgot to initialize the boolean: inline Player::Player(const std::string& aName, const std::string& aFamilyRank, bool madeMan) : name(aName), familyRank(aFamilyRank), madeMan(madeMan) { std::cout << "Player " << name << " (" << familyRank << ") has been created." << '\n'; }
66,566,427
66,566,613
Don't print space in text file in c++ code
hello i have a c++ code for convert latin alphabet to arabic alphabet It works well for all characters except space character When space character needs to be printed in the file, no character is printed in the file how i can fix it ? #include <iostream> #include <string> #include <fstream> #include <cstdlib> us...
Instead of: cin >> ch; you should use: ch = getchar(); This way you'll be able to read spaces too. Don't forget to include: #include <cstdio>
66,566,452
66,566,473
What is the difference between `char **argv` and `char** argv`?
I have the two following C++ main function headers: int main(int argc, char **argv) int main(int argc, char** argv) I know that the asterisk * signifies a pointer, but I do not understand the difference between these two. The one I usually see is char **argv, which, If I'm not mistaken, declares argv to be a pointer ...
If so, then what is char** argv? If (also) declares argv to be a pointer to a pointer to a char. What is the difference between char **argv and char** argv? The difference between them is the placement of space. There is no other difference. These are also the same: char**argv char * * a...
66,566,889
66,566,989
How to initialise variables of returning tuple in c++?
I have a function xyz() which returns an tuple<std::string, double>. When I call this function individually, I can do the following: auto [tresh, loss] = xyz(i); This results in no error, but if I want to use the xyz() function in an if else block, then I can not use the tresh and loss variables anymore in the followi...
Before structured bindings were created, std::tie was the solution for unpacking tuples. std::string tresh; double loss; if (boolX) { std::tie(tresh, loss) = xyz(i); } else { std::tie(tresh, loss) = xyz(i); } std::cout << tresh << std::endl; It was considered clunky, because you have to declare variables befor...
66,567,162
66,567,315
Get the previous or next item in a map from a for loop
I'm making a calculator that can accept more than one operator at once (e.g. 5x5x5). I have a map that contains the positions of the operators, and what type they are (x/+-). I also have a for loop for (auto const& [key, val] : oper_map) which I got from this post. In order to get the left and right numbers, ...
No. key is not an iterator. for (auto const& [key, val] : oper_map) key is a const reference to the key in the map. If you want iterators, use iterators: for (auto it = oper_map.begin(); it != oper_map.end(); ++it) { auto next = std::next(it); auto prev = std::prev(it); } However, consider that std::map is no...
66,567,553
66,567,651
Aren't forwarding references deduced as r-value references?
I have a specific question regarding forwarding references. (I think) I understand r-value references and std::move, but I have trouble understanding forwarding references: #include <iostream> #include <utility> template <typename T> class TD; // from "Effective Modern C++" void consume(const int &i) { std::cout << "...
Types and value categories are two independent properties of expression. Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category. Each expression has some non-reference type, and each expression belongs to exactly...
66,567,828
66,568,419
template deduction failure in variadic macro
the decltype(__VA_ARGS__) in my macro compiles when only for a single argument and not when multiple arguments are passed. What I'm trying to achieve is to invoke a variadic function based on a runtime condition. The arguments to my printer could be expensive to compute and therefore I'd like to not evaluate those when...
You can do something like this to avoid having to find the template overload: template <class T> auto add_pointer(T&& t) { if constexpr (std::is_pointer_v<std::remove_reference_t<T>>) { return t; } else { return &t; } } #define PRINT_IF(printer, cond, ...) if(cond) add_pointer(printer)-...
66,567,964
66,568,143
Use public function as sorting criteria, C++;
Consider this example, I have public function less that I want to use as a comparator. P.S. I know if I change it to operator< it will work. class A { std::string str; int id; public: virtual bool less(A const& rhs) const{ return id < rhs.id; } }; int main() { std::set<A, A::less> s; } Thi...
The second parameter of std::set needs to be a type, not a value. It also has to be a type where comp(a, a) is a valid expression, where comp is a value of the compare type, and a is a value of the element type, so we can't use a pointer-to-member-function directly. std::set<A, decltype(std::mem_fn(&A::less))> s(std::m...
66,568,087
66,568,301
Problem with height and width for displaying Text with SDL 2
I have a problem for displaying text in SDL2. The text look weird with Message_rect.w = 100 and Message_rect.h = 100. I change manually change that, but it's not automatic. Do you know how can I automatically know the perfect height and width for text ? This is my actually code : TTF_Font* Sans = TTF_OpenFont("asset/ar...
I found the answer, I just have to give my Message_rect to the 'SDL_GetClipRect' function. So the code is now : TTF_Font* Sans = TTF_OpenFont("asset/arial.ttf", 24); SDL_Color White = {255, 255, 255, 0}; SDL_Surface* surfaceMessage = TTF_RenderText_Solid(Sans, "This is a good test", White); SDL_Texture* Message = SDL_C...
66,568,617
66,569,205
array bound is not an integer constant before ']' token
main: #include <iostream> #include "common.h" #include "squares.h" #include "board.h" using namespace std; int Board::board_length=8; int main() { Board *tabla=new Board(); tabla->printBoard(); } board.h : #ifndef BOARD_H #define BOARD_H #include "squares.h" class Board { static int board_length; Square...
As the error message indicates, board_length is not a constant value. To fix that, change the line static int board_length; in board.h to static const int board_length = 8; and remove the line int Board::board_length=8; from your main file. This should compile, but I cannot tell for sure, since you did not provide a...
66,568,875
66,569,150
How can I write a variadic template class?
To my understanding variadic functions are functions that take a variable number of arguments. Now I would like to apply this to a template function for which I want the constructor to be a variadic one. I don't know if this is possible and how I can accomplish this. My questions are therefore: Is it possible? And how ...
Since there is no way to create a variadic data member, you'll have to use a std::tuple. The rest is pretty straightforward: template<typename... Ts> class tXmlBase { public: tXmlBase(tXmlDoc* doc, Ts const&... id1); // if you have no other virtual member, it's better to remove this. virtual ~tXmlBase(); p...
66,569,196
66,569,269
std::map as class member
I have a class X with a member std::map<int,int> m_lookupTable. Which of the following should I use : Class X { ... private: std::map<int,int> m_lookupTable; ... } or allocate using new and delete in destructor of Class class X{ private: std::map<int,int>* m_lookupTable; X() { m_lookupTable = new st...
I would recommend to use a simple member. Dynamically allocating it, has no benefit, and adds unneccasry overhead for no reason. It also potentially introduces memory leaks if wrongly handled. You also have to take care when you use assignment or copying of your class, which you have to handle yourself then. Always pre...
66,569,496
66,577,192
Why has my function to hide the console scroll bar randomly stopped working?
I based my function on one which was provided as an answer on a different query here (C++ How to remove vertical scrollbar?), and when I initially used it, it worked fine, however now it has stopped working. I've copied the other person's solution into mine, and that doesn't work either. This is my copied code in the m...
When the SetConsoleScreenBufferSize function is executed, the console sometimes does not resize immediately (it takes a while to resize the console), so that ShowScrollBar has hidden the console, and the console has not been resized. When the console is resized, the scroll bar will reappear. No matter how you hide the ...
66,569,518
66,569,613
ulimit -c unlimited does not generate a core file in c++ segmentation fault
When I get a segmentation fault (core dump) in a c++ programm I don't get the core file after type the command: ulimit -c unlimited. It is the first time that I see that, and I do not why. Could you help me?
You want to take a look at the content of: /proc/sys/kernel/core_pattern … which enables the system to store your core file as a given name and/or behind a given path, and even pipe it to a command if needed. Check out this entry too : Core dumped, but core file is not in the current directory?
66,570,198
66,570,464
problem with operator+ priority in making a HyperComplex class
I'm making a HyperComplex class just for practice, I have problem with operator+ behaviour between 2 HyperComplex variables, I get the regular complex operator+, I tried also to do 2 opeartor+ (1 with Hc and Complex, second with complex and Hc, but that gave me ambigious eroor) here's my code: class Complex { public: ...
For starters the destructor of the class template Complex shall be virtual virtual ~Complex() = default; Make this constructor HyperComplex(const Complex<T>& p); explicit explicit HyperComplex(const Complex<T>& p); Otherwise an object of the type Complex can be implicitly converted to an object of the type HyperComp...
66,570,718
66,570,834
How to give a child a weak pointer to a parent? (C++)
I've read here that, in a situation where some parent object uniquely owns several children, and each child needs to be able to access its parent, a weak pointer should be used as the back-pointer instead of a shared pointer so as to avoid a dependency cycle. I have two questions: What are the advantages of giving a w...
weak_ptrs come from shared_ptrs. If your parent nodes "uniquely own" the children, then the children cannot have weak_ptrs to their parents, as this would require that a shared_ptr to them exist somewhere. Note that the example you cite does not state anything about "unique ownership" of the relationship between the it...
66,570,753
66,570,780
C++ Structure issues passing variable
This assignment requires me to create a program that takes in student info, firstname lastname and grade on test. I then have to assign the correct letter grade. Then I must output the student's name with the highest grade. Everything works except for the part with the highest grade. I know it is an issue with my "max"...
Your findmax() function is wrong. You are comparing student scores to each other, not to the max variable. Try this instead: int findmax(studentType student[]) { int max = 0; for (int i = 0; i < 3; i++) { if (student[i].testscore > max) max = student[i].testscore; } return max;...
66,570,928
66,575,628
GetDIBits returns array with all values 0
I need to find some image on screen. I decided to make a simple comparing loop. I found this answer that seems to be helpfull and wrote the next code: void Capt() { HDC hdcSource = GetDC(GetDesktopWindow()); // the source device context HDC hdc = CreateCompatibleDC(hdcSource); HBITMAP hSource = CreateCompatibleBi...
For screen data without transparency, you can simply set the fourth byte (Alpha) to 255, which means opaque. The color format of the bitmap data obtained by GetDIBits is written in BGR (lpPixels parameter). If we want to assign data to a byte array using RGB format, we need to perform some conversion. e.p. for (size_t ...
66,571,071
66,571,801
Aggregate initialization error in GCC 4.8.5
I am trying to port (something similar to) the following code to RHEL 7: enum class TestEnum { Foo, Bar, }; struct TestStruct { TestStruct() = delete; bool test_bool; TestEnum test_enum; bool operator==(const TestStruct &other) const { return test_bool == other.test_bool && test_enum == othe...
For compilers that don't support/allow this type of aggregate initialization† (due to the fact that your TestStruct class has a deleted default constructor), you can add a constructor that takes the values of the initializer list as arguments and use those to initialize your data members. Adding the following construct...
66,571,521
66,572,722
The time complexity of the for loop nested with if-statement and while loop
void makeGraph(){ for(auto itr = inputs.begin(); itr != inputs.end(); itr++){ string str = itr->second; if (strstr(str.c_str(), "->") != NULL){ char ch = '>'; size_t pos = str.find_last_of(ch); parent = str.substr(0, pos-2); string child = str.substr(p...
The difficulty in this case is that you have many variables that need to be accounted for. The important one being: The number of elements in input. For each string in input, the number of characters in the string. If you want a precise estimate, you would have to separately account for each of these variables. If we...
66,572,621
66,572,712
This program should show that the input is equal to the inverse number
#include <iostream> using namespace std; int main() { int n; int reversedNumber = 0; int remainder; cout << "Enter an integer: "; cin >> n; while (n != 0) { remainder = n % 10; reversedNumber = (reversedNumber * 10) + remainder; n /= 10; } if (reversedNumber =...
You divide n /= 10 in your loop until you have 0 left so if (reversedNumber == n) will never be true for anything but 0 as input. Save n before the loop and compare with the value you've saved after the loop. Example: int saved = n; while (n != 0) { remainder = n % 10; reversedNumber = (reversedNumber * 10) + ...
66,572,890
66,573,570
What is the difference between these codes involving a structure?
I have a structure node which has 2 pointers small and large and an int val. I intend to make a binary tree out of it later, but before that I just tried to insert only one element in three different ways and then print it. The 1st way works fine when I use a double ptr during insertion- struct node { struct node *...
Looks like you're still learning pointers? If so, consider code like this: int a = 10; int *b = &a; int **c = &b; You get: c -> b -> a=10 If you pass a to a function and change it, just the value is passed and the original is unchanged: void fa(int a) { a = 11; } ... fa(a); printf("%d\n", a); // -> 10 If you pass b...
66,572,910
66,573,036
unable to get return data from class in .hpp file
I have 2 files: main.cpp and parser.hpp I am returning vector<vector> from a member function in class in parser.hpp. However it seems I am not getting anything in my main.cpp from the return value because when I print its size I get 0. This is my main.cpp: #include <vector> #include <cstring> #include <fstream> #includ...
The first time you call obj.parse the stream object is read from until you get to the end of the file. You need to either reopen the file or reset file to point back to the beginning of the file after reading from it. You pass the same file variable to each of the three functions below but only the first one works. The...