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
64,412,405
64,412,786
Writing a copyable unique_ptr for copyable classes with PIMPL idiom
I want to write a class that uses the PIMPL idiom but makes the following possible: int main() { MyClass myclass {12}; std::string val = myclass.get_value(); std::cout << val << "\n"; MyClass copy = myclass; val = copy.get_value(); return 0; } That is, provide copy functionality while using P...
Although you can write a custom smart pointer here, I always like to reuse as much code as possible. It seems you want a dynamically created object with copy semantics rather than pointer semantics. For that reason I would hesitate to call your copyable_unique_ptr a pointer at all. I did write a class for this once and...
64,412,650
64,412,701
Can I extend conditional expression in C++
Can I make conditional expression with more than one else if: Casual condition: int number = 50; if (number > 23) cout << "The variable number is greater then 23 " << endl; else cout << "23 is greater then variable number" << endl; Conditional expression: int number = 50; cout << (number > 23 ? "The variable number...
Similar to an else if, you could just have the else case be another conditional: condition1 ? val1 : condition2 ? val2 : condition3 ? val3 : val4 which is kind of equivalent to if (condition1) val1 else if (condition2) val2 else if (condition3) val3 else val4
64,412,651
64,413,167
How to read structs properly
I hope someone can help me. I'm trying to read file that consists of some amount of structs from below: struct query { int key; char surname[16]; char name[16]; char patronymic[16]; char subject[16]; int grade; }s; I need to use mmap() to read some data from file, for example to print all struc...
mmap() can treat a file as being on memory. And you don't need to know the file size. See the sample code below: fd = open(filename, O_RDWR); fstat(fd, &buf); t = (struct query *)mmap(NULL, buf.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0); for(i = 0; i < buf.st_size/sizeof(struct query); i++){ ...
64,412,688
64,412,818
Ambiguous overload of pointer and integer?
The following overloaded function, void foo(const void*) { printf("first"); } void foo(unsigned int) { printf("second"); } generates an ambiguous overload in this case foo((int)0); but not in this one foo((int)1); Why? Is it because people still use NULL? And what's the best way to get around the problem, witho...
The literal 0 has special meaning in C and C++, as it's also a null pointer literal. This is how NULL works. If you're calling the function with a literal, instead of foo(0) you could do foo(0u), which works because 0u already has the type unsigned int, so there's no conversion needed to call the integer overload. If...
64,412,869
64,412,963
Method from a class declared as friend of another one raises error
I have the following two classes Player and FriendOfPlayer: Player.hpp #ifndef PLAYER #define PLAYER #include"FriendOfPlayer.hpp" #include<string> using namespace std; //class FriendOfPlayer; class Player{ public: // getters and setters ... static int getNbObj(){ return nbObj;...
I wonder why you don't get an header inclusion problem. You can't do a circular inclusion like you did. I would suggest to remove #include "player.hpp from your Friendofplayer.hpp. Instead just forward declare the Player class in Friendofplayer.hpp. Edit: The error message you got is confusing, but I just tried it by m...
64,412,956
64,442,995
Copy constructor doesnt happen when assign a QGraphicsDropShadowEffect object in qt
I declared two QGraphicsDropShadowEffect null pointers due to add shadow effect on some QPushButton(s) in qt : QGraphicsDropShadowEffect *effectButton1; QGraphicsDropShadowEffect *effectButton2; Then i allocate memory to effectButton1 and called the setXOffset, setYOffset, setBlurRadius methods to set shadow options t...
Consider the statement... effectButton2 = new QGraphicsDropShadowEffect(effectButton1); That will invoke this constructor... QGraphicsDropShadowEffect(QObject *parent) with effectButton1 as the parent parameter. It doesn't, as you seem to think, call a copy constructor. Indeed QGraphicsDropShadowEffect doesn't have...
64,413,109
64,415,306
Understanding compare_exchange_weak
The code below is the example for compare_exchange_weak from https://www.cplusplus.com/reference/atomic/atomic/compare_exchange_weak/ I don't understand what kinds of operations are acceptable inside the compare_exchange_weak while loop. In the example, they are setting the newNode->next value to the oldHead pointer as...
Basically you can do whatever you like inside the loop. compare_exchange (both, weak and strong) only ever succeed if and only if the value of the variable to be updated equals the first provided argument. In your example, list_head.compare_exchange_weak(oldHead,newNode) can only ever succeed iff list_head == oldHead. ...
64,413,350
64,413,655
Error C++ : ‘const_iterator’ does not name a type;
I have a class called Nuage (which is a collection of Points) where I will use the functions of the class Vector to manipulate the class. The nuage.cpp file is: #include <iostream> #include "nuage.hpp" template <typename T> Nuage<T>::Nuage(){} template <typename T> void Nuage<T>::ajouter(const T& p) { v.push_bac...
Use template <typename T> typename Nuage<T>::const_iterator Nuage<T>::begin() const{ return v.begin(); } When the compiler works with your .cpp file you reference a type const_iterator which does not exist. Only Nuage<T>::const_iterator exists. Easy to oversee. The typename keyword is needed beacuse Nuage<T>::cons...
64,413,800
64,414,134
How to read number from a console without any variables
I know that for reading from console we can use int number; cin >> number; //A line of code where we use int number But is it possible to read a number from console without any variables. Are there any methods that return a number from console?
But is it possible to read a number from console without any variables. Read a number without using any variable – sounds like a puzzle. Here we go: #include <iostream> int main() { return !std::cin.operator>>(*new int()); } This program returns 0 … on success (input was a number) 1 … on error (input was not a n...
64,414,112
64,420,250
remove multiple files with same extension in visual studio c++
I moved my code from Xcode on macOS environment to Visual Studio C++ on Windows. I used to remove several files with same extension without any issue on Xcode macOS by system("rm -f toto_folder/*.txt"); Now, on Visual Studio C++ I tried remove("toto_folder\\*.txt"); but in vain. Any help?
I suggest that you could delete files with the same extension by calling cmd. std::string command = "del /Q "; std::string path = "path\\directory\\*.txt"; system(command.append(path).c_str()); Quietly deletes all files in the supplied directory. If the /Q attribute is not supplied then it will confirm delete for ever...
64,414,470
64,414,551
Count read bytes in linux?
I read from file in main.cpp #include <iostream> #include <fstream> #include <unistd.h> #include <string> int main() { std::ifstream in ("file.txt"); std::string str; in >> str; in.close(); std::cout << str << std::endl; sleep(100); } State of /proc/[pid]/io before running: rchar: 11179 wchar: ...
From man proc, under /proc/[pid]/io: read_bytes: bytes read. Attempt to count the number of bytes which this process really did cause to be fetched from the storage layer. This is accurate for block-backed filesystems. As I interpret this, if your file was already cached in memory, then reading it will not cause...
64,414,869
64,415,035
A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++
As the title mentioned, I am trying to implement a summation function which can deal with various type arbitrary nested iterable things in C++. The various type here includes the types that can be summed together, and the arbitrary nested iterable things here include for anything that has begin() and end(), such as std...
You just need to be smarter in deriving the type of sumResult: template<class T> requires Iterable<T> static inline auto Sum(const T& numbers) { typedef typename std::iterator_traits<typename T::iterator>::value_type value_type; decltype(Sum(std::declval<value_type &&>())) sumResult{}; for (auto&...
64,414,933
64,864,162
How to use bitfields that make up a sorting key without falling into UB?
Let's say I want to have the following bitfield: struct SortingKey { uint8_t a: 2; uint8_t b: 4; uint8_t c: 2; } To use a simple integer comparison, I may need to wrap it into an union like this and use value for sorting: union UnionSortKey { SortingKey key; uint8_t value; } However, in C++, readi...
You can't use union for type punning, In C++20, you might use default operator <=> struct SortingKey { uint8_t a: 2; uint8_t b: 4; uint8_t c: 2; auto operator <=>(const SortingKey&) const = default; }; Before, you have to provide the conversion/comparison manually: bool compare(SortingKey lhs, Sorting...
64,415,058
64,415,302
Pointer to class with only static methods
Is there a way to obtain a pointer to a class consisting of only static methods? There are no member variables. I have a vector class using a typename alloc = allocator<T> as one of the template arguments. the allocator<T> template class is purely made of static methods. I intend to implement a get_allocator method whi...
You can't get a pointer to a type (e.g. &int), only to objects of a type. So either create an object and return a pointer to it, or use the static functions directly through the type: custom::vector<int>::alloc::allocate(5).
64,415,102
64,416,218
Error in MulVAL: multiple definition of `mylval'; collect2: error: ld returned 1 exit status
I'm getting this error while compiling MulVAL with "make" command on fedora OS. This is the error: multiple definition of `mylval'; lex.yy.o:/home/user/Desktop/mulval/src/attack_graph/graphit.l:5: first defined here collect2: error: ld returned 1 exit status make: *** [Makefile:4: attack_graph] Error 1 This is the Mak...
I gather that you didn't write the program you're trying to compile, and I see that you filed some sort of bug report. It's also evident that whoever did write the program had very little or no experience with flex or bison, and not much with C either. There are a great number of problems beyond the one which creates t...
64,415,112
64,415,183
std::transform not working for statically allocated string
Could someone help me understand why this doesn't work? #include <vector> #include <algorithm> using namespace std; struct person { int age; char name[30]; }; int main() { vector<person> persons(2); vector<char*> names(2); persons[0].age = 1; strcpy_s(persons[0].name, "mike"); perso...
In this lambda: [](person p) -> char* { return p.name; }); you are making a copy of each element in persons, and then returning a pointer to a member of the copy. This dangles as soon as you return from the lambda, invoking undefined behavior when you use the pointer later.. Instead, you could a return a pointer to a...
64,415,266
64,415,354
aliasing a type from a template struct
I shrunk down the problem to this: template <typename value_t, bool citrus = false> struct fruit_structs { struct fruit_base { value_t weight; }; struct banana_t : fruit_base {}; struct lemon_t : fruit_base {}; using fruit_t = typename std::conditional<citrus, lemon_t, banana_t>::type; }; template<typ...
You compiler can't be sure that what you're referencing is a type. Make it explicit by prepending the typename keyword: template<typename value_t> using banana_struct = typename fruit_structs<value_t, false>::fruit_t; template<typename value_t> using lemon_struct = typename fruit_structs<value_t, true>::fruit_t;
64,415,970
64,416,003
Call non-class function from a class method C++
I want to call the function print which is outside the class. At the forward declaration void print(Entity* e), I'm getting errors like this: 'Entity' undeclared identifier 'e' undeclared identifier 'print' illegal use of type 'void' term does not evaluate to a function taking 1 arguments (at the function call)-...
In your first line of code, the compiler doesn't know what a Entity is. So add the following line to the top of your code: class Entity;
64,416,436
64,417,324
C++ C-string has (apparently) no content to display
First of all, I am nothing but new to both programming and Stack Overflow. I am self-studying with Schaum's outline for Programming with C++ and I have some issues with problem 8.24 (solutions are given to almost every problem in the book, but I want to know why my code in particular isn't working as expected). You are...
Unfortunately, the code is wrong in many ways. The most obvious thing is the obscurity of the word reversal process (and the fact it is mixed with word iteration). According to the commenters, you are not using C++. In C++ it would be rather straightforward: #include <algorithm> #include <iostream> #include <string> v...
64,416,698
64,420,799
How to find a subsequence which it's sum satisfies requirements?
I'm looking for a way to search for the minimum subsequent size from a sequence that it's sum satisfies the minimum sum needed from the question. Examples (take note the index started from 0): arr[]={5, 1, 3, 5, 10, 7, 4, 9, 2, 8} sum = 15 so the answer should be 2, because the minimum size of the subsequence is f...
I have actually got an accepted answer on the judge, and it looked like this, #include <bits/stdc++.h> #define f first #define s second typedef long long int lli; using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int sequenceSize, sumAsked, sum=0; cin>>sequen...
64,416,720
64,695,793
Cannot set thread priority to real time despite using cap_sys_nice
I have an application that checks on POSIX environment whether thread priorities can be set to real time by calling struct sched_param param; param.sched_priority = 1; int canSetRealTimeThreadPriority = (pthread_setschedparam(pthread_self(), SCHED_FIFO, &param) == 0); On one system system A this works, but on another ...
It turned out the reason why realtime thread priorities could not be set system wide was another service running, which had following settings in service script defined: CPUShares=20 CPUQuota=500% After removing these settings from the script and restarting the service, thread priorities could be set system wide again...
64,416,851
64,416,913
Optional/ignored argument in C++ lambda, or lambda signature-based overload resolution
I have an iteration helper like this: template <typename T, typename Op> void for_each(T* a, size_t n, Op op) { for (size_t i = 0; i < n; i++) { a[i] = op(a[i], i); } } I'd like it to be able usable with or without the i argument to op: // float* a; for_each(a, n, [](const float& v) { return v + 1; });...
With SFINAE, you might do template <typename T, typename Op> auto for_each(T* a, size_t n, Op op) -> decltype(op(a[n], n), void()){ for (size_t i = 0; i < n; i++) { a[i] = op(a[i], i); } } template <typename T, typename Op> auto for_each(T* a, size_t n, Op op) -> decltype(op(a[n]), void()){ for (siz...
64,417,038
64,417,237
Non-virtual function in the base class with same name but different signature not found
struct A { void foo() { cout << "a:foo(void)" << endl; } virtual void foo(int) = 0; }; struct B : public A { virtual void foo(int) override { cout << "b:foo(int)" << endl; } }; int main() { B x; x.foo(); } So, here's the code sample. In the main, I would expect to have the non virtual foo() to b...
When you define a function in a derived class, the overload set with the same name as that function in the base class gets hidden in the derived class. So the compiler only finds the foo taking an int in the derived class, which causes an error. If you want to bring the overload set of foo from the base class into the ...
64,417,403
64,417,432
Rotate camera around z axis by 45 degrees works but not around x axis
I'm trying to setup an orthographic camera in C++ and I have some problems getting the rotation correctly. When I try to rotate the camera around the z axis by 45 degrees, everything works as expected (model is defined from -0.5f to 0.5f). However, when trying to rotate around x axis, the angle gets really amplified (...
When you rotate a round the x or y axis, then the objects is clipped by the near and far plane of the Orthographic projection. By default near is -1.0 and far is 1.0. Increase the distance to the near and far plane (see glm::ortho). For instance: glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f); glm::mat4 ...
64,417,530
64,418,562
Overloading variadic templated methods
My compiler is having a hard time to understand this code, I am struggling for hours to find what's wrong. #include <utility> #include <string> template<typename Derived> struct AssetLoader { template<typename... Args> void doLoad(Args&& ... args) const { static_cast<const Derived *>(this)->load(std::f...
After digging, I found finally a solution. Basically I had to check that the first type of Args... is not a loader itself, so the compiler will be forced to choose the 2nd overload instead. Here is the code #include <utility> #include <string> template<typename T1, typename...> struct first { typedef T1 type; }; ...
64,418,273
64,418,417
C++ different constructor calls
I wrote a little class to learn the different constructor calls #include <iostream> #include <cstdlib> #include <cstring> class String { private: char *str; public: explicit String(const char *p); String(String&& StringObject); String(String& stringObject); ~String(); ...
I'd suppose that you start line counting at 1 ;-) The case with a complex expression We would expect the following statement to construct in principe a temporary String for String{" "}, and then a temporary string for each of the two +. Since the parameter obj is to be constructed from a temporary object, the move con...
64,419,586
64,419,790
In C++-17, how to detect the existence of a templated static member function at compile time
I have a templated function (Process) where I would like to perform a compile time check to see if the supplied typename (Z) has a templated static member function taking arguments of the two supplied types (X) and (Y). Is it possible to do this with an if constexpr test and if so, what would it be? #include <iostream>...
I can't think of a way to do it with if constexpr alone, without a pair of overloads to test with SFINAE. See if something like this works for you: template <typename Z, typename X, typename Y> auto test(X x, Y y) -> std::enable_if_t<sizeof(decltype(Z::compare(x, y))*) != 0, std::true_type>; template <typename Z> ...
64,419,931
64,420,098
In C++-17, is there a template deduction guide possible for this constructor?
Is there a template deduction guide that would enable the variable c to be deduced as type bar<baz> just that it is just like variable b? #include <vector> #include <functional> template<typename T> struct foo { using container = std::vector<T>; using creator = std::function<container()>; }; template<typename T> ...
The difficulty here is due to the relationship between the parameter and the type being deduced being extremely tenuous. It's also unnecessary, due to unnecessary constraints on the function parameter. I don't see a reason why you specifically need to take a std::function here. You're already in a template; you could t...
64,420,224
64,420,431
Printing rdbuf() to console works, but getline fails
I'm having a strange issue where printing to the console using rdbuf() from a file using ifstream works, but the string parameter inside of getline never returns a value, and thus fails to print to the console in a for loop. I was trying to add the lines in the file to a vector for processing and I know there's other m...
File.rdbuf() doesn't return a copy of the buffer for the stream, it returns a pointer to the actual in-use buffer for the stream. That means when you do std::cout << stream << std::endl; you exhaust the actual file stream, and put it at the end of file. Which means the std::getline call will fail. You need to reset t...
64,420,478
64,420,591
How to output positive minimum number in do while loop?
The program outputs a minimum negative number when I need to output a positive minimum number. Negative number is ending data entry. #include <iostream> using namespace std; int main() { int totalNumber, max, min, score = 0, sum = 0; float avrg; do { sum = sum + score; cout << "Enter score " << ++totalNumber...
This should work. All you needed to do was to make sure that the number was not less than 0 and that if it is the first number inputted, that should become min immediately. #include <iostream> using namespace std; int main() { int totalNumber = 0; int max = 0; int min = 0; int score = 0; int sum = ...
64,420,684
64,421,083
Trying to have c++ program quit by inputting a letter
I made a program that generates a multiplication table for the number that is inputted by the user: #include <iostream> #include <iomanip> #include <string> #include <cstdlib> #include <ctime> using namespace std; int main() { char userSelection; int numForTable; int col; int row; do { ...
I totally used your program to write the table, and only make the mechanism to switch between writing the table or exiting the program. Since your program only writes the table for integer between 1-10, which is 2-9, I used the ASCII code of the char for it. Here's the code. #include <iostream> #include <iomanip> #incl...
64,420,868
64,420,922
C++ pointer with c-style string
Why i don't get the address when cout the pointer ? See the code below: code1: string s1 {"NAME"}; string *p1 {&s1}; cout<<p1; gives 0x71fcc0 which makes sense. But see what happens when i use cstyle string: char cstring1 [] {"NAME"}; char *cp2 = &cstring1[0]; cout<<cp2<<endl; Prints NAME on the screen So why it do...
So why it doesn't print an address ? Because it is a pointer to char. And pointers to chars are treated differently from other pointers when inserted into a character stream. When pointer to char is inserted into a character stream, the pointed string is produced, rather than the address. If the pointed string is not...
64,422,215
64,460,148
Linaro toolchain fails to create ARMv5 binary
I am trying to upgrade my compiler to support C++11, the kernel of my target machine is 2.6.33.20. For this purpose I am attempting to use the prebuilt binaries at https://releases.linaro.org/components/toolchain/binaries/, namely the version 5.5.0. The trivial testing program //#include <functional> #include <stdio.h>...
Kudos for this answer to go old_timer, who gave me an invaluable hint on where to go. All I ended up having to do was mosey over to https://crosstool-ng.github.io, download the package, rummage through the dependencies and then let the thing do it's magic. I chose the minimal configuration, compiler version 5.5.0 and, ...
64,423,630
64,424,404
Unable to set a background image on UWP C++ project with XAML
I've completed a couple of projects using Visual Studio 2019 and C# with no problem. I am currently learning C++ and as part of the process, I am recreating a C# UWP application with C++. I haven't gotten to the C++ yet. I'm just about done with the XAML and this also uses Visual State Manager but the problem is that I...
OK! I have finally figured it out. I needed to copy the files into the projects' Assets folder and then copy the files from that specific folder to the Filters. It would not work any other way. Sorted!
64,423,700
64,562,445
Qt5 embedded window stays independent and isn't being displayed in my own
I've been trying to learn how to embed a window in Qt5 for my game engine. I'm getting the window id from xwininfo. It's valid, fromWinId doesn't return nullptr. The app runs with no errors, but the window doesn't show anything and the embedded one stays independent of my window. There is some of the background leaking...
Turns out the fix was to pass the window id as a decimal, not hex value. It is weird though, because there weren't any errors.
64,423,716
64,424,150
How to get the status of an URL?
I am using Qt and what I should do is given a QString containing my URL, before opening the page, I want to know if this is reachable. I read the documentation of QNetworkReply and I saw that there are different codes for the different types of error (eg: the remote content was not found at the server -> code 203). The...
How to know if this is reachable, before opening the page? It is not something you could know in advance, but a trial and error: Make the request Check for errors Get the error code How can I do this? Let's take the example from the documentation: QNetworkAccessManager *manager = new QNetworkAccessManager(this); QNet...
64,424,595
64,424,662
Does QT use dynamic_cast for QML properties?
I came across curious behavior in QT. Lets say you have a base controller: class BaseController : public QObject { Q_OBJECT public: BaseController() = default protected: inline BaseNode * getRoot() const noexcept { return root; } protected: BaseNode * root; }; And ExtraController: class ExtraControl...
Qt uses its own meta object system. That is why you need MOC and the Q_OBJECT macro. So Qt "knows" which properties each object has during runtime and uses that knowledge for QML as well. On the C++ side you can see this through QObject::property(): Returns the value of the object's name property. If no such property ...
64,424,692
69,544,175
How does the address of R_X86_64_PLT32 computed?
I am trying to understand how the linking works. I have a simple C++ code #include "a.h" int Other() { return 1; } int SomeFunction() { Other(); Other(); Other(); return 0; } which generates the following Relocation table. $ readelf -r a.o Relocation section '.rela.text' at offset 0x240 contains 3 entri...
I'm not an expert and a little bit late but as far as I understand it newer GCC versions use R_X86_64_PLT32 instead of R_X86_64_PC32 to mark 32-bit PC-relative branches. "On x86-64, for 32-bit PC-relative branches, we can generate PLT32 relocation, instead of PC32 relocation, which can also be used as a marker for 32-b...
64,424,885
64,433,144
Is cv::Mat::clone() more efficient than assigning a matrix created by cv::Mat::zeros()?
I have a function that is executed many times in the application lifespan. In order to optimize the code, which solution is better? Is this: void foo() { static const cv::Mat zeroMat16 = cv::Mat::zeros(rows, cols, CV_16UC1); cv::Mat newMat = zeroMat16.clone(); ... } faster than this: void foo() { cv::M...
clone uses copyTo without mask in its implementation. inline Mat Mat::clone() const { Mat m; copyTo(m); return m; } copyTo implementation -> memcpy zeros implementation -> makeExpr -> MatExpr which is then converted from MatExpr to Mat MatExpr::operator Mat() -> assign which calls m = Scalar(); Mat::operator= -...
64,425,283
64,429,015
Auctions in Boost ASIO
I'm implementing an auctioning system in C++ with Boost.Asio. There is a single centralized auctioneer (the server) and some connecting bidders (the clients). I am implementing this in an asynchronous fashion, and I have implemented the basic communication between the bidder and auctioneer (register, ping, get client l...
In asynchronous protocol design, it helps to draw Message Sequence Diagrams. Do include your timers. The code now becomes trivial. You start your timer when the message arrives that should start your timer. Yes, this is shifting the problem a bit forwards. The real point here is that it's not a Boost Asio coding proble...
64,425,612
64,426,157
How can I change the byte orders of a struct?
How can I change the order of a packed structure in C or C++? struct myStruct { uint32_t A; uint16_t B1; uint16_t B2; } __attribute__((packed)); The address 0x0 of the structure (or the LSB) is A. My app communicates with hardware and the structure in hardware is defined like this: struct packed { logic [31:0]...
How can I change the byte orders of a struct? You cannot change the order of bytes within members. And you cannot change the memory order of the members in relation to other members to be different from the order of their declaration. But, you can change the declaration order of members which is what determines their...
64,425,666
64,435,806
Replace back slashes with forward slashes in string (std::replace works on windows but not on linux)
I was working on a small application in Windows, one of the steps is to send it a path through the command line (CMD.exe), something like this: c:\> my_environment_var catch folder/sub_folder/file.txt The program receives the path and executes a process. For this, I was asked to control two cases: Transform the string...
From your description, my guess would be that the issue is not with your code: it's with the way you are providing input to your program. Unlike on Windows, Linux doesn't use \ as a path separator, and instead it's usually given special meaning as an "escape character"—much like in C++. As such, your shell is likely pa...
64,425,716
64,425,816
C++: Program crashes when trying to print value of pointer
I'm writing a program that is supposed to allow a user to enter the size of an array, enter the values for each index of the array, and print out the Min and Max Values of the array using a pointer. The program successfully determines the Max and Min Values of the array and prints out the max value with the use of the ...
For starters variable length arrays like this int ar[arsize]; is not a standard C++ feature. Instead use the standard container std::vector<int>. This call fflush(stdin); has undefined behavior. Remove it. In the both for loops like this armax = ar[0]; for (i = 0; i < arsize; i++) { if (armax < ar[i]) { ...
64,425,953
64,426,218
Why do I need to use dynamic memory allocation when I can achieve the same from static?
Let me take an example to explain my problem, Case I #include<iostream> using namespace std; int main(){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; } Case II #include<iostream> using namespace std; int main(){ int n; cin>>n; int *a = new int[n]; for(int i=0;i<n;i++) ...
The case 1 does not do a "static" memory allocation, rather it's memory allocation "on stack". It's a variable length array. There are multiple reasons: Variable length arrays is a compiler extension. They are not part of C++. There is no error handling with variable length arrays. It's impossible to forward to the u...
64,426,295
64,426,365
c++ overload generic method, by-reference and by-value
I have two generic methods (edit: actually operators but the issue is the same for methods) that are identical, except from that one uses its formal parameter by reference and the other method uses its formal parameter by value. struct shout_t { template<typename T> shout_t& operator<<(T &x) { cout << x; return...
There are two scenarios here, either you might want to change the object passed as a parameter, or you don't. In the latter case, pass as const-qualified reference: struct shout_t { template<typename T> shout_t& operator<<(const T &item) { cout << item; return *this; } }; and otherwise, use a forwarding refere...
64,427,009
64,427,304
How to deal with this eigen error of static assertion failed?
I'm using vscode to write my cpp code. It use the Eigen package. And I met a strange error: error: static assertion failed: YOU_CALLED_A_FIXED_SIZE_METHOD_ON_A_DYNAMIC_SIZE_MATRIX_OR_VECTOR 214 | EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I don't know what does it mean.So I ask so...
Eigen::MatrixXd::Zero(rows, cols) can be used to create a matrix initialized to 0. E.g. U=Eigen::MatrixXd::Zero(m+2,n+2); If you already have defined a matrix and want to set it to zero, use the setZero function: U.setZero();.
64,427,162
64,427,357
How to compare string_view using if-constexpt in a constexpr context
Is it possible to compare std::string_view using "if constexpr" in a constexpr context? And why is_hello_2 and is_hello_4 fail to compile showing error: "‘s’ is not a constant expression" static constexpr bool is_hello_1(auto s) { return s == "hello"; } static constexpr bool is_hello_2(auto s) { if constexpr (s ...
Is there a way to fix "is_hello_2" and "is_hello_4"? Remove the constexpr from ifs in is_hello_2 or is_hello_4. How to compare string_view using if-constexpt in a constexpr context Normally, like anywhere else. static constexpr bool is_hello_5() { constexpr const std::string_view s1 ("hello"); if constexpr ...
64,427,215
64,430,080
How to paint in Qt using hardware acceleration?
I need to do some quite intensive drawing processes in my appliation - I'm recording a camera and a desktop. I'm using ffmpeg to capture and encode/decode my videos. Those processes are quite fast and they working in a separate thread, but when it comes to render - perfomance drops drastically. I'm using QLabel to dis...
Software rendering is not the only possible performance killer. I also used to use QWidget for similar kinds of jobs, and it seems to be OK. I assume the result of FFmpeg processing is an uncompressed byte array with YUV or RGB color scheme. You already have some memory allocated for your FFmpeg image frame. I believe...
64,427,552
64,428,039
name followed by :: must be a class or namespace but header defined
I am trying to implement some methods that have been declared in my header file in my source file. I keep getting this error name followed by :: must be a class or namespace and from searching it seems like a project setup error, however both my files are in the correct directory. main #include "sarray.h" #include <io...
Your member function implementations need the template parameter too: template<class genericData> sarray<genericData>::sarray(...) ... Put the implementation of the class template member functions in the header file as well. If you don't nothing will be generated in the object file when you compile the .cpp file. Th...
64,428,220
64,442,146
sharing internet connection from two different connections with iptables
I have wrote a c++ code to share internet from wlan0 or eth1 with eth0 and code works properly. code to share eth1 with eth0: cmd = "systemctl stop networking"; system(cmd.c_str()); cmd = "iptables -A FORWARD -o eth1 -i eth0 -s 192.168.2.0/24 -m conntrack --ctstate NEW -j ACCEPT"; system(cmd.c_str()); cmd = "ptables -A...
Well I have figured out the solution, first of all I have a SIMCARD and a WIFI connection, the SIMCARD connection was ppp0 instead of eth1, my first mistake... the second problem was when I had WIFI connected the ppp0 was not able to ping any destination and could not connect to internet, so I needed to turn off WIFI w...
64,428,725
64,432,185
How to write code to calculate partial derivative of several variable function in C++?
I already wrote the code to calculate the derivative of a single variable function at a point by making a class called "Der". In class Der, I defined two private variables double f and double df and a print() function to print the values of f and df. Inside the class, I overloaded the operators +, -, *, /, ^ to calcul...
You seem to be very close to the solution, but struggling with the step to functions defined over multiple dimensions. Instead of having one member variable df, you need several of them, one for each partial derivative. You could hard-code them: double dfx, dfy, dfz; or use a container: double df[3]; I'll use hard-co...
64,428,809
64,438,103
compiling win32 official example with VS 2019 build tools (cl command) encounters _wWinMain@16 error, how do I fix it?
I'm trying to render a window by using the exact code in the Microsoft doc I'm not sure whether the error "_wWinMain@16" refers to the 16th line of code. doing.obj : error LNK2019: unresolved external symbol __imp__GetMessageW@16 refe renced in function _wWinMain@16 doing.obj : error LNK2019: unresolved external symbol...
user32.lib is required to link as @dxiv pointed out. You can try the following command line: cl test.cpp /link /subsystem:windows user32.lib
64,428,819
64,479,054
QtVirtualKeyboard focus problem when editing a cell in a QTableView
I have been battling for the last couple of days to include the QtVirtualKeyboard into my QWidget based app that is running on a Raspberry Pi with a 7" touch screen display. Here's what I've done so far : Installed the plugin : sudo apt-get install -y qtvirtualkeyboard-plugin sudo apt-get install -y qml-module-qtquick-...
Ok, so after another few days of all out war with the virtual keyboard, I have finally achieved the desired result. After finding this gem of a guide, it turns out that because the widget containing my QTableView and QtVirtualKeyboard was a QDialog that was being displayed using the exec() method, it meant that the win...
64,428,876
64,429,134
Is it necessary to have default ctor for the most-base class in virtual inheritance?
Preliminaries I am writing a high level library for VMEbus modules. I have two levels of abstraction to represent modules: |---------------------| | VBoard | |---------------------| | + VBoard( address ) | | + Init() = 0 | | + ... | |---------------------| /\ /\ ...
The constructor of V1785N should forward the address to it's base class VBoardAcquisitor, which itself will forward the address to VBoard Here is the constructor of V1785N V1785N( int address ) : VBoardAcquisitor(address) {} and the constructor of VBoardAcquisitor VBoardAcquisitor(int address) : VBoard( addres...
64,429,212
64,430,203
Display rotation of 3D triangle
I am trying to show a triangle which is rotated with respect to y axis. But I can not show it properly. How do I solve it? What is wrong with my code init: void init() { glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glClearColor(0.7f, 0.9f, 1.0f, 1.0f); glEnable(GL_CULL_FACE); glCullFace(GL_B...
The model rotates around (0, 0, 0). Don't translate the vertices along the negativ z axis, but arrange the vertices around (0, 0, 0) and translate the model by glTranslate after rotating the model. For instance: void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); ...
64,430,512
64,435,095
c++ variadic templates, arguments descendants of same base class
Consider the following base interface and two concrete implementations of it. I would like to test these with 1 template method, with arguments that are the types to be tested. All the sub-types (QueueA, QueueB) inherit from IQueue. How could I achieve an implementation for the template method tester_queues? Similar fu...
If you really want to specify only the Queue types as template arguments, then you can use something like this to let tester_queues() construct instances of those type internally for testing: #include <iostream> template<class T> class IQueue { protected: T Data[10]; public: virtual const T pop() = 0;...
64,430,789
64,439,430
How can I tell Visual studio where my additional .dll files are?
I have recently switched my IDE to Visual Studio 2019 for C++ projects. I easily followed a tutorial into setting up a new library like SFML into visual studio, and tell it where the additional include and library directories are. But there is something else that is required for it to work, which are the .dll files. Ev...
You could create a path environment for your specified directory, which is like drescherjm’s suggestion. The steps: Right-click “This PC” -> “Properties”-> “Advance System settings” Click “Environment Variables” In the System Variables group, edit “Path” Add your directory, for example: ”D:\ SFML-2.5.1\bin” Restart yo...
64,431,350
64,431,468
What is the difference between `auto` and `std::any`?
I recently came across the std::any class, introduced in C++17, based on boost::any. This class can "hold an instance of any type" and auto automatically deduces the data type of a variable. So what is the main difference? What are the pros and cons?
std::any and auto are completely different constructs. std::any is a container type that can hold an object of any type: std::any a = 42; // a holds an int, but type is std::any a = std::string{"hi"}; // ok, a holds a string now The type of the object held by std::any can change during the execution of the pr...
64,431,563
64,431,650
Weird behaviour when holding std::ostream rvalue member
#include <iostream> #include <fstream> class A { private: std::ostream&& out; public: A(std::ostream&& o) : out(std::move(o)) { out.write("test", 4); } void writeTest2() { out.write("test2", 5); out.flush(); // still does nothing. } }; int main() { A a{std::ofstre...
The temporary std::ofstream{"testic"} that you created only exists for the duration of the constructor call. After that it is destroyed and the file is closed, which means you are left with a reference that refers to garbage. Using that reference results in undefined behavior. To fix it you can remove the reference all...
64,431,606
64,431,812
ReadProcessMemory only works with breakpoint
I start off creating a process, logging if it fails, and then a while loop to wait for the window to be found. PROCESS_INFORMATION p; STARTUPINFO s; ZeroMemory(&s, sizeof(s)); s.cb = sizeof(s); ZeroMemory(&p, sizeof(p)); if (!CreateProcessA("D:\\SteamLibrary\\steamapps\\common\\Fallout 4\\Wolf4SDL.exe", "", NULL, NULL,...
It's pretty straightforward. The variable you are reading is still 0 when you read it. When you use a breakpoint, the time delay where you look at the code and press continue is when the other process sets the variable.
64,431,661
64,476,960
simplest syntax for passing in an array of subclasses of a polymorphic base class into a constructor
Here's working code, that I'd like to simplify the calling of. Let's start with the call: Config c2( { new ConfigPairInt( "one", 1 ), new ConfigPairDouble( "two", 2.0 ), new ConfigPairString( "three", "3" ) } ); The first thing I'd like to get rid of is the new's. (If I do new...
AS Remy and Panta point out in other answers: You simply can't get rid of the derived type names if you want to use polymorphism, since the compiler needs to know which types to create. Since this is the most typing for the caller, to eliminate it is a priority. Thus polymorphism is ruled out. Instead, what was a vir...
64,431,925
64,432,261
Avoiding NANs for expressions that are partly imaginary in c++
I have an expression whose outcome is a real number, but is composed of imaginary terms (that cancel one another). A significantly more simple example than the one I am considering would be something like, z = a + 1/[sqrt(a-b) - a] - f[sqrt(a-b)] = a where a and b are real numbers and f is some function that statisfi...
tl;dr for the comment thread: If you know you're doing something that will involve imaginary numbers, just use std::complex. You can't avoid getting NaN if you insist on asking for a real result to something (sqrt, say) that you know will have an imaginary component. There is no real answer it can give you. At the end ...
64,431,950
64,433,060
Code unexpectadly giving an infinite loop
Recently started learning C++ and i wrote a simple program that defines is the given number prime or not, and when the input is zero, it finishes. But i accidentally noticed that it creates an infinite loop when the input is somewhere between 2100000000 and 2200000000. I don't know why this happens, can you please expl...
The value overflows its type (int) which maximum value is 2147483647 and it results in Undefined Behaviour. If you need to accept large numbers as input you may have to use a long long. Additionally, why check if number equals 0 twice? #include <iostream> #include <math.h> int main() { while(true) { lo...
64,432,007
64,460,496
How to extend constant array in C++ using a base array
In C++, is it possible to declare a constant array as an extension of a smaller constant array? For example, if I have the following array: const uint32 oid_base[] = {1,3,6,1,4,1,72000}; const uint32 oid_complete[] = {1,3,6,1,4,1,72000,1,1}; Is there a way to declare oid_complete using oid_base in the declaration of o...
Isn't this what gsl::span is for? const uint32_t oid_complete_data[] = {1,3,6,1,4,1,72000,1,1}; const gsl::span<const uint32_t> oid_complete{ oid_complete_data, sizeof(oid_complete_data)}; const gsl::span<const uint32_t> oid_base{ oid_complete_data, sizeof(oid_complete_data)-2}; (cf. https://godbolt.org/z/b...
64,432,081
64,432,283
What happens to a variable of a member function having same name as that of a private data member of the same class?
When i compile the code below i don't get any error and on debugging it initializes the class data member a of class abc to zero. Can someone just tell me how is the compiler differentiating between the two. I dont see it happening in runtime. //A function friendly to two classes (finding maximum of objects of 2 classe...
That's called "variable shadowing". When you do that, the local variable a "shadows" the class variable. The compiler will use the local variable, so in the inivalue function of the class abc you're just setting the parameter value to itself. The a member of the class is unitialized when it is used in the max and the c...
64,432,810
64,432,920
Can a function return a type?
I was wondering if there was any way to do something like this in C++: $(some typename) func() { if (/*condition*/) return int; else return bool; } Edit: I think I wasn't clear enough. I was wondering if you could say something like this: func() var = /*something*/. Basically, the function is returning somethi...
A function cannot choose which type to return at runtime; it must have a definite return type at compile time. What you can use instead is a template with a member type. You will need to use template metaprogramming for this. As an example, here is an adapter template that makes a type T into its const pointer form: te...
64,433,293
64,433,443
Is a contiguous_range always a sized_range?
I have the following question concerning the ranges library in C++20: Let std::ranges::contiguous_range<T> for an arbitrary type T. Can I assume std::ranges::sized_range<T>?
No, not every contiguous_range is a sized_range. The simplest example is a null-terminated string. It's contiguous, but we don't know its size in O(1) time. And we can easily represent such a thing using sentinels: struct ntbs_sentinel { bool operator==(char const* p) const { return *p == '\0'; } }; st...
64,433,650
64,433,826
Concatenate multiple std::vectors taking duplicates into account in c++17
Even though it is straight-forward to concatenate two std::vectors in C++, especially with ranges, I have a slightly different problem. Say I have the following vectors: {1,2,6}, {6, 8, 9}, {9, 8, 10}, and so on. If the tail of one vector is the same as the head of the next vector that is being concatenated to, I want ...
You can do something like the following. #include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> v1 = {1,2,6}, v2 = {6,8,9}, v3 = {9,8,10}, v4 = {0, 1}; for ( auto p : { &v2, &v3, &v4 } ) { auto it = std::begin( *p ); if ( v1.back() == p->front() ) ...
64,433,829
64,434,460
How can I make my loop ask me for my next input in C++
I am trying to make a Yahtzee game told hold my dice. But I keep getting an infinite loop. cout << "Choose what Dice you want to hold. Use numbers from 0-4. If you are done selecting Dice type 5. "; cin >> Hold; for(int i = 0; i < 5; i++) { switch (Hold) { case 0: cout << "You held t...
From the code you've posted I would say you to do this: cout << "Choose what Dice you want to hold. Use numbers from 0-4. If you are done selecting Dice type 5. "; do { cin >> Hold; switch (Hold) { case 0: cout << "You held the " << NumArray[0] << " Die. "; ...
64,433,920
64,437,331
Avoid UserDataFolder for MS edge (webview2)
In my application, I am creating Edge environment using CreateCoreWebView2EnvironmentWithDetails. Right now it is creating a folder next to my exe as "myexe .WebView2", which I don't want. So I am passing "C:\Users\username>\AppData\Local\MicrosoftEdge as an UserDataFolder. But still it is creating an empty folder "Mye...
What you describe is a bug. If you still see this behavior with the latest SDK, please open an issue against our WebView2 feedback GitHub repo and we can look into it. Thanks!
64,434,198
64,434,236
How do I use constexpr logic?
I would like to implement some constexpr logic in some piece of code. I am able to compile and execute this code without problem. #include <iostream> int main(){ std::cout << "Starting c++ main" << std::endl; constexpr int val_1 = 100; int val_2; if constexpr (val_1 == 100){ val_2 = 10; }...
You can put the initializer in a ternary expression: constexpr int val_2 = val_1 == 100 ? 10 : val_1 == 200 ? 20 : 0; If your initialization logic is more complex you can write a constexpr function like this: constexpr auto f(int val_1) { int val_2{}; if (val_1 == 100){ val_2 = 10; } else if (val_1 == ...
64,434,970
64,435,195
How can I pass a type or variable to this is_same function?
I want to be able to pass a type or variable to a function that will return true or false if it's the same type: template <typename T> struct OneType { template <typename U> //??? static constexpr bool is_same_type(U u = std::declval<U>()) { return std::is_same_v<T, U>; } }; struct AnotherType { AnotherTyp...
The default value is unnecessary, just define: template <typename U> static constexpr bool is_same_type() { return std::is_same_v<T, U>; } Then use it with parenthesis: a.is_same_type<AnotherType>(); If the type of an object is needed then decltype can be used: AnotherType obj; a.is_same_type<decltype(obj)>();
64,435,208
64,435,333
Exiting gracefully when running an invalid command c++
I'm using boost for running commandline commands from my application. I am using the following piece of code that I've encapsulated into a helper function: tuple<string, int> Utility::RunCommand(const string& arguments) const { string response; int exitCode; try { ipstream iStream; auto ...
That's what your catch clause is for, to handle exceptions. It doesn't have to rethrow them: tuple<string, int> Utility::RunCommand(const string& arguments) const { string response; int exitCode; try { ipstream iStream; auto childProcess = child(arguments, std_out > iStream); str...
64,435,399
64,435,626
How to push_back() C array into std::vector
This doesn't compile: vector<int[2]> v; int p[2] = {1, 2}; v.push_back(p); //< compile error here https://godbolt.org/z/Kabq8Y What's the alternative? I don't want to use std::array. The std::vector declaration on itself compiles. It's the push_back that doesn't compile.
You could use a structure containing an array, or a structure containing two integers, if you really don't want to use std::array: struct coords { int x, y; }; vector<coords> v; coords c = {1, 2}; v.push_back(c); alternatively, as mentioned, you could use a structure containing an array: struct coords { int x...
64,435,697
64,435,724
Error passing by value in operator overloading
I'm trying to understand why passing by reference works and passing by value does not in a simple class definition #include <iostream> class Rettangolo { int a, b; public: Rettangolo (Rettangolo& r) { a = r.a; } Rettangolo (int _a, int _b) : a(_a), b(_b) {}; Rettangolo operator+= (Rettangolo ...
This is because your copy constructor is not fully functional. It only copies a, and not b. Therefore when rectb is copied when you call operator+=, passing rectb by value, the a is copied and added to recta but the b is not copied and therefore not added to recta. To fix this, add the b copying in the copy constructor...
64,435,998
64,436,154
Know which version of c++ is running on Visual Studio
I'm trying to set up c++11 to my project on visual studio, and to find out which version the compiler used by default I used the following code: #include <iostream> int main(){ #if __cplusplus==201402L std::cout << "C++14" << std::endl; #elif __cplusplus==201103L std::cout << "C++11" <<...
According to this question: Visual Studio 2012 __cplusplus and C++ 11 , provided by @paddy, this is a known bug with MSVC in that the version macro is set to C++98. You should compile with the /Zc:__cplusplus switch to change the version macro to the correct value.
64,436,361
64,438,743
Stepping through an OpenCV Mat with different data types automatically
This is a general question when stepping through OpenCV Mat in OpenCV >=3.0 Currently, I have a nearly copy-pasted function for each datatype of an OpenCV Mat (32F, 8U, 64F, 16S). That's not great because if I want to change anything, I'd have to change it in all 4 functions. Let's take, for example, a "max" function f...
Consider using Mat_ class template instead of Mat. With Mat_ you know type at compile time, and it is easy to rewrite your function into function template which is type-safe: template<class T> T Max(cv::Mat_<T>& A) { T* imPtr = (T*)A.data; T max = 0, dummy; for (int i = 0; i < A.rows; i++) { const T...
64,436,379
64,436,473
The need to pass different types in the initialization_list
I'm looking for a template based way to pass arbitrary number of params in the initialization_list(s). Something like: func({0, 1}, {0, 2.0f}, {0, "boo"}, ...); or func({{0, 1}, {0, 2.0f}, {0, "boo", ...}}); In the same time I want to be able to check the type of the second param in each (inner) brace. Maybe get size...
Make f take std::initializer_list<std::pair<std::any, std::any> >: void f(std::initializer_list<std::pair<std::any, std::any> > il) { for (auto it = il.begin(); it != il.end(); ++it) { const std::type_info& type1 = it->first.type(); const std::type_info& type2 = it->second.type(); if (type1 ...
64,436,390
64,436,450
Difference between pointer and array as template arguments
template<typename T, typename U = int> struct A {}; template<typename T, typename U> struct A<T*, U> {}; template<typename T, typename U> struct A<T[], U> {}; int main() { A<int*> m; // m: A<int*, int> A<int[]> n; // n: A<int[], int> return 0; } What's the difference between int[] and int* here as temp...
Isn't int[] simply a pointer too? No, it simply isn't. Arrays are arrays and pointers are pointers. Arrays are not pointers and pointers are not arrays. int[] is an array. There is a case where "array is pointer (and isn't an array)": In a function parameter delcaration, an array parameter will be adjusted to be a po...
64,436,686
64,436,750
Initialize a vector of classes that have member pointers to another class' member variables
For a scientific code I need to construct classes that require (member) pointers to member variables of other classes (i.e. both parents and siblings). I have researched this for hours and found several topics about pointers to member variables, but nothing about my specific problem. Hence my question: what is the corr...
In your code, whenever you copy a B object, the Cs inside the new B still point to the beta member in the old B. This is the problem you'd want to solve. Option 1: Use only B pointers, wrapped in smart pointers like or shared_ptr. Now when you copy it does not copy the underlying B object, and all Cs remain intact. Opt...
64,437,141
64,437,353
C++, pack integer bytes into a char array?
I'm transferring data over network, so trying to set up a header, where first 3 bytes are a message type, and the next 4 bytes are the size of the message. When I'm adding an integer, for anything over 127 bytes, I'm overflowing. How do I set up such header? Here's a simple example. If num is 127 or less, then the outp...
If num is 127 or less, then the output is correct, but if it's 128 or more, then the output is all messed up. It appears you're talking about the following part of the code where you try to read your integer back out of the char array and then display it: int out = *(x + 3); cout << "out: " << out << endl; The probl...
64,438,151
64,439,038
What is the best way to reject duplicates in a sorted doubly linked list
I am trying to make a sorted doubly linked list that doesn't insert duplicates, but I am having trouble finding a way to do this. I looked at posts on how to remove duplicates, but no posts on preventing duplicate insertions. Here is the code I have to insert and sort without rejecting duplicates. The parameter, dataIn...
What is the best way to reject duplicates in a sorted doubly linked list? I suggest delaying the creation of the new ListNode until you know that the new node isn't a duplicate. Assuming that the ListNode looks like this struct ListNode { Student stu; ListNode *back; ListNode *forw; }; and that y...
64,438,234
64,617,303
Function-local static objects in static inline functions aren't shared
I have the following in bla.h: #include <iostream> static inline void bla() { static int x; std::cout << "bla @ " << (uintptr_t)bla << ": x @ " << &x << std::endl; } Then bla() is called from 2 separate translation units resulting in this output: bla @ 94796100194693: x @ 0x56376fe10178 bla @ 94796100194897: x @ ...
As Igor Tandetnik commented the error is on cppreference.com as they left out an important part of the standard: The actual text of the C++ standard has this note in [dcl.inline]/6: "A static local variable in an inline function with external linkage always refers to the same object." Emphasis mine. – Igor Tandetnik O...
64,438,349
64,438,408
How can I delete the Error when creating pointers on C++? I this case I have to use raw pointers
I'm trying to make a linked list with a pointer to a template class called Node: template <typename T> class llnode { public: T key; llnode<T> *prev, *next; llnode() { }; llnode(const T &k, llnode<T> *w = NULL, llnode<T> *y = NULL) : key(k), prev(w), next(y){}; ~llnode() { d...
When you use them in main your pointers are not initializated. This ends in Undefined Behavior. Do this: llnode<int> *node = new llnode<int>; node->key = 6; llnode<int> *node1 = new llnode<int>; node->key = 2; Also note that calling delete this; in the destructor causes an infinite loop (More info here). Remove the de...
64,438,770
64,438,871
Trying to point to object in class constructor (C++)
I have this C++ code for my class DoubleKnob. I'm trying to have the class connect to a specific object of the class KnobLook that is specified when the DoubleKnob object is created. I am getting no errors in the object creation code and the KnobLook object is created before this one, but in this class I am getting the...
You declare the member variables outside the contructor, but assign them in the constructor. If you want a reference to the lookfeel variable to persist, make that a member variable. class DoubleKnob : public Knob { public: KnobLook &lookFeel; DoubleKnob(KnobLook& lookFeel) : lookFeel{ lookFeel } {} }; Then yo...
64,438,859
64,508,550
C++: I don't know how to solve the timeout in the problem of comparing coordinates in the coordinate plane
Up to 100,000 coordinates are entered. Only coordinates corresponding to specific conditions should be output. If there are coordinates with larger x values ​​and smaller y values ​​than each coordinate, the corresponding coordinates are excluded from the output list. My English is not good, so I'm giving some examples...
I'm not totally sure this works for every corner case, but the idea is here. It took me a while to nail it down, probably because the problem description wasn't exactly clear. Basically you want to mark as not visible the points for which it is possible to find another one with a larger x and a smaller y, i.e. the poin...
64,439,124
64,439,862
Is there a way to prevent creating another if statement for different types?
Is there a way to reduce all the if constexpr statements assuming the searching of the buffers is all the same behavior? template <typename T> struct Buffer {}; struct BufferManager { Buffer<int> intBuffers[8]; Buffer<float> floatBuffers[8]; Buffer<char> charBuffers[8]; template <typename T> stati...
Without changing the way you store your buffers, you can write a findSuitableBuffer that takes multiple heterogeneously typed buffers via a a recursive function variadic template... template <typename T> Buffer<T>& findSuitableBufferImpl(size_t size) { throw std::runtime_error("not found"); } template <typename T,...
64,439,569
64,439,708
Logcat on (embedded) test firmware
I am trying to create a test firmware using C code and would like to integrate LOGCAT onto it. Has anyone done this? or is this possible? I search over the internet and LOGCAT is commonly used in Android development, haven't seen one for embedded systems/ hardware. Is there an equivalent for embeddeded test firmware?
i belive your question is off topic but in embedded systems we use serial port such as UART for monitoring and debugging it works like terminal or LOGCAT and i didn't see any library that give you what you want i always build my own command system or debug system over serial port
64,439,654
64,439,676
How substr() of c++ really works?
I'm trying to print the substring of a string but the substr() function's behaviour seems odd to me. In my below program, I'm trying to print the substring of a string with value "Kamal". Here, substr(0,4) prints "Kama" which makes me assume that 0 is inclusive and 4 is exclusive. But substr(1,4) prints "amal" which vi...
string substr (size_t pos = 0, size_t len = npos) const; Generate substring Returns a newly constructed string object with its value initialized to a copy of a substring of this object. The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the st...
64,439,721
64,439,745
C++ Safe way to convert vector of char to size_t
Here is my vector of char: std::vector<char> size; Here is the size_t value: size_t body_size{0}; Here is how I convert std::vector<char> size to size_t body_size _packet.body_size = *(reinterpret_cast<int*>(_packet.size.data())); Is there another better/safer way to make the conversion?
Use std::memcpy(&body_size, &size[0], sizeof (body_size));. That's safe.
64,440,318
64,440,349
C++ - memcpy gives Exception: std::bad_alloc
Here is my code: std::vector<std::byte> size; static const int header_size_in_bytes = 4; size.resize(header_size_in_bytes); size_t body_size{0}; assert(size.size() <= sizeof(body_size)); std::memcpy(&body_size, &size[0], sizeof (body_size)); std::cout << "SIZE: " << body_size << std::endl; I use this piece of code to...
Why do you assert(size.size() <= sizeof(body_size)); If you read sizeof(body_size) from size, it should be >=. That assertion will likely fail, because on a 64-bit system, sizeof(size_t) is usually 8, not 4.
64,440,654
64,441,187
Why isn't my backtracking solution for N queens problem working?
Here's the output that it returns when I call it from the main function by passing args: 0 and board where 0 is the row number to start from and board is a 4x4 board filled with zeros: 9 1 1 1 1 1 9 1 1 1 1 1 1 0 1 1 Note: 9 means a queen and 1 me...
You're not backtracking - backtracking involves undoing a choice that leads to failure, but your board[row][col] is forever. You need to restore the board to its previous state if the recursion fails.
64,440,799
64,441,125
c++ derived constructor when defining function outside of class body - "no default constructor"
I'm working by myself through Bjarne Stroustrup's principles of programming book and am having trouble with defining constructors. This question requires using an interface which is built from the FLTK graphics library; generally no worries there. We have to make a smileyface out of the circle class, which does not h...
if I just define it in the initialization list, it works fine. So do that. That's what you are supposed to do. Initialization lists exist exactly for doing that. there will be lots of times in the future You Ain't Gonna Need It. do computation in an outside constructor function. In a pinch you can write a helper ...
64,440,989
64,441,650
Where is the 'unit'-ratio convenience typedef?
std::ratio provides convenience typedefs for metric prefixes (centi, deci, deca, hecto). yocto std::ratio<1, 1000000000000000000000000>, if std::intmax_t can represent the denominator zepto std::ratio<1, 1000000000000000000000>, if std::intmax_t can represent the denominator atto std::ratio<1, 100000000000000000...
what would be the most paradigmatic way to work with a 'unit' ratio? The most pragmatic way to work with a unit ratio is to not use it. It's a bit like asking what is the best way to multiply by 1. You don't. For example, when duration_cast-ing to whole seconds. You would write std::chrono::duration_cast<std::chron...
64,441,129
64,441,316
What exact is segmentation fault when using Stack and how to fix it?
Im writing a program to check the score of parenthesis, Leetcode Question 856. However, with the algorithm I used, I'm encountering a "Segmentation Fault (core dumped)" error. I'm unsure as to how there is a segmentation fault when using stack and how could I fix it? string s; cin >> s; int score = 0; stack<in...
When the stack is empty and you try .top() or .pop() then it will give segmentation fault (error caused by accessing memory ). string s; cin >> s; int score = 0; stack<int> st; for (int i = 0; i < s.size(); i++){ char a = s[i]; if (a == '('){ st.push(score); score = 0; } el...
64,441,248
64,441,321
Display using std::cout not work as expected
So I'm trying to make a school schedule that'd have text on the right side with text of a string I declared as laikas[7]. Note that it's in my native language (Lithuanian). My code is: cout << " 1) Vokieciu\n" << laikas[0] << "2) Biologija\n" << laikas[1] << "3) Vokieciu\n" << laikas[2] << "4) Daile\n 5)" << laikas[3] ...
your new line should come after the laikas part, and adding a couple of tabs will make it look prettier aswell :) int main() { // your code goes here string laikas[7] {"08:00", "08:55", "09:50", "11:05", "12:00", "12:55", "13:50"}; cout << "\n1) Vokieciu\t" << laikas[0] << "\n2) Biologija\t" << laikas[1] <...
64,441,292
64,441,850
Opengl using freeglut on linux shows only a transparent window
I am trying to use freeglut3 on linux mint 20 to do some basic openGL ( my teacher forced me to use glut/freeglut with c++ ). I am just trying to make a black window to show on screen but only a transparent window shows up and it doesn't close until it shows Segmentation fault (core dumped) here is my code #include <G...
You're creating a double buffered context using... glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); But you never call glutSwapBuffers. Change your display function to... void display() { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glFlush(); glutSwapBuffers(); }
64,441,302
64,441,366
std::list remove function gives compilation error for struct data
#include <iostream> #include <list> using namespace std; struct DATA { int d; int d2; }; int main() { DATA d1; d1.d = 100; d1.d2 = 200; list<DATA> ld; ld.push_back(d1); ld.remove(d1); } Compiling the above code gives following error: 1>------ Build started: Project: ConsoleApplicat...
As the error message tells you, you need an operator== to check equality. This is how the remove function will know which elements to remove. struct DATA { int d; int d2; bool operator==(const DATA& other) const { return d == other.d && d2 == other.d2; } }; Edit As pointed out by Jens it's generally a g...
64,441,667
64,441,829
Qt c++ application autostart on android tv
I have a QT application written on C++. It is working fine on all android/Linux/windows devices. But I want to make it run on android enabled TV. I also want to make it run and when the TV is turned on. Google shows me that the application must use leanback libraries. But is it possible to use these libraries inside C+...
Assuming the architecture is correct (ARM/x86), you need to mark it as AndroidTV. This link may be useful to you. https://developer.android.com/training/tv/start/start.html#tv-activity
64,441,733
64,511,809
LNK2019 error when using a library installed with vcpkg
I have installed libraries with vcpkg using the correct triplet : C:\Users\***>vcpkg list libnoise libnoise:x64-windows 1.0.0 A general-purpose library that generates three-d... Then I have executed the following command : C:\Users\***>vcpkg integrate install Applied user-wide integration for this v...
It has been fixed by the developers, on GitHub : https://github.com/microsoft/vcpkg/issues/14127