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
61,567,887
61,568,033
Vector of Card classes for Uno
I'm currently in the process of making Uno for a programming project. One part requires that I make the deck of 108 cards, where Card is its own class with a char color and an std::string value, the values of which I get from a file. I currently am just creating all 108 cards individually and then using push_back to pu...
As far as reading from a file and instantiating objects line by line goes, the code you’ve written is correct. However if I’m correct in assuming your goal is to make the code readable/more concise, a for loop would go a long way. For loops are code blocks that will automatically increment a counter variable for you u...
61,568,439
61,828,999
Question on querying memory regions (Windows)
I had written a program that enumerates all the memory regions of a process with the following attributes: MEM_COMMIT and PAGE_READWRITE, and that at the end of the program prints the total size of all the regions found, everything seems to work well, then I tried it on programs at 64 bits and it turned out that the to...
You cannot query physical memory using any normal documented Windows API functions. Virtual Memory is intended to be an abstraction, the Operating System is meant to handle all this in the background for you. There is RAMMap from SysInternals which can display information regarding physical memory but the source code ...
61,568,563
61,568,597
Why does my code occasionally show memory on the free store (heap) growing both up and down? (C++)
My understanding is that memory allocated on the free store (the heap) should grow upwards as I allocate additional free store memory; however, when I run my code, occasionally the memory location of the next object allocated on the free store will be a lower value. Is there an error with my code, or could someone plea...
The main problem with that code is that you are casting int * to int, an operation that may lose precision, and therefore give you incorrect results. But, aside from that, this statement is a misapprehansion: My understanding is that memory allocated on the free store (the heap) should grow upwards as I allocate addit...
61,568,612
61,568,759
Is jumping over/removing `PHDR` program header in ELF file for executable OK? If so, why?
I was doing some hacking in the binary for this simple C++ program to understand program headers for ELF: int main(){ } compiled with: ❯ make g++ -O0 -fverbose-asm -no-pie -o main main.cpp I used readelf -l main to get the following: Elf file type is EXEC (Executable file) Entry point 0x401020 There are 11 program he...
If the main program is of type ET_EXEC (non-PIE), it's probably runnable without PT_PHDR. The main use of PT_PHDR is being able to compare the (unrelocated) address in the header with the actual runtime address of the program headers (obtained by the dynamic linker via AT_PHDR in the aux vector) to determine the offset...
61,568,647
61,568,730
disable all warnings for google tests from cmake
I have a c++ project that I am compiling with cmake. I am also using google tests. These are my cmake files: cmake_minimum_required(VERSION 3.5) project(se-03-team-08 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 14) if(EXISTS $ENV{HOME}/Qt/5.14.2/gcc_64) set(CMAKE_PREFIX_PATH $ENV{HOME}/Qt/5.14.2/gcc_64) endif() if(EXIST...
-Wall is the compiler flag to enable all warnings. If you don't to see those warnings, I would start with removing that compile flag. That means, instead of set(CMAKE_C_FLAGS "-g -O0 -Wall -W -fprofile-arcs -ftest-coverage") try set(CMAKE_C_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage") Of course, compiler warnings a...
61,568,849
61,568,969
how to write constructor prototype for a struct in a class
I created a class BST and I am facing problem in creating constructor of a struct node in it. class BST{ private: struct node{ int key; node* left; node* right; }; node* root; public: //constructor for BST BST(); //constructor for node node...
Constructors for classes and structs must be declared within the definition of the class/struct. Your version does not do this, as node(int) is declared outside the node class. Change your code to this: class BST { private: struct node { int key; node* left; node* right; ...
61,569,136
61,569,160
why would complier allow Initializing a Class with reference member by default constructor
I am learning C++ primer 5th, and know that constructor initializers are required when a class defines reference member otherwise, compiler would complain about it. However, I wrote a static factory method returing the class with empty statement. #include <iostream> using namespace std; //Learning default initializin...
FromDefault exhibits undefined behavior, by way of reaching the closing brace without encountering a return statement. On an unrelated note, Default(int t) constructor binds the reference r to the local variable. Once the constructor returns, t is destroyed and r becomes dangling. Any attempt to use it afterwards woul...
61,569,465
61,569,507
C++ `std::move` custom type into a lambda capture
I have a class in which I deleted the copy assignment operator and copy constructor, leaving only a move assignment operator and move constructor. For example: struct Number { public: int *pNum; Number &operator=(const Number &rhs) = delete; Number(const Number &rhs) = delete; Number &operator=(Number &&rhs...
The problem isn't with the lambda. E.g. this works: auto l = [&, capA{std::move(n)}](int) mutable -> int { int b = *capA.pNum; // 5 return a + b; // 8 }; The problem is with std::function and this lambda. Because you capture a non-copyable object then the lambda is non-copyable. std::function requires ...
61,569,543
61,569,544
Why does the dynamic linker *subtract* the virtual address to find out location of loaded shared library executable in memory?
According to the ld source code here in dl_main. Without the context of what phdr is passed in to dl_main, I'm a bit confused on why main_map's load address is deduced by subtracting the virtual address. The code that I've traced through: 1124 static void 1125 dl_main (const ElfW(Phdr) *phdr, 1126 ElfW(Word) ...
In particular, on line 1414, we see main_map->l_addr = (ElfW(Addr)) phdr - ph->p_vaddr;. From the file link.h which defines the type link_map for main_map, I see that link_map is a struct that describes a loaded shared object. The l_addr field is to describe the difference between where the .so is loaded into memory vs...
61,570,016
61,570,193
Nested inner class access to outer class
I have a nested class that needs to manipulate the data members of its outer class. I demand that the outer class will not have an empty constructor. The following version compiles fine Is there any way to avoid using Outer *o inside Inner, and use Outer o? class Outer { private: class Inner { private: Outer ...
No, if you create a new instance, the situation will become cyclic. Instead of using pointer to the outer class, you can however use a reference, like so: class Outer { private: class Inner{ private: Outer& o; public: Inner(Outer& outer) :o(outer) {} void visit() { o.d = 65; } };...
61,570,044
61,570,180
getting specific k bits from a Decimal number
I have a number x and I want to print decimal of k bits from x suppose I have number 12 x = 12 k = 3 binary of 12 is 1100 and k =3 so my resulting new binary will be 100(decimal is 8) ie form last position I want to display 8 as output I want to do this with help of << and >> in c++ Thanks!!
Here is one way of doing it: zero out the last k bits, then subtract that from x. unsigned int last_k_bits(unsigned int x, unsigned int k) { return x - ((x >> k) << k); } You can also calculate the bitwise & of x and 1...1 (k 1s) unsigned int last_k_bits(unsigned int x, unsigned int k) { return x & ((1u << k) ...
61,570,389
61,570,478
getting error while trying to rotate array clock wise using stack
Given an unsorted array arr[] of size N, rotate it by D elements (clockwise). Input The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Su...
I followed your logic, it seems like there is problem in your backfill part. for(int k=s-1;k>=s-r;k--) { // change k>r+1 to k>=s-r a[k] = st.top(); st.pop(); }
61,570,603
62,747,990
Can not compile win32 C++ Using Mingw
I wanted to start learning win32 api but the g++ would always return with undefined reference to `WinMain@16' I copied my cpp code from microsoft's website from here - Link. I tried multiple other sources of "Hello World" but without luck. What should I do?
You can work with two types of entry-point functions in WinAPI: WinMain and wWinMain. The WinMain function is identical to wWinMain, except the command-line arguments are passed as an ANSI string. The Unicode version is preferred. Source: Microsoft Docs Both should work well with Microsoft Visual C++ compiler. Howeve...
61,570,671
61,572,592
How to build Qt5 without webengine?
Following is the result of building Qt5 from source on macOS. It takes 31G, from which 27G are from webengine. Unfortunately I didn't tracked the build time but it's many hours. I think I don't need webengine for my application. And I guess build will be much quicker (and smaller) without it. How to remove webengine fr...
You can skip modules with -skip qtwebengine as argument for configure: https://doc.qt.io/qt-5/configure-options.html#excluding-qt-modules
61,570,701
61,571,690
C++ g++ -pedantic warning
I am studying Bjarne Stroustrup's book 'Programming Principles and Practice Using C++'. I downloaded his header file from here and used the following compiling command in VSCode on Windows: g++ -Wall -Wextra -Wconversion -pedantic -std=c++17 -g -c main.c The compiler threw up a bunch of errors: std_lib_facilities.h: I...
1. That semicolon is redundant. It’s only mandatory after the closing brace } of a class, struct, enum or union definition. 2. As the error message says, an unsigned type can never have a negative value, so testing if (i<0) is useless. The compiler warns because such a useless test is an indicator for a probable mistak...
61,570,740
61,570,997
stable_sort on a vector of pairs by first element in pair in increasing order without comparator function in C++
#include <bits/stdc++.h> using namespace std; int main() { vector<pair<int,int>>v; v.push_back(make_pair(1,3)); v.push_back(make_pair(1,1)); v.push_back(make_pair(2,19)); v.push_back(make_pair(2,4)); int n = 4; stable_sort(v.begin(),v.end()); for (int i = 0; i < n; i++) ...
The reference for operator< of std::pair<int, int> says that it Compares lhs and rhs lexicographically by operator<, that is, compares the first elements and only if they are equivalent, compares the second elements. So both elements are used to compare a std::pairand what you see is a fully sorted vector. Relative o...
61,570,936
61,570,956
Custom container traversal with range-based for loop
In C++, some STL containers like vector, map, string can be traversed by for loops with colon in it. for instance: for(auto c:v) When I'm writing a custom container, can I make it traversed that way like Java (which only need to implement Iterable)?
Yes, you need to implement some form of iterator and override std::begin(container) and std::end(container) (might work also if you container has begin and end methods). Internally the code is equivalent to something like the following (this is just to get the point across, the compiler can write it slightly differentl...
61,571,081
61,580,243
Problem implementing reflections in ray tracing
I've implemented a simple ray tracer and now I'm trying to implement reflections but objects are behaving as transparent. Here is my code for getting the reflected ray. ray* reflected = new ray(); reflected->direction = rayIn.direction - (2 * glm::dot(rayIn.direction, normal)) * normal; reflecte...
Problem was this part of code for (objects in scene){ double intersection = (*objIterator)->intersect(rayIn,normal); if (intersection < minDistance && intersection > epsilon ) { minDistance = intersection; int_object = *objIterator; int_point = rayIn.origin + intersection * rayIn.d...
61,571,089
61,572,416
why cannot use the double pointer as the return type in function head?
I'm not sure how to handle the bug for the double pointer as the return type in function head. The code like this: #include<iostream> #include<fstream> #include<sstream> #include<string> int noodrows(); int noodcols(); string** genMatrix(int rows, int cols); using namespace std; void main() { //ifstream file("te...
write std::string** genMatrix(int rows, int cols) { string is a std(standard template library for c++ witch is Optional to use) type si you need the namespace and the header file included (witch you have already included) . i personally don't prefer using using namespace std; in global scope to not mix types in diffe...
61,571,099
61,574,097
Variadic templates for multiple heritage assertions - "...redeclared with 3 template parameters..."
I am trying to implement my own std::is_base_of for my AVR programming (avr-gcc does not yet support <type_traits>. I took inspiration of the possible implementation on the cppreference page, it worked for a single type check. However, what I want to achieve is a statically executed validity checks of multiple types' h...
Issue with template<typename TBase, typename TCandidate, typename... TRest> struct isBaseOf { isBaseOf() = delete; static const bool value = isBaseOf<TBase, TRest...>::value && std::is_base_of<TBase, TCandidate>::value; }; Is that a the end, you finish with: static const bool val...
61,571,117
61,572,435
How to access a constexpr string that is defined in a struct?
How to properly access the string "bye" from the struct? #include <iostream> static constexpr char hi[] = "hi"; struct S{ static constexpr char bye[] = "bye"; }; int main(int argc, char *argv[]) { typedef struct S ST; std::cout << hi << std::endl; // this prints "hi" std::cout << sizeof(ST::bye)...
This can be made working by redefining the static constexpr outside the struct: #include <iostream> static constexpr char hi[] = "hi"; struct S{ static constexpr char bye[] = "bye"; }; constexpr char S::bye[]; // <<< this line was missing int main(int argc, char *argv[]) { typedef struct S ST; std::cout << hi <<...
61,571,145
61,573,933
Default template paramters and partial specialization
I'm trying to understand partial template specialization with default arguments. If I remove the cast to void in the is_comparable specialization the value printed is always false, while if I keep the cast to (void) things work fine. Can someone please explain why the cast to void is needed? It likely has to do with ma...
We use primary template for default, so is_comparable<int, char> is is_comparable<int, char, void> is_comparable<int, float *> is is_comparable<int, float*, void> is_comparable<int*, int*> is is_comparable<int*, int*, void> Now, your specialization without void cast is mostly (unless special overload of operator==) i...
61,571,219
61,571,317
Why always need [&] when using recursion with lambda?
I am new to lambda expression ,When I wrote little program like this : function<int(int)> test=[](int i){ if (i<3) return i; else return test(i-1); }; //call test(5); And the error message be something like this : lambda.cpp:36:16: error: ‘test’ is not captured return test(...
Normal functions do not capture anything. test is globally (actually in the namespace) available. That's why int test(int i){ if (i<3) return i; else return test(i-1); } works. When you define a local variable in a scope in which you define a lambda you'll need to tell the lambda to capture (copy) that vari...
61,571,396
61,571,419
Calculating the sum. Unintendedly getting fractions rounded. C++
I need to write a code to calculate the following sum: #include <iostream> #include <cmath> using namespace std; int main() { int m,n; cin>>n>>m; float sum = 0.0, prod = 1.0; int i = 2; while(i <= n) { int j = 3; while(j <= m) { prod = prod * (float)(i*i/j);...
Recast j: prod = prod * (i * i / (float)j); This will promote the product to a float. Some rules of conversion may be useful, generally: https://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions
61,571,429
61,571,547
C++ Calling a function that returns template type value
I am trying to understand if it is possible to call a function that returns a template type value without explicitly specifying it in call statement? Function I am trying to call is like this, template <typename T> std::unique_ptr<SomeClass<T>> createObjectInstance(InputData data) { if(data.type_str == "abc") { ...
It is not possible to define the return type of a function at runtime, as your example tries to do. When you define a function with a templated return value, the returned value can only be of one type. And that type MUST be defined at compile time. The only way your function may compile, is to have the type of the r...
61,571,668
61,572,408
How to fix it in BST insertion and let the insertion function work
The code showed in Visual StudioThe InsertBSTNode function is wrong. But I don't know how to fix it. The requirement is that do not change the type of the function. TreeNode class TreeNode{ public: int data; TreeNode* left; TreeNode* right; TreeNode(int x): data(x), left(NULL), right(NULL){} ...
So this is the code I think you are trying to write void InsertBSTNode(TreeNode* &root, int val) { if (root == NULL) { root = new TreeNode; root->data=val; root->left=root->right=NULL; } else if (val<root->data) InsertBSTNode(root->left,val); else InsertBSTNode(ro...
61,571,779
61,572,571
Number of occurences of a number in all the queries?
Take an unsorted array like: 4,5,1,2,3,7,8,3 and queries be like: [1 2] [5 5] [2 6] [6 6] [1 6] [1 5] where each query represents a interval of indices. Length of array and total queries can be upto 100000. I want to calculate the number of occurences of every index in each of the queries like below: occurences of...
You can solve it by BIT(binary index tree) or Segment-Tree.. I attached two link there to learn about those algoritm... BIT solution: For each query lets range: [l r] : Now you need to update in BIT l to n with value 1. Now you need to exclude update r+1 to n...so update r+1 to n with value -1 in BIT.. Each update op...
61,571,793
61,572,017
How can I print out the record of specific staff using vector in C++?
For the task, there are 4 staffs and each staff has own work record. How can I save the work record to that specific staff and print it out using vector? For example, the second staff has 2 works to do and others don't have any. Then I have to print: First Staff: No Work Found! Second Staff: Work 1:xxxxx ...
i assume you have a class that contains your staff your vector would look like vector<Staff> staff; // Staff would be replaced with your class name then you can create a loop to populate your vector for (int i=0;i<n;i++) // where n is the number of staff { staff.push_back(worker) // push back what ever function you h...
61,572,072
61,572,146
Overloading a function with the same require conditions
The following code (online) template<int m> struct A { void f(A<m> const& that) const requires m > 1 { } void f(A<1> const& that) const requires m > 1 { } }; int main(){ A<2> a; a.f(a); return 1; } gives the error void A<m>::f(const A<1>&) const requires m > 1 [with int m = 1] cannot be overloaded...
The key here is "[with int m = 1]". When m is 1, you get these two "overloads" void f(A<1> const& that) const requires 1 > 1 { } void f(A<1> const& that) const requires 1 > 1 { } The unsatisfied requires clause doesn't "undeclare" an overload. It only makes the overload not participate in overload resolution. The over...
61,572,289
61,572,346
output is NaN for standard deviation - C++
I have a process in my client program that iterates through a custom vector, and performs some calculations to calculate standard deviation. It converts a wind speed from m/s to km/h, so its *3.6 to convert. For my sigma value, and of course my standard deviation which requires the sigma value, my output is NaN and I c...
You must initialize variables before using. Strictly speaking, in this case, you don't have to initialize nrofel, averagespeed, and sd because they are assigned some values in the loop without being read before assignment. On the other hand, you must initialize sum and sigma because their values are read before assignm...
61,572,399
61,572,618
Using lambda for callback function as C function parameter
I was writing my own std::thread-like wrapper for pthread_* functions (for educational purposes). The constructor I came up with looked like this: template<class Fn, class... Args> explicit Thread(Fn&& fn, Args&&... args) { using Invoker = Thread_invoker<Fn, Args...>; void* (* start_fn)(void*) = [](void* invoke...
Does this modification solve the problem and is the code legal now? No, it doesn't solve the problem. The function pointer you can obtain from the lambda expression is only to a function with C++ language linkage. The way to obtain with certainty a pointer to a function with C language linkage is to use a free functi...
61,572,610
61,575,849
concept in header doesn't constrain a parameter pack in C++20?
Context: I am rewriting a library that worked with the GCC -fconcepts to C++20. Clang 10 and GCC 10 give me the same unexpected problem, so it's probably my fault. I have a class template that supports two cases. It can either be created from a list of pin_out's, or from a list of port_out's. template< typename T > con...
One of the many things that P1141 changed was what a variadic constraint actually means: In [temp.param]/11 we have: template <C2... T> struct s3; // associates C2<T...> This seems to be doing an unexpected thing, which is having the constraint apply to more than one type in a pack at a time. And as a result of tha...
61,572,664
61,642,171
Make - Internal compiler Error under QT 5.14.2 "Q_CORE_EXPORT"
I just installed QT Creator with QT under Win10 to build an already existing project. (Under Ubuntu everything went fine running the Make file). I'm not an expert for QT therefore I'm not able to find out how to resolve the error: C:\Qt\5.14.2\mingw73_64\include/QtCore/qfloat16.h:102:54: internal compiler error: in m...
I just found out from qmake.stash, that the included script for creating the make file always referenced a false path for the gcc compiler. I therefore build i manually with the QT Creator and it worked as expected. So I guess the fault was due to different paths for gcc in the environmental variables.
61,572,826
61,573,315
Is there a macro for ifstream and ofstream or a way to shorten ifstream/ofstream?
For example if my file name is : sum00.in, sum.00.out, is there a possibility excepting the one of writing each time the same piece of code: ifstream in("sum00.in"); ofstream out("sum00.out"); I first thought of macro: #define read(x) ifstream in("x.in"); ofstream out("x.out"); ///But it doesn`t work for a word. Eve...
I would recommend not using a macro. I'd encapsulate it in a class. Example: #include <fstream> #include <iostream> #include <string> class MyIO { public: explicit MyIO(const std::string& basename) : in(basename + ".in"), out(basename + ".out") {} std::ifstream& is() { return in; } std:...
61,572,940
61,573,128
C++ Beginner: std::cin to std::string
Just started learning C++ and encountered an issue with strings while doing an exercise. So I initialized std::string phrase; while allowing the user to input and save the phrase to the string with std::cin >> phrase;. Now my issue comes when the inputed phrase has spaces, I noticed that the computer will only save th...
I have also had this problem when i was first starting out. whenever you want to read a string i would use the getline. ie string phase cout << "enter phase" <<endl; getline(cin,phase);
61,573,028
61,573,073
Difference between \\ and / when working with path directories
Whenever I do any sort of file read or write, I always use the '/' but I've seen some examples where the value of the given filepath is '\\' instead. So what's the difference? Am I doing it wrong or introducing bugs if I use '/'?
There's nothing wrong with using / on systems that support it. In fact, on UNIX systems it's the only thing that works. Windows supports both / and \ as path separator in most situations. Note that a platform agnostic option is available in the form of std::filesystem::path.
61,573,279
61,573,373
Compiler error with sfinae and custom power function
I want to implement power of integer in metaprogramming way with sfinae like #include <iostream> template<bool B, typename T = void> struct enable_if; template<typename T> struct enable_if<true, T> { using type = T; }; template<typename T> struct enable_if<false, T> {}; template<int N, typename T> typename enable_i...
The order of declarations matters. Whichever block appears first does not see the other block. Which means that when you do overload resolution in the body of the first block, the second block won't be a candidate. Only declarations that are visible up to that point are candidates (excluding other details like ADL, whi...
61,573,374
61,573,618
Getting only the filename out of the path with GetOpenFileName
So I have this code: OPENFILENAME ofn; char file_name[100]; ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = NULL; ofn.lpstrFile = file_name; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = 100; ofn.lpstrFi...
Got it by using the std::filesystem::path class: std::filesystem::path myFile = ofn.lpstrFile; std::filesystem::path fullname = myFile.filename(); cout << fullname.c_str() << endl; And it also works with the method pointed out by @WhozCraig: #pragma comment(lib, "shlwapi.lib") #include <Shlwapi.h> PathStripPath(ofn....
61,573,417
61,574,137
c++ particle system inheritance
i'm creating particle system and i want to have possibility to choose what kind of object will be showing on the screen (like simply pixels, or circle shapes). I have one class in which all parameters are stored (ParticleSettings), but without those entities that stores points, or circle shapes, etc. I thought that i m...
From the sounds of it, the ParticlesInterface abstract class doesn't just have a virtual getParticleVertex because that doesn't make sense in general, only for the specific type ParticlesVertex, or maybe a group of related types. The recommended approach here is: Any time you need code that does different things depend...
61,573,792
61,573,851
searching for the times in an array
there, I am new to C++, The code below is supposed to output all the items containig a certain character I input. I mean ,if I enter the char 'w',it should output "two" and "water" or when 's' is input the result shoud be "sabit","sally", and "paris". So I can not figure out how to modify the code. #include <iostream>...
Instead of your for loop it seems you mean the following for ( const auto &s : ad ) { if ( s.find( q ) != std::string::npos ) std::cout << s << '\n'; } Here is a demonstrative program. #include <iostream> #include <string> int main() { std::string ad[] = { "sabit", "two", "sally", "water", "mike...
61,573,820
61,573,964
Why can .end() return an invalid iterator instead of being evaluated every time (like .size()) and checking if it's still valid?
I recently learned about iterator invalidaiton in c++. I fail to understand why a .end() function in a for loop can return an invalid iterator, when, because it's a for loop, it should result in a function call to .end() every time the loop runs, just as a index based for loop would with .size(). Is there some kind of...
Basically std::vector<int> is a wrapper around an array int * that is dynamically allocated. So let's take a look how to iterate over an array. We can iterate using the size. Here the 6 corresponds in your code to v.size(): int *v = new int[6]{0, 1, 2, 3, 4, 5}; for (size_t i = 0; i < 6; ++i) { // do something with...
61,574,273
61,595,147
Delay before rendering issue using OpenGL save and render process is used
I have created a c++ compute program using GLFW OpenGL that calculates the simple physics of gravity on particles over a pre-defined time period, saving the calculated results to a standard GL_ARRAY_BUFFER. This is setup in a standard way: glGenBuffers(1, &vboSTATE); glBindBuffer(GL_ARRAY_BUFFER, vboSTATE); int bufferS...
This issue was solved by using the glFinish() after each copy operation to ensure the data was actually copied. I found the solution with the help of the suggestions provided by the community here. This does increase the loop times considerably but at least you know for sure openGL is finished writing and the data is r...
61,574,514
61,595,856
C++: assignment operator: pass-by-value (copy-and-swap) vs pass-by-reference
Considering the advantages of copy-and-swap idiom... Why do we still need copy-assignment operator accepting references as the mainstream? class T { public: // 1: Why still commonly this? T& operator=(const T& rhs); // 2: Why not mostly that? T& operator=(T rhs); } There are answers suggesting to use...
I was pointed to the valuable hint: For example, ever wonder why high performance / often used std::types like std::vector and std::string don't use copy/swap? | Howard Hinnant Everything I found against copy-on-swap was about optimization (avoid copy, re-purpose lhs): Obviously, self-assignment is noop. Another com...
61,574,996
61,575,160
recursive vs iterative factorial in C++
I made a shitty c++ programme to calculate the factorial of an entered value wherein I wrote two functions to do the actual calculations independently (one iterative, the other recursive). What doesn't make any sense to me is, why does the iterative factorial collapse at around n = 13 but the recursive goes all the way...
In iterativ_fak() you multiply variable n which has type int. It is 32 bit type and can only store 12! at max. rekursiv_fak() on the other hand returns unsigned long long type variable and therefore has 64 bit to store result of n * rekursiv_fak(n - 1).
61,575,014
61,575,271
How to modify pointer reference to struct member variable
I want to create BST in C++. When I try to assign pointer to new node - it does not change. After fucntion call it still have random value. Is it possible to do it my way? struct wezel { int value; wezel *l_val; wezel *r_val; wezel(int aValue) { value = aValue; l_val = NULL; r_val = NULL; } }; ...
wezel pt = wezel(aValue); wezel *point = &pt; aNode.l_val = point; Here you are creating a pt object of type wezel, which will get destroyed once it goes out of the scope, while the pointers 'point' and aNode.l_val still pointing to its address. (By the way 'point' will also get destroyed upon leaving the scope.) Inst...
61,575,056
61,575,257
Arduino, Run Time Code Error in Debouncing Voltage Time Delay Code
I am Ansh Goel, I was learning Arduino from Udemy. I am beginner to this field. I was creating a code for Debouncing the button to solve the issues of bouncing voltage. But there is error in the code. There is no Compile time error but it is run time error. I also tried to check the code using the Serial.print() to fin...
There are several locations where your code could malfunction: you're not looping properly for loop your logic doesn't work digitalRead doesn't work print doesn't work first, remove the debounce check and see if this works: //if(millis() > (last_debounce_time + debounce_delay)){ to check all other issues, add the fo...
61,575,222
61,586,644
show webview/webpage window in c++ windows desktop application
I want to display a popup/notification in a c++ windows application. The notification will display a webpage from our website. I am looking for something similar to CEF but native OS APIs to display the webview content. Maybe there is some class that I could use with CreateWindowEx?
Create an empty C++ project Create a resource dialog. Right click on dialog and add an ActiveX->Microsoft Web Browser control. Resize it, and move to right place. Change the ID so you can identify it in your program Add a C++ file with similar content: //#import #include <Windows.h> #include <Ole2.h> #include "reso...
61,575,287
61,576,207
How has += operator been implemented in c++?
This is a question I've always pondered on and have never found any resource stating the answer to this question. In fact its not only for +=, but also for its siblings i.e. -=, *=, /=, etc. (of course not ==). Consider the example, int a = 5; a += 4; //this will make 'a' 9 Now consider the equivalent expression: a = ...
Operators are not generated from others (except with/from <=> in C++20): providing operator < doesn't allow a > b (which is indeed "logically" equivalent to b < a). You have to implement all (even by re-using some). For classes, a += b is not a shorthand for a = a + b but for a.operator +=(b) or operator +=(a, b) In t...
61,575,288
61,586,640
Memory leak on throwing an exception with a pointer member variable
I have the following problem: Every time I throw the following exception, I am getting a Valgrind Memory leak warning: I am was able to reliably trace it back to the throw MyException{pointer} statements I have in my program. - If I comment them out the warning is gone. I have multiple other exception classes that work...
I managed to solve the problem: My catch was: catch(Except::CustomException& exception) { std::cout << "Exception occurred" << std::endl; exit(0); } Which was causing all the problems. Now I use catch(Except::CustomException& exception) { std::cout << "Exception occurred" << std::endl; flag = true; } if(flag)...
61,575,350
61,575,616
C++ Variable unexpectedly overwritten
I just don't get it. I have two "main variables" address and parameters. address is a const char and parameters is a string (char array) which is getting filled with information. Now the very weird thing (at least for me): After adding the timestamp to parameters, address is cleared! Does someone have an idea why? #inc...
This pile of buffers and strcats and stuff is waaaaaay more complicated than it needs to be Instead you can do this: char parameters[512]; int result = snprintf(parameters, sizeof parameters, "?secret=w2q3oifin23c" "&deviceName=%s" "&status=%d" "&value=%d" "&functionName=%s" "&time=%d" ...
61,575,415
61,577,616
Class with std::map object and deleted copy assignment and constructor causes C2280 with std::pair's copy constructor
I'm trying to build my dll library after adding serialization classes to it. I have this code: class VariablesSerializableValue : public SerializableValueBase { private: Serializable::Variables value; public: VariablesSerializableValue() = default; VariablesSerializableValue(const VariablesSerializableV...
An error with the std pair constructor is caused by a map operation that invokes the copy constructor, such as std::map::insert. A call to insert won't work, because one cannot copy a unique_ptr, so the compiler will complain about a deleted constructor. Instead, you will have to std::move the unique_ptr into the map w...
61,576,279
61,576,540
How to use openGL draw the point?(c++)
I want to use openGL draw a Coordinate System,and the code has draw the x-axis and y-axis. However the origin point cannot be draw. How to solve the problem? I think the code is correct and search the resource in the internet. There are no solution for the debug. Here is my code: #define FREEGLUT_STATIC #include <GL/fr...
GL_POINT is not a valid primitive type. The primitiv type for points is GL_POINTS. See Point primitives. Furthermore the point size is limited. 100.0 exceeds the limit. Reduce the point size: glPointSize(10.0); glColor3f(0, 1, 0); glBegin(GL_POINTS); glVertex2f(450, 0); glEnd(); GL_POINT is a enumerator constant ...
61,576,402
61,576,574
Regarding variables declared in a C++ file but not the header file
If I make a static global variable in the C++ file, but do not declare it in the header file, when I make a library from those files, will I be able to access it (the variable)?
Assuming that the variable is free-standing and defined at file scope (it is not part of a class in some way) and that the keyword static adorns its definition, then the variable will be accessible in the file in which it is defined. It will not be accessible by name from any other file — that's the point (or one of t...
61,576,440
61,633,561
Define class in Delphi without implementation details
My Delphi application using a C++ DLL which internally uses a 3rd party library (also written in C++). There is a class from the 3rd party library which I would like to use in the Delphi application. We have the header(s) from the 3rd party library. The idea is to pass a pointer to an instance of this class, via CALLBA...
The flattening approach suggested by Rudy Velthuis worked, but I managed to solve the problem in a way which may be of interest to other Delphi developers. This approach works because the data that is needed (_height, _width and _data_) has been defined as public in the C++ class. Step 1: Define a custom structure to h...
61,576,673
61,577,827
OpenCV get faces from image and predict with model
The piece of code which retrieves faces from grayscale image (already converted to cv::Mat) works oddly, what I'm doing wrong? // in initializer list model(cv::face::FisherFaceRecognizer::create()) // .... const cv::Mat grayscale = cv::imread("photo_15.jpeg",cv::IMREAD_GRAYSCALE); std::vector<cv::Rect> faceCandidate...
We resolved this in the comments, but for future reference: The fact that this line // this line for the testing purposes only model->predict(grayscale, label, confidence); had better confidence than // Recognize current face. m_model->predict(faceResized, label, confidence); occurred because the model was trained wi...
61,576,695
61,627,061
How to understand what two declarations are different
I just kind of don't understand the sentece " if the declaration sets of S ( f , B i ) and S ( f , C ) differ" in [class.member.lookup] section,what are different declarations except that their types are different,such as If two declarations are declared the same type but they are declared in different scopes resp...
The text you quote is from [class.member.lookup] which only applies to looking up names in class scope (as covered by the first sentence of the section). In your sample code there are no classes so this section does not apply. That code would be covered by [basic.link]/9: Two names that are the same (Clause 6) and tha...
61,577,053
61,577,297
Why garbage is displayed in the thread function? | Pthread
Sorry for my English. I'm use QT Creator. I'm just starting to study threads) And this is my first serious problem. I do not understand why I cannot get the exact value of my string from a thread function. With string My code Output I tried many options, but everything turned out to be in vain. I tried to do 'char *' i...
int rec = pthread_create(id_stream, NULL, PrintMessage, (void *)&call_mess) This creates a new thread, passing to it a pointer to call_mess, as a parameter to PrintMessage. This, the parent thread, immediately continues running, it returns from pthread_create() and reaches the end of the loop, at which point the call_...
61,577,740
61,580,061
Operator overloading in queue
so what im trying to dois overload the - operator in a queu in order to remove the numbers in common with another queue from a queue. ex: queue A:[5 4 3 7] queue B:[5 2 1 7] A-B A=[4 3] i have done this: CFilaInteiros& operator-(const CFilaInteiros& b) { if ( inicio == NULL ) cout << "Fila vazia..." << end...
You posted: CFilaInteiros& operator-(const CFilaInteiros& b) { ... CNoFila * aux = inicio; while( aux != NULL ) { if(aux->dados==b->dados) retiraDaFila(aux->dados); aux = aux->proximo; } } But b->dados is incorrect (b is not a pointer, and CFilaInteiros has no dados), and you are it...
61,578,474
61,579,700
Parsing G-code with arduino from an sd card
As the title suggests, I am using the following function to read the parameters of some g-code files present on the SD card: long parseParameters(String data, char* c){ int offset = data.indexOf(c); int offset1 = data.lastIndexOf(" ", offset + 1); return offset1 > 0 ? data.substring(offset + 1, offset + off...
Thats the explanation: int offset = data.indexOf(c); //in your example S "P3 S255"; ^ offset = 3 then you parse for offset1 but take another param namely " " after offset - but there is no " " in the string from offset+1 see above where the index is so it returns -1 why? myString.lastIndexOf(val, from) The i...
61,578,698
61,579,932
std::unordered_map::count is not working in my code
I have a doubt with the solution of this question which is stated below - Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in ...
unordered_map::count returns the number of items with specified key. As you don't use multi_map version, you only have 0 or 1. Associated value doesn't change presence of key in map. To use count, you should remove key when value reaches 0: for (char r : ransomNote) { if (umap.count(r) == 0) { return false;...
61,578,748
61,579,840
How to return a vector from repository to the service layer
For the repository i had to use a implementation of a linked list of Movie , ( all is a list ) , but i need to return a vector of the elements from the list to the services layer, I'm kind of lost and I would really need some help const vector <Movie>& MovieRepo::getAll() const noexcept { vector<Movie> vect; fo...
Possible fix 1: const vector <Movie> MovieRepo::getAll() const noexcept { vector<Movie> vect; for (auto& m : all) { vect.push_back(m); } return vect; } const vector <Movie>& means you will return a const & to a temporary(vect). This temporary will be destroyed after the function returns. Possib...
61,578,918
61,580,538
C++ Inheritance Overriding Vector Member Variable
Say you had an class class Foo { // stuff }; and you had a derived version of that class class Bar : public Foo { // extra stuff }; and you had a class with a vector of pointers to Foos. class FooManager { public: std::vector<Foo*> objects; } Could you derive FooManager into BarManager where BarManager has a v...
No, that is not possible. As one user pointed it it looks like a XY problem. You should better explain what you want to achieve. Given only the few explanation... One solution is to use std::vector<Foo*> objects; in FooManager and in BarManager to have functions that take objects and cast the pointers in objects to Bar...
61,579,041
61,608,416
Calculating the vertical gradient of 2D image causes strange output
I want to apply a simple derive/gradient filter, [-1, 0, 1], to an image from a .ppm file. The raw binary data from the .ppm file is read into a one-dimensional array: uint8_t* raw_image_data; size_t n_rows, n_cols, depth; // Open the file as an input binary file std::ifstream file; file.open("test_image.ppm", std::io...
Ok, first clue is that the image looks circularly shifted. This hints that strides are wrong. The core of your problem is simple: n_rows = std::stoi(temp_line.substr(0, temp_line.find(' '))); n_cols = std::stoi(temp_line.substr(temp_line.find(' ')+1,temp_line.size())); but in the documentation you can read: E...
61,579,059
61,579,219
One mouse click is registered twice C++ / GLUT
I have to make some transformation with left mouse click. This is part of my code: void mouse(int button, int state, int x, int y) { if(button == GLUT_LEFT_BUTTON && v*p + xk <= 34 && v*p + yk <= 34 && v*p - xk <= 34 && v*p - yk <= 34) { std::cout << "Resized" << std::endl; p += 0.02; } glutPostRedisp...
The glutMouseFunc() is invoked once, when the mouse is pressed and once when the mouse is released. When the mouse is pressed, then the actual state argument is GLUT_DOWN. When the mouse is released then the argument is GLUT_UP. Additionally test if state == GLUT_DOWN: void mouse(int button, int state, int x, int y) ...
61,579,178
61,579,367
Is there a way to perform math operations on a vector of vectors in C++?
Attempting to use the banker's algorithm and trying to calculate need using C++. I was trying to get the Max / Allocation vector to subtract from each other and can't seem to get the right method of using math on vector of vectors. The whole program is supposed to output the Allocation / Max / Need and I haven't been a...
need[i][j] = max[i][j] - alloc[i][j]; This doesn't work because you haven't allocated any memory for need. need.push_back(max[i][j] - alloc[i][j]); This doesn't work either because need is a vector of vector, so push_back expects a vector, and you are giving it a single value. I'm guessing what you want is something ...
61,579,182
61,579,317
How can I let two classes communicate with each other the best in C++
What I have now 2 Classes, of which one has the other, ClassB is a part of ClassA, I thought of this abstract example to show how the relation is. //-----------car.cpp #include "engine.cpp" class Car{ Engine engine; ErrorLight errorLight; //in other languages I would here pass the method engineReportsError ...
callback should work, but you have to pass also the custom data... We are in C++, you can use std::function to resolve all those issue: class Car{ Engine engine; ErrorLight errorLight; Car() { engine.startEngine( [this](const std::string& msg){ return this->engineReportsError(...
61,579,440
61,580,286
Overloading Pre-Increment Operator
Here is the declaration: Iterator operator++();//pre-increment Here is the definition: LinkedList::Iterator& LinkedList::Iterator::operator++(){ return Iterator(current->next);//this is giving me an error } Here is how the class looks class LinkedList{ public: Node struct{ /*contains pointer to next nod...
You create a new iterator object, and (attempt to) return a reference to that. The prefix-increment operator modifies this object, and should return a reference to itself: current = current->next; // TODO: Add checking for not going out of bounds or dereferencing a null pointer return *this;
61,579,630
61,581,084
cin to function arguments without variable
I want to pass user input directly to function without variable. Now I am doing this: int temp, len; cin >> len; for (int i = 0; i < len; i++){ cin >> temp; foo(temp); } Can I do it without temp? Maybe I should not use "cin"?
You can still create wrapper function: template <typename T> T get_input(std::istream& cin) { T res; std::cin >> res; return res; } And then: const int len = get_input<int>(std::cin); for (int i = 0; i < len; i++) { foo(get_input<int>(std::cin)); }
61,579,631
61,581,411
Ranges V3 zip with auto and structured bindings
I would like to be able to use C++ ranges to help simplify code logic via zipping containers rather than explicitly indexing into them. I can get this to work with a verbose lambda argument, but I would rather try to make it simpler/generalizable with more auto. const int n = ...; std::vector<float> a(n), b(n), c(n); ...
The short answer is: don't use const if you don't actually need const. You want to modify something, so why const? This works fine: ranges::for_each( ranges::views::zip(a, b, c), [](auto&& v) { auto&& [a, b, c] = v; c = a + b; } ); As does the shorter: for (auto&& [a, b, c] : ranges::v...
61,579,749
61,579,771
Strange type deduction
Today I saw a really strange type deduction. Here is the code: unsigned int y = 15; int k = 5; auto t = k - y / 2; Since k is int, I assumed that type of t should be int too. But to my surprise, its type is unsigned int. I cannot find why type is deduced as unsigned int. Any idea why?
Due to the usual arithmetic conversions if two operands have the same conversion rank and one of the operands has unsigned integer type then the type of the expression has the same unsigned integer type. From the C++ 17 Standard (5 Expressions, p.#10) — Otherwise, if the operand that has unsigned integer type has rank...
61,579,780
61,586,350
Opencv4nodejs addon for cv::createLineSegmentDetector() function crashed. Exception can only be caught by catch(...). How to debug type of exception?
I am trying to make an integration of cv::LineSegmentDetector to opencv4nodejs which is an node addon of opencv (link: https://github.com/justadudewhohacks/opencv4nodejs). I have successfully complied an opencv4nodejs module which get loaded by require. Initially was facing problems of opencv_core.dll , and opencv_imgp...
As I understood there is no problem with my code the implementation is not present in version 3.4. LineSegmentDetectorImpl::LineSegmentDetectorImpl(int _refine, double _scale, double _sigma_scale, double _quant, double _ang_th, double _log_eps, double _density_th, int _n_bins) { CV_Assert(_scale > 0 && _sigma_scale ...
61,579,813
61,579,996
Stack behavior when adding new thread
What happens to stack when we create new thread? If it gets on the top of the stack, so how is it a thread?! If it doesn't get on the top of the thread, so how the program know where to continue it's job?
Each thread gets it's own stack. So if the initial thread creates a second thread, then this does not affect the stack of the first thread. And the second thread will have it's own stack. So in that process two independant stacks exist - one per thread. But each thread will only use it's own thread. The operating syste...
61,580,009
61,580,556
Control flow in a program that transforms a number using base 10
Here is a program that does a number transformation and I am trying to understand the control flow of this code. It's not really clear what the value of cn is in the first pass of the while loop, meaning if we declare cn = n at the beginning of the program, will the first value of cn be the first value of n or it will...
The assignment statement of "cn = n" is temporarily assigning the value of n to cn, before n is going to get modified inside the while loop. Here is the program with print statements added to illustrate how the values are getting changed: #include <iostream> using namespace std; int main() { int n, cn, x = 0, p ...
61,580,238
61,581,891
Why is the delete temp crashing even though the function is defined with new
I am making a modified double ended Linked List, but the head and the tail point to each other. In the insertBeforeCurrent and the insertAfterCurrent I defined the objects with new and put them into the Linked List. But when I go to use delete, the program just crashes. I have done some tests, and insertBeforeCurrent a...
I know you can only use the delete function for delete the data created by the new's dynamic memory allocation, So far so good. but that doesn't seem to be the case since every element of the Linked List is created by new. This is not relevant, since the temp in CircularDoublyLinkedList::remove() never points to an...
61,580,418
61,683,711
TDLib: how to send bold text in the message? (С++)
Using the official TDLib C++ example, I'm trying to send a message with formatted markdown text. Here's my code: auto send_message = td_api::make_object<td_api::sendMessage>(); send_message->chat_id_ = -1001424068198; auto message_content = td_api::make_object<td_api::inputMessageText>(); std::string text = "Hello! **...
You can use td_api::textParseModeMarkdown, td_api::parseTextEntities and td::Client::execute() like this: using namespace td; const std::string text = "*bold* _italic_ `code`"; auto textParseMarkdown = td_api::make_object<td_api::textParseModeMarkdown>( 2 ); auto parseTextEntities = td_api::make_object<td_api::parseT...
61,580,642
61,580,711
why is this function outputting a word multiple times instead of one?
#include <iostream> #include <string>//needed to make string array #include <fstream>//Needed for redaing in from external file #include <cstdlib>//needed for rand() function (for random word) #include <ctime>//needed for time() funtion to seed rand() using namespace std; void wordPick(); int main() { wordPick(); ...
Move this: srand(time(0)); string secretword = wordlist[rand() % 10]; cout<< secretword << endl; outside of your for loop, and remove the redundant call to srand(time(0)): for(int i = 0; i < 10; ++i) { inFile >> wordlist[i]; } string secretword = wordlist[rand() % 10]; cout<< secretword << endl;
61,580,754
61,581,007
Memory allocation error when attempting to print contents of a tree in C++
My problem probably has a simple solution that is staring me in the face, but so far I have been unable to find it. I am pretty new to C languages and this is the first program I have written in C++. I have a function create_complete_tree(int nr_child_nodes, int tree_depth) that makes a tree of depth int tree_depth in ...
Problem This code very probably infringes the rule of 3. The following statement: node child = (*this->get_child(i)); creates a clone of the node. If you didn't provide for the rule of 3, but implemented the destructor, the clone will use the same pointers to the same children than the original node. Unfortuna...
61,580,860
61,580,991
Storing heterogeanous class type in a variable
I'm a beginner with c++ :), I simplified my problem to this: I have a class Person class Person{ string name;} And another class Student that inherits Person class Student : public Person{ string schoolName;} And then I have a class Library that must have a different comportement depending on the input class ...
You can use dynamic_cast to cast downwards which will only succeed (i.e return a non nullptr value) if the runtime type is correct. Applied to your situation: void checkBeforeEntry(Person* p){ if (dynamic_cast<Student*>(p)) { std::cout << "You can enter" << std::endl; } else { std::cout << "Only s...
61,581,221
61,604,330
How to convert a string-type position to a Coord-type position?
In my work a txt file is read, among the data in it, there are geographical positions of the vehicles. Due to a problem I am having at the time of reading this file, I want to read this information as the string type, but I need to store the position information as the Coord type. Is it possible to convert a string to ...
First of all, sorry my poor English... When I need to read a string and convert to Coord, in VEINS + OMNeT simulator I do this: Coord MyClass::strToCoord(std::string coordStr){ //this 2 lines is will remove () if necessary coordStr.erase(remove(coordStr.begin(), coordStr.end(), '('), coordStr.end()); //remove '...
61,581,366
61,581,528
Program Gives An Error Every Time After Working Once
I'm attempting to implement my own array using pointers in C++. I'm using Visual Studio. I'm relatively new to C++, so if there is something obvious that I'm missing bear with me. But when I run it the first time, it works as intended. However, the next time I run it, I get one of two errors. One of the errors is Unabl...
Well you must be right! It is a memory issue and the error message "main.cpp has triggered a breakpoint" on windows indicates corruption of the heap in this case! I didn't have access to the hpp files you used apart from array.hpp Let's start with some memory issues that your code is making While initializing your ar...
61,581,657
61,581,767
c++ Setting equal_to as a default template argument for template class
How exactly are you supposed to set a generic class as a default template argument? I've managed to get non-generic classes to compile, but not generic ones. using namespace std; template <typename T, typename Cmp = std::equal_to<T> > class CSearch { public: CSearch(){ MComp = equal_to<T>(); } CSear...
This line of the error says what is wrong: error: no match for call to '(const std::equal_to<std::__cxx11::basic_string<char> >) (const char&, const char&)' You try to call an instance of std::equal_to<std::string> to compare two character, but std::equal_to<std::string> compares strings. You want std::equal_to< typen...
61,582,174
61,582,430
My template class's ctor takes a callable object as an argument but cannot be initialized from it?
I've been asked to implement a desktop calculator using std::function through a Function table for binary operators only. So I have this code: #include <functional> #include <iostream> #include <string> int main() { std::map<std::string, std::function<int(int, int)>> binOp; binOp["+"] = [](int a, int b){return...
You can use direct initialisation here to construct a BinOp directly: BinOp<std::string(std::string, std::string)> bstr {[](string s1, string s2){return s1 + s2;}}; The reason why your original code won't compile is likely because you are asking the compiler to perform two conversions, and that it won't do.
61,582,278
61,582,405
How to template a parameter in function pointer?
I have a template: template<typename T> void testFuction(int(*testFunc)(CallBack, void *, T *)) { // define CallBack callback, void* param1, T* param2 // ... testFunc(callback, param1, param2); } It works but it looks terrible, I want to do something like: template<typename T> // using TestFunc<T> = std::f...
You can provide a type alias for the templated function pointer as follows #include <utility> // std::forward template<typename T> using FunPointerT = int(*)(CallBack, void*, T*); template<typename T, typename... Args> void testFuction(FunPointerT<T> funcPtr, Args&& ...args) { // variadic args, in the case of pass...
61,582,379
61,582,928
Is my time-complexity paranoia in this case justified?
The documentation for an unordered_set says that 'Search, insertion, and removal have average constant-time complexity.' In the worst case, all of them degenerate to be linear in time. As against this, in case of a set, it says all the operations are Logarithmic in the size of the container (which IMHO alludes to a w...
I think, unless I want the elements to be sorted, it makes sense to always use a set over an unordered_set If you want elements sorted, then you cannot choose unordered set. If the order does not matter, then either may be an option. It mostly boils down to whether you care about worst case or average case performanc...
61,582,464
61,584,342
OpenGL rotating glRectf() function?
I'am working on a project which one my homework. I need rotate a car(not exactly but like a car this is not important I think). My car 2d. I create it with glReactf(); function. Because of I can create a rectangle with this function pixel by pixel. Like; // Create a rectangle (0,0) to (30,30) :) Like a square, yeap :)...
I solve it, how I did it I don't know, I am serious but it done. This is my display function; void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glRotatef(rotate_y, 0.0, 1.0, 0.0); glColor3f(1.0, 1.0, 1.0); glRectf(1, 1, 11, 11); glFlus...
61,582,517
61,582,617
How to display my templated vector of pairs? [solved]
#include <iostream> #include <ostream> #include <vector> using namespace std; template <class T> class Map { public: vector <pair <T, T>> x; void emptyMap(); insertPair(T, T); findKey(); eraseKey(); void display(); }; template <class T> Map<T>::insertPair (T key, T val){ // val = value x.p...
There is no overload for ostreaming a std::pair by default. Its fairly straight forward to write your own however: template<typename A, typename B> std::ostream& operator<<(std::ostream& os, const std::pair<A,B>& pair){ os << pair.first << ", " << pair.second; //one possible output format return os; }
61,582,601
61,583,062
Nested C Array Struct Alignment in Clang
I have a small memory problem in C++17 using Clang compiling for x64. Since I work with low level memory copies to specialized hardware, I do depend on the memory being aligned as expected. I have recently moved from Visual Studio to Clang and have encountered the following issue: See the below code: struct ContainerRo...
Quoting en.cppreference.com: The size of any object or member subobject [...] is required to be at least 1 even if the type is an empty class type (that is, a class or struct that has no non-static data members), in order to be able to guarantee that the addresses of distinct objects of the same type are alw...
61,582,641
61,988,869
How is ordering defined for UUIDs?
I am stuck in the following problem. I have two UUIDs const boost::uuids::uuid first = Helper::String2UUID("43E3F007-3993-4587-801E-D24C012587E4")); const boost::uuids::uuid second = Helper::String2UUID("652335C1-6479-4D6A-9599-25A671366E05")); In Boost I am getting this to be true. BOOST_REQUIRE(first < second); But...
There is no official ordering UUIDs since they are just an opaque string of 128 bits with no inherent meaning. Some applications may "helpfully" define them to be ordered, but since there is no official ordering to follow, they may make different decisions on how to do that. It may even vary between instances of the sa...
61,582,710
61,584,827
Counting the unique values in a binary search tree
I have a binary search tree. So far, I've been able to sort the tree using in-order traversal. My tree is a tree of strings being read from a file, and I want to count all the unique values within the tree (I need to use the duplicates for another part of the code, so I can't make a new tree with no duplicates and coun...
If you want to count unique content of binary tree then try this code this format void uniquecount(struct Node* node) { int count=0;//make this global to bring value out of function if (node == NULL) return; uniquecount(node->left); if(node->right!=NULL && node->right==node->data) count...
61,582,767
61,597,974
How to render images to /dev/video0 using v4l2loopback?
I've been trying to render images to /dev/video. I can get something to sort of display but it's somewhat scrambled. I first started off trying to render a normal RGB24 image (based off this example https://stackoverflow.com/a/44648382/3818491), but the result (below) was a scrambled image. #include <stdio.h> #include ...
After a lot of hacking around, I've managed to generate a valid YUYV video/image to send to /dev/video0. First I make a buffer to hold the frame: // Allocate buffer for the YUUV frame std::vector<uint8_t> buffer; buffer.resize(vid_format.fmt.pix.sizeimage); Then I write the current canvas to the buffer in YUYV format....
61,582,789
61,582,929
C++14: How can I use my template function with `iterator` and `const_iterator`
So I have these two functions which should make it more pleasant to check whether a key exists in a map: template<template <typename...> class Map, typename K, typename T> bool isEqualToEndOfMap(const typename Map<K, T>::iterator &it, const Map<K, T> &map) { return it == map.end(); } template<template <typename......
Couple of points: There is no need to for isEqualToEndOfMap to accept the iterator by reference. You may use a const_iterator as the argument type in isEqualToEndOfMap. An object of type iterator can be used in a call to the function. template<template <typename...> class Map, typename K, typename T> bool isEqualToEn...
61,582,906
61,583,011
H­ow d­oes List::in­sert w­ork with a­rr­a­ys­
I am on youtube looking over tutorials. One had a block of code using the list library as such: int arr1[5]{ 1,2,3,4,5 }; list<int> list1; list1.insert(list1.begin(), arr1, arr1 + 5); My question is, how can one use an array like this? Last I checked, arr1 is an array not a pointer that you use to loop through elemen...
When an array is used by name, it's name references to first element of the array. For an array arr whenever you say arr[x], [] is defined in terms of pointers. It means start at a pointer referencing arr and move x steps ahead. A size of each step is the sizeof datatype your array is made up of. Thus,arr[x] can also b...
61,582,985
61,583,466
OpenGL changing uniform changes previous draw
I have this sample code // EBO is just a rectangle // copypasted from learnopengl glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderId); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glUniform1f(glGetUniformLocation(shaderId, shiftName), 0); //shiftName is string "shift" glDrawEleme...
The actual source code triggering this issue was this: shader.Select(); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); shader.Set("shift", 0); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); shader.Set("shift", 0.5f); glDrawElements(GL_TRIANGLES, 6, GL_UNS...
61,584,042
61,584,150
c++: Is a multiple inheritance from template class and general class valid?
I'm trying to figure out why b->boo() actually calls a.far(). is the multiple inheritance from template class and general class forbidden? why does the inherit order matter? The code is here: #include <iostream> template <int somecount> class inner_parent_class { public: int array[somecount]; virtual void far(...
reinterpret_cast cannot be used to do what you're trying to do. A reinterpret_cast from a void* to a T* only produces a pointer to a valid T* if the void* pointer it was given was a pointer to an object of type T. Doing a dynamic_cast<void*>(p) returns a void* which points to the most-derived object pointed to by p. Si...
61,584,236
61,584,253
Why I get strange characters when looping an array on C++
This is my main function: string a[18] = { "1", " " ,"2", " ", "3", "\n", "4", " " ,"5", " ", "6", "\n", "7", " " ,"8", " ", "9", "\n" }; for (int x = 0; x <= 18; x++) { cout << a[x]; } and the output is something like this: 1 2 3 4 5 6 7 8 9 \�V�W(SV��8\�V������ Am I looping my array incorrectly? ...
If you have an array of 18 elements, the only valid indexes are 0 .. 17. You need to change the loop to: for (int x = 0; x < 18; ++xx) { cout << a[x]; } otherwise, you invoke undefined behaviour on the the last iteration of the loop, if you try to index a[18].
61,584,255
61,596,384
Is it possible to enforce, at compile time, that two derived classes would always return different values for an overriding function?
Is it possible to enforce, at compile time, that the following is acceptable: class B { public: virtual constexpr const char* getKeyStr() const = 0; }; class D1 : public B { public: constexpr const char* getKeyStr() const override { return "D1"; } }; class D2 : public B { public: constexpr const char* get...
If you can have a list of all Derived classes, you might do something like: template <typename... Ts> bool have_unique_keys() { std::string_view keys[] = {Ts{}.getKeyStr()...}; // requires constexpr default constructor // static method might be more appropriate ...
61,584,334
61,647,700
Dynamically linking with libstdc++ does not work when compiling with x86_64-w64-mingw32-cmake
I am cross-compiling a Windows 64-bit-only app from my Linux 64-bit machine. The Linux build build works flawlessly, but on windows the app crashes with "The procedure entry point ......basic_ostringstream......char_traits.... could not be located in the dynamic link library .... I am compiling and using many .dll fi...
Solved. For anyone else having this issue, make sure you are using the dll that comes from the same version of mingw than the one you are compiling with.
61,584,534
61,765,833
Error: (E112) get interface failed: port is not bound: port 'server.outgoin1' (sc_out)
I can't seem to figure out why I am getting the error. server.cpp #include "systemc.h" SC_MODULE(server){ sc_in<bool> begin1, begin2, begin3, end1, end2, end3, incoming1, incoming2, incoming3; sc_out<bool> free, outgoing1, outgoing2, outgoing3; void monitor(){ free = true; outgoing1 = false; outgo...
Deleting the executable file and recompiling the code helped me out.
61,584,655
61,589,110
How can I get my price vector to = values inside my json array
Hello I am pretty new to json parsing and parsing in general so I am wondering what is the best way I can assaign the correct values for the price of the underlying stock I am looking at. Below is an example of the code I am working with and comments next to them showing kinda what Im confused about Json::Value chartDa...
Hope I understood correctly (correct me if not) and you just want to save some subset of json data to your QVector. Just iterate through all json elements: for (int idx = 0; index < chartData.size(); ++idx) { time[idx] = convert2Timestamp(chartData[idx]["minute"]); price[idx] = convert2Price(chartData[idx]["high"],...
61,584,887
61,585,134
Can't figure out this stack output c++
So I have a stack example I created following a tutorial using the stack library stack<string> custs; custs.push("george"); custs.push("louie"); custs.push("florence"); // cout << "size" << custs.size() << endl; if (!custs.empty()) { for (int i = 0; i <= custs.size(); i++) { cout ...
Here is a step by step explanation of what is happening so you can understand it better: First, i starts as 0, and custs.size() returns 3. Since 0 <= 3 is true, the body of the loop executes, printing "florence" and removing it from the stack. On the second iteration, i equals 1, and custs.size() returns 2, because you...