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,362,157
64,363,491
Class template overload based on presense of non-type parameter?
I have a templated class that works as such: template <typename T, std::size_t maxSize> class Foo { std::array<T, maxSize> arr; }; I'd like to make an overload where you can choose to only pass T and instead get a vector as the underlying container: template <typename T> class Foo { std::vector<T> arr; }; W...
You can use a parameter pack for the size, and specialize on 1 argument or 0 arguments: First, provide a default that fails to compile template <typename T> struct always_false : std::false_type {}; template <typename T, std::size_t... Is> class Foo { static_assert(always_false<T>::value, "too many sizes"); }; Th...
64,362,720
64,362,744
initializing an object oriented array c++
I'm trying to write a program that simulates an ATM. The user can log in with a pin and account number, check their account balance, and make a withdrawal. I'm having trouble initializing the array that contains the account information, here's what I have so far: #include <iostream> #include <string> using namespace st...
You need curly braces around the entire initializer list, and also around the initializer for each element. Account account[]= { {123, "abc123", 100.00}, {456, "def456", 50.00}, {789,"ghi789", 500.63} };
64,362,915
64,363,298
Initailizing a char** in C++ in a class
I am trying to initialize a char** which will act as a two dimensional char array of size (board_size * board_size). However, I am having trouble filling the grid the character '-', when I get to that line I am getting exit code 11 which is a seg fault. How do I assign data to the dynamic 2d array. Is char ** the wrong...
If you want to do C-style arrays in C++, you need to manage them the same way as you do in C. So if you have a T**, that needs to point at an array of T*, each of which points at an array of T. In your case: this->board = new char*[board_size]; for(int i = 0; i < board_size; i++) { this->board[i] = ne...
64,363,147
64,363,423
GDB not finding symbol table
I cannot determine the reason that gdb is either not finding the proper debugging symbols or they are not being generated by my makefile. I have added and removed various flags such as -g, -ggdb, and -O0 in as many combinations as I can think of. Any help would be appreciated! Makefile: FLAGS =-std=c++11 -ggdb -g -O0...
OBJS = main.o LSorter.o LNode.o exec: $(OBJS) $(CC) $(FLAGS) -o exec $(OBJS) This specifies that the exec target depends on main.o, LSorter.o, and LNode.o targets. The make command then proceeds to search your Makefile for any rules to build main.o, Lsorter.o, and LNode.o. Unfortunately, make fails miserably in ...
64,364,005
64,364,432
Does C++ have a way to do Cuda style kernel templates, where parameters produce separate compilations?
In Cuda you can specify template parameters that are used to automatically create completely different versions of kernels. The catch is that you can only pass const values to the functions so that the compiler knows ahead of time exactly which versions of the kernel need to be created. For instance, you can have a tem...
Something like this? #include <iostream> template <int x> void function() { if constexpr (x == 1) { std::cout << "hello\n"; } else { std::cout << "world\n"; } } int main() { function<3>(); }
64,364,114
64,364,410
Infinite loop problem with the merge sort during the portion recursively calls mergeSort
Im working on a homework assignment comparing both execution time and theoretical O-notation of 10 separate sorts. However, as the question says I keep having an infinite loop when I get to the point that the code recursively calls merge sort. I know that it is when the left is at 2 and the right is at 3 so middle cont...
In mergeSort function, you forgot parenthesis when calculating middle. It should be: int middle = (left + (right - 1)) / 2; Also, in merge function, Left and Right should have type int[]. Instead of new int(SIZE), you should use new int[SIZE]. Moreover, you should use delete[] to delete them before leaving the functio...
64,364,145
64,364,186
I need help solve my problem of my activity
So I need my help to correct my code, which is given to my programming class assignment. My activity is to print numbers divisible by 5 for the integers from 1 to 99. So I tried to code like this: #include <iostream> using namespace std; int main () { int num, min, max; cout << "Enter Number: "; cin >> num; min = 1; m...
The input is an integer from 1 to 99, which means that it should be >= 1 AND <= 99. So, simply change if (num > min || num < max) to if (num >= min && num <= max)
64,364,632
64,364,822
How does the compiler determine what value to output during runtime when a function name is sent to cout without parenthesis? C++
#include <iostream> int returnFive() { return 5; } int main() { std::cout << returnFive << '\n'; return 0; } Since this compiles without error, how does the system determine what value is actually sent and printed to console?
Imagine if the code written is something like if(returnFive) returnFive(); Here the expectation is that the compiler checks if the function pointer for returnFive is nullptr or not. The compiler here is evaluating the function pointer as a boolean expression of whether it is NULL or not and printing the output. http...
64,364,722
68,345,465
Boost r-tree "correct" way to access objects
TLDR: is there a way to update object directly in a Boost r-tree (by setting the location class property to const, or something similar)? More info: I am using C++ Boost's R-tree to store objects with spatial coordinates (for reference, please see my previous question). For the sake of the discussion, let's assume my o...
No, it's not possible to store mutable values in the rtree right now. You could store the point and index in the rtree and then the rest of the data in a different container. It could be vector/deque if the index is preserved (you don't remove elements from the container) or map if you need sorting by key or unoredered...
64,364,964
64,365,546
ListView_GetItemPosition doesn't write to referenced pointer
I'm trying to get the position of icons on the desktop (will ultimately be trying to move them). ListView_GetItemCount() returns the number of desktop icons successfully, so I know I have the correct window handle. However, ListView_GetItemPosition() doesn't write to iconPos. int numberOfIcons = ListView_GetItemCount(...
The desktop ListView you are accessing exists in a different process than your app. The POINT object you give to ListView_GetItemPosition() must be allocated in the address space of the same process that owns the ListView. You can use VirtualAllocEx() for that allocation, then request the position using that memory, th...
64,365,575
64,365,863
How to CMake compile a library as part of my app's source and not as static/shared library?
I'd like to be able to debug my app at the same time as the library(ies) with VSCode and CLion using CMake. . +-- lib | +-- CMakeLists.txt | +-- lib.c | +-- lib.h +-- app | +-- CMakeLists.txt | +-- app.c | +-- app.h As an example, let's say I want to compile my app with the {fmt} library as part of the sou...
I think that cmake's add_subdirectory (https://cmake.org/cmake/help/latest/command/add_subdirectory.html) does exactly what you need. It will include library's CMakeLists.txt to your project and you will be free to use its targets in functions like target_link_libraries. Simple example: Let's assume that you checked ou...
64,365,821
64,367,412
c_str() returns nothing, but string not empty
So, I have a class class MySuperClass { public: std::string buffer; }; And wants to print buffer to std::cout. Here's some code about filling string from a file: MySuperClass msc; std::fstream file("./favicon.ico", std::fstream::in | std::fstream::binary); if (file.is_open()) { std::stringstream ss; while (!file.eo...
An ICO file starts with 2 zero bytes so buffer.c_str() points to an empty string. As a result printing it shows nothing. If you print the byte values you'll immediately see why for (const auto c: buffer) std::cout << std::setfill('0') << std::setw(2) << std::hex << +c << ' '; OTOH std::string can contain embedded ...
64,366,216
64,368,233
Get the size of a directory (not its content)
(please before dismissing this as already answered, read the full question) In C++ we can get the file size of a regular file by running std::filesystem::file_size(PATH); But this function does not work on directories, which is my problem. I am in a situation where I need to know the size of directory "inode", in (most...
https://en.cppreference.com/w/cpp/filesystem/file_size For a regular file p, returns the size determined as if by reading the st_size member of the structure obtained by POSIX stat (symlinks are followed) The result of attempting to determine the size of a directory (as well as any other file that is not a regular fil...
64,366,481
64,394,466
CUDA C++ read image from host and copy to device
I need read a image and store it into a unsigned char array and use the array to construct a class. The class construction is device function. so I need read the image and copy to device. The code is similar to below. __global__ void print_copy_result(unsigned char **tdt) { if (threadIdx.x == 0 && blockIdx.x =...
As indicated in the comments, &d_texture_data is a pointer to host memory (not managed memory, but host memory). Such a pointer to host memory is essentially unusable by CUDA device code (CUDA kernel code cannot dereference such host memory pointers, except in some cases on Power9 platforms). You don't need that level...
64,367,019
64,367,187
why is list initialization not invoked when initialize this class?
according to value initialization described in this page https://en.cppreference.com/w/cpp/language/value_initialization If T is a class type that has no default constructor but has a constructor taking std::initializer_list, list-initialization is performed. so I was expecting when initialize the class in bellow cod...
Myclass does have a default constructor; which is just marked as delete explicitly. So the effect of value-initialization should be: if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized; In default-initialization the deleted defau...
64,367,057
64,367,370
C++ - printing objects in statistically allocated array causes segmentation fault
So I'm creating a program that implements several classes representing a school, and its students and courses. I'm getting a segmentation fault when I try to prints out all the Taken objects in the studentCoursePairs[] array which represents Student objects taking a particular Course. I think my segmentation fault come...
Your School object has two major problems. Let us start with the one you posted in your question: void School::printTaken(){ cout << name << " === TAKEN: "<< endl; for(int i = 0; i < sizeof(studentCoursePairs)/sizeof(studentCoursePairs[0]); ++i){ studentCoursePairs[i]->print(); //seg fault } } T...
64,367,496
64,367,745
variadic template struct, recursive type declaration, is it possible?
there! There is any way to declare a type recursively? I was almost there but I got a compile error. I'm designing a simple template to determine the optimal type for storing the result of operating mixed type stuff. OP_T<> Use case example: typename OP_T<char, float, int>::M var //var is actually a float Code templat...
I guess you meant something like this: template <typename T0, typename... Ts> struct OP_T<T0, Ts...> { using M = typename OP_T<T0, typename OP_T<Ts...>::M>::M; }; Now OP_T<T1, T2, ...>::M will be a type obtained from the pack T1, T2, ... by the application of the "reduction" binary metafunction x_traits<S, T>::MUL...
64,367,820
64,367,908
Temporary object created in case of an object declared and then assigned
I have a user defined class Fixed, with a default constructor, a parameter constructor and an assignment operator. When I declare an object and then assign it: Fixed a; a = Fixed( param ); I get: call to default constructor (line 1) call to parameter constructor (line 2) call to assignment operator (line 2) call to d...
Is a temporary object created ? Yes. The expression Fixed( param ) will create a temporary object. This temporary object will then be passed to the assignment operator of the a object. The statement a = Fixed( param ); is somewhat equivalent to { Fixed temporary_object( param ); a.operator=( temporary_object...
64,367,839
64,367,989
How Do I Get a subvector from a vector?
How do i access 1,2,10 from the below vector? D = [[1, 2, 10], [2, 3, 20], [2, 5, 25]] int i=B[i][0]-1; int j <= B[i][1]-1; Was Solving a Problem, I Had to use them in a for loop to check for the answer. Can Anyone help me out
Are you looking for this? #include <iostream> #include <vector> int main() { std::vector<std::vector<int>> d = { {1, 2, 10}, {2, 3, 20}, {2, 5, 25} }; auto subvector = d[0]; for (auto& value : subvector) { std::cout << value << ' '; } std::cout << "\n"; // or (poor solution) for (int i = 0; i <...
64,368,714
64,369,645
C++ Do-while loop doesn't work as i expected
int main() { int a; //virknes skaitlis int N; //skaitlis int count = 0; int sum = 0; double average; int ok; do { cout << "Ievadiet, cik skaitļu būs virknē: " << endl; cin >> a; for (int i = 0; i < a; i++) { cout << "Ievadiet veselu skaitli: " << endl; ...
I believe my amendments to your code would smooth things out: #include<iostream> using namespace std; int main() { int a; //virknes skaitlis int N; //skaitlis int count = 0; int sum = 0; double average; int ok; do { count = 0; sum = 0; cout << endl << endl << "Ieva...
64,369,300
64,369,387
How to return multiples variables from a function in c++
string choices() { string ch1 = "1",ch2 = "2",ch3 = "3",ch4 = "4",ch5 = "5",ch6 = "6",ch7 = "7",ch8 = "8",ch9 = "9"; return ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9; } void display(string a,string b,string c,string d,string e,string f,string g,string h,string i) { cout << a << b << c << d << e << f << g << h <<...
Use tuple and structured bindings: auto choices() { std::string ch1 = "1",ch2 = "2",ch3 = "3",ch4 = "4",ch5 = "5",ch6 = "6",ch7 = "7",ch8 = "8",ch9 = "9"; return std::tuple {ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9}; } auto [a,b,c,d,e,f,g,h,i] = choices();
64,369,527
64,372,258
Is there a way to initialize a const static field from another const static field in a different class?
I'm trying to initialize the state of my static const field from (a part of) the state of another const static field from a different class in a different file. In a simplified example: // object.h class Object { public: Object(std::string s) : s(s) {} private: std::string s; }; // a.h #include "object.h" c...
From C++17 onwards, you can use inline member variables - in the class declarations - in the respective header files. This avoids the need for definitions of those members in individual source files, thus avoiding any ambiguities related to the order of evaluation of different translation units. Also, in the example yo...
64,369,616
64,369,818
Android application only in C++
Is it possible to make an Android application only in C++? I don't know Java. I've tried Visual Studio 2019 approach but I guess my computer isn't good enough for emulating Android phone.
You can write code for Android in C++, if you have the appropriate programming tools. You'll need a cross-compiler and linker for the appropriate architecture. These are readily available in Google's Native Development Kit: https://developer.android.com/ndk/ I don't know if these tools can be used with Visual Studio --...
64,369,680
64,372,078
Readling a line and using the next lines information c++
I am new to c++ and I need help when reading and changing lines from an input file to use the next lines and saving it into another output file. I have an example of a single DNA sequence stored in .fastq format, with the following structure. @Read_1 AGACUUUACGCT + ++//187-,/02 So each DNA sequence has four lines wort...
I think you could make your task much easier overall by reading in the full fastq fragment first, then split it into multiple fragments, and then finally output it all again. If you make a struct for the fragment and add input and output operators (operator>> and operator<<) for it, then you can do the reading and writ...
64,369,997
64,370,111
Create an array inside a lambda capture
Lambda captures allow us to create new variables, e.g: auto l = [x = 10]() { }; I know this also works for std::array but what about C style arrays? To be clear, I don't want to copy or reference an array here. I want to create a new one inside the capture clause.
It can't work as currently specified for C style arrays. For one, the capture syntax doesn't allow for declarators to compound types. I.e. the following are invalid as a capture *x = whatever x[] = whatever (*x)() = whatever So we can't "help dictate" how the captured variable's type is supposed to be determined. The ...
64,370,396
64,370,735
DFS of a graph using vector
I want to implement the adjacency list rep of graph using vectors, and I was using a program meant for implementing adjacency list using linked list as a guide, and I'm unable to do so. Here's my tried code upto now: #include <bits/stdc++.h> using namespace std; class graph{ int v; vector<int> *adj; void DF...
There were a few errors in initialization: #include <bits/stdc++.h> using namespace std; class graph{ int v; vector<int> *adj; void DFSutil(int v, bool visited[]){ visited[v]=true; cout<<v<<" "; vector<int>::iterator i; for(i=adj[v].begin();i!=adj[v].end();++i){ i...
64,370,481
64,384,844
Problem with compiling DLL (CURL library) (Visual Studio)
I have a problem with compiling DLL in C++. I am using CURL library for HTTP POST. When I compile my code as Console App, I do not get compile errors. But that same code gets Unresolved external symbol errors. Lines like: curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); curl_easy_setopt(...); curl_mime...
Problem was in #define CURL_STATICLIB order. Corect order is: #include "pch.h" #define CURL_STATICLIB #include "CURL/curl.h" Thank you all for help.
64,370,621
64,370,727
How to calculate time complexitiy?
I'm really having trouble calculating big O. I get the basics but when it gets to nested for loops and all that, my mind just blanks out. I was asked to write down the complexity of the following algorithm which I have no clue how to do. The input string contains only A,B,C and D string solution(string &S) { int le...
It is O(n^2). DDDDDDDDDDDDDDDDDDDABABABABABABABABABABABAB First n/2 characters are D Last n/2 characters are AB For each AB, (there are 1/4n such) - O(n) You are resetting i (iterating from start) shifting all successive elements to fill the gap created after erase. Total: O(n)*(O(n) + O(n)) = O(n^2)
64,370,965
64,371,608
Template argument deduction for constrained parameter (bitset size) fails
Is there a way to make the compiler deduce the parameter size_t L using a constrained by concepts template argument? That's the best I got template <typename T, size_t L> concept def_bitset = std::is_same<T, std::bitset<L>>::value; template<size_t L> void stamp(def_bitset<L> auto const &b) { std::cout << b << std:...
Concepts exist to check constraints on template arguments. A concept is not a type, despite appearing in the same location as a type can when employing terse notation. It doesn't carry any type information that can be used for template argument deduction. To illustrate it, let's rewrite your terse function template def...
64,371,274
64,371,386
how to enable C++11 or C++14 in Dev C++ IDE
I'm trying to compile this on Dev C++ IDE, but it's showing this error : error This file requires compiler and library support for the ISO C-+ 2011 standard. This support is currently experi Ical, and it be emblem with the -stdest or -stdagno 11 compiler options
Follow these Steps in DevC++. Got to Tools -> Compiler Options... -> Settings -> Code Generation In language standard(std), choose -> ISO C++11 more https://www.geeksforgeeks.org/how-to-fix-auto-keyword-error-in-dev-cpp/
64,371,515
64,371,891
Instantiating template struct inside template function
This is my code and I'm trying to understand why it won't compile struct Base {}; template <typename T> struct Derived : Base {}; Then in some class template <typename S> void SomeClass::SomeMethod() { Derived<S>* ptr; //ok ptr = new Derived<S>(); //Compiler error C2760 on Visual Studio 2019 } Is ther...
Well, it compiled for me, by putting the whole stuff into a single file and defining the function inside the class.
64,371,563
64,375,838
How to keep a pointer to a CUDA Texture object generated in a C dll called from .NET?
I have a C dll that uses CUDA to perform operations on a CUDA texture object. I am repeatedly calling the C dll from C# managed code using the same data for the texture. The time taken to transfer the data for the texture object onto the GPU is significantly longer than the time taken to perform the actual processing. ...
I have found a solution which appears to work (thanks Robert for your comment above). Because the dll itself exists in memory inbetween the function calls from managed code (I didn't know this originally), I simply declared two static variables in the C dll:- static cudaTextureObject_t TexureVariable; static cudaArray*...
64,371,588
64,371,656
Why is the difference between behaviors in for loop?
I am confused by getting the different results after executing the same loops after one another. The first loop Increments the different way and second is completely different. Results: 1 , 1 1 , 2 1 , 3 2 , 1 2 , 2 2 , 3 3 , 1 3 , 2 3 , 3 Code: #include <iostream> using namespace std; int main() { for(int outerv...
You have a nested loop here. For each iteration of the outer loop, the inner loop is completed. The output is hence to be expected. If you want to tear these loops apart, you can do so by for(int innerval {1}; innerval <= 3; innerval++) cout << innerval << '\n'; for(int outerval {1}; outerval <= 3; outerval++) ...
64,371,808
64,372,264
Non-constexpr variant member call compiling inside constexpr class member function with condition - why?
#include <variant> struct S { constexpr auto f() -> void { // deleting the next line creates an error if(std::holds_alternative<int>(m_var)) m_var.emplace<double>(5.0); } std::variant<int, double> m_var; }; int main() { return 0; } std::variant has a non-constexpr member ...
You don't actually need to delve much into std::variant to reason about this. This is mostly about how constant expressions work. constexpr functions must be defined in a way that allows for evaluation in a constant expression. It doesn't matter if for some arguments we run into something that can't appear in a constan...
64,372,079
64,372,322
How to iterate over two containers sequentially
I have two vectors. I want to iterate over all elements of both and do something (say print them out). So I could write something like: vector<int> vec_a{1, 2, 3}, vec_b{4, 5, 6, 7}; for (auto a : vec_a) { cout << a; } for (auto b : vec_b) { cout << b; } This has a lot of duplication. I could do something like: f...
A simple solution is to use a helper function: #include <functional> template <typename Func, typename... Containers> void for_all(Func&& func, Containers&&... containers) { auto iteration_func = [&](auto&& container) { for (auto&& elem : std::forward<decltype(container)>(container)) { std::inv...
64,372,352
64,374,661
C++ Replace even number of zeros in an array with only two zeros
My program should replace the group with an even number of zeros, which go in a row, with two zeros and group with an odd number of zeros replace with only one zero. If the input has no zeroes, it should be left as is. I've written following code to solve this problem. #include <iostream> #include <vector> #include <...
I have altered the structure of your program (inserted a counter count_zeroes in place of auxiliary vector temp_arr), but this should work as intended: #include <iostream> #include <vector> using namespace std; int main() { int n; cout << "Enter an array size:\n"; cout << "n = "; cin >> n; vector<...
64,372,362
64,373,953
c++ nested class getter and setter does not work
I'm making a pokemon battle code. Here are codes that I've made. First, I define Pokemon class. (pokemon.h) class Pokemon{ ... private: int hp; public: int gethp(); void sethp(int n); ...} (pokemon.cpp) ... int Pokemon::gethp(){return hp;} void Pokemon::sethp(int n){hp = n;} ... Next, I define Trainer...
me.getpokemon(1).sethp(80) Let's walk through this--you're calling me.getpokemon(1), which returns a copy of a Pokemon from me's pokemons array. You then call sethp on the copy, setting its hp to 80. And then, since the copy isn't saved anywhere, you never see it again until it's destroyed... What you want instead, i...
64,373,304
64,374,815
First Makefile Questions: No rule to make target
I'm attempting to create my first ever Makefile and looking for the most simple, understandable version--even if it isn't "good practice." I'll deal with that at a later time. :) Basically, I just want to run make in the command line and have it execute the several g++ commands so I don't have to. For example, instead ...
As a first step, you need to make sure your recipes produce their target and that inputs are either files or targets of other rules: bin/RaspPi4Main: src/RaspPi4Main.o src/funcI2cCom/funcI2cCom.o g++ -o bin/RaspPi4Main src/RaspPi4Main.o src/funcI2cCom/funcI2cCom.o -lwiringPi src/RaspPi4Main.o: src/RaspPi4Main.cpp...
64,373,574
64,373,791
C++ How to return array of objects from a function
recently I have started learning c++, so I'm trying to make a simple grade calculator using my base knowledge (I'm already good with Javascript so i know the basics of programming). So in this case, I had to return an array of objects from a function call so i can use it later in the program, but I just couldn't find t...
Use std::vector: #include <iostream> #include <vector> using namespace std; // the Subject class class Subject { public: string name; float grade; int factor; Subject(){}; Subject(string x, float y, int z){ name = x; grade = y; ...
64,373,632
64,373,778
General-purpose clear function for stack<ItemType>
Is there a way to write a general-purpose function to clear any stack in C++ with any given item type? I am currently writing a program that uses a string stack and an integer stack but I cannot figure out how to pass the stack as a parameter that decides during runtime which data it contains and how to delete it. My i...
You can template your function with the same argument as the stack you pass in e.g.: template<typename T> void clearStack(std::stack<T>& s) { while (!s.empty()){ s.pop(); } } You then don't need to explicitly specify the template argument, the compiler can infer it from the stack type: std::stack<int> ...
64,373,644
64,378,110
Why can I use CMake supplied modules (CMakeDependentOption.cmake specifically) locally, but not on CI or Docker?
I have a cmake project that successfully builds locally but errors with include could not find load file: CmakeDependentOption when trying to build on a CI platform or in Docker. Note that CMakeDependentOption.cmake is a script that comes with cmake itself. So it should just be available. On CI to install cmak...
You can locally because most likely you don't use a linux based platform, like windows or mac. This is because linux filesystem are case sensitive. Which means CmakeDependentOption is different from CMakeDependentOption. Docker runs containers in linux, so filenames are gonna be case sensitive, and the include is going...
64,373,735
64,390,943
How might I build a templated functions that compiles differently if a template int is odd or even?
class Whatever { public: // doThing overloads: template <typename T> inline static T doThing(T t, float n) { /* It's a SmoothStartN function in my code, but don't worry about the specifics. Includes a for loop up to n times (result gets interpolated between n...
Answer: Thanks to Quentin's suggestion, I believe a good solution looks something like this: template <unsigned int n, typename T> inline static T doMoreComplexThing(T t1, T t2) { if constexpr((n % 2u) == 0u) { unsigned int halfN = n / 2u; return (doThing<halfN>(t1) * doThing<halfN>(t2)); } ...
64,373,874
64,373,982
Safe way to unpack integer values from a remote device
I get bytes from a remote device via USB protocol. These bytes contain integer data. Is the following code a safe way to unpack them without portability issues (except endianess which is known): #include <iostream> #include <string> #include <cstdint> #include <cstring> int main() { std::uint8_t someArray[4] = {1,0,...
Yes. std::memcpy is indeed the way to go. In real-life code, I'd static_assert on the size of types used and check data size at run-time, but nothing more.
64,373,991
64,374,508
How pass string from C++ native to C# Unity?
I found such answer on SO https://stackoverflow.com/a/42987032/5709159 And there is my implementation C# Unity [DllImport(m_pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr /* char const * */ get_profiling_info(IntPtr native_stream_ptr); string foo(){ string pro...
result goes out of scope. Then, the pointer returned from c_str() is no longer valid. A quick fix is to use a static string: static std::string result = ... But a more robust solution involves allocation/deallocation of a temporary char buffer. Or perhaps returning m_prof_txt directly? Not sure what that variable is th...
64,374,152
64,374,499
Define field with macro, but Field cannot have type 'void' and/or Expected ')'
Trying to simplify writing boiler plate, but I get Field cannot have type 'void' and / or Expected ')' Newbie c++, I've seen a bunch questions like this, but still can't figure it out. The errors are still too cryptic to me to able to google them.. #define GAME_STAT(Stat) \ UPROPERTY(BlueprintReadOnly, Category = "...
## is for pasting tokens together, but it looks like you think it is "reverse stringification". It's also a binary operator, not an "around-ary" operator. That is, #define hello(x) Hello_##x hello(World) will produce Hello_World This should work (but is thoroughly untested): #define GAME_STAT(Stat) \ UPROPERTY(Bl...
64,374,233
64,385,236
VCPKG Pcl: Cannot open include file: 'pcl/io/vtk_lib_io.h': No such file or directory
I am trying to compile a project using Point Cloud Library (PCL) on Windows 10 using Visual Studio 2019. I installed the PCL library via vcpkg (latest version 2020.07) both the pcl and pcl[vtk] version. Vcpkg is connected to my program through its vcpkg integrate install function. I am using the dynamic build in releas...
The visualization module in PCL is currently disabled within vcpkg since PCL currently does not support VTK 9. You either have to use overlay ports to install VTK 8.2 or update PCL to use the PR adding support for VTK 9
64,374,526
64,375,340
Is is necessary to use volatile when writing to hardware in C or C++?
Is it necessary to use volatile when writing to hardware (say a FIFO) in C or C++. It is easy to confirm from online documentation that volatile is necessary when reading hardware, but what about writing? I am concerned that an optimiser could eliminate a loop to write an array of values to a FIFO, and just write the l...
Just try it. #define MYFIFOV (*((volatile unsigned char *)0x1000000)) #define MYFIFO (*((unsigned char *)0x1000000)) void funv ( void ) { MYFIFOV=0; MYFIFOV=0; } void fun ( void ) { MYFIFO=0; MYFIFO=0; } 00000000 <funv>: 0: e3a03401 mov r3, #16777216 ; 0x1000000 4: e3a02000 mov r2, #0...
64,374,589
64,375,250
Using std::decay with std::forward
template<typename T> struct test { std::string key; T value; template<typename U> using decay = typename std::decay<U>::type; template<typename U = decay<T>, typename US = decay<std::string>> test(U&& _value, US&& _key) : value(std::forward<U>(_value)), key(std::forward<US>(_key)){} }; I ...
You overthink this. You need just this: template<typename T> struct test { std::string key; T value; // as a safety this could be replaced by: // typename std::decay<T>::type value; template<typename U, typename US> test(U&& _value, US&& _key) : value(std::forward<U>(_value)) , ke...
64,374,667
64,374,998
Check If N and Its Double Exist
This is from one of the problems in the tutorials at leetcode, it asks: Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). Here's my attempted solution: class Solution { public: bool checkIfExist(vector<int>& arr) { for(int i = 0; i <...
We can also use a std::unordered_map for solving this problem: // The following block might slightly improve the execution time; // Can be removed; static const auto __optimize__ = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return 0; }(); // Most of headers ...
64,375,206
64,378,190
Git Diff defining incorrect hunk header for cpp file
I am using git diff to find out which methods have changed. Evidently its defining the hunk header incorrectly (as shown below) due to which I am not able to find a way to get the list of changed methods. @@ -22,7 +22,7 @@ void func2(){ void func1(){ cout<<"Function 1"<<endl; - int i=100...
The issue here is that this diff is in function func2. Note that the diff begins with a blank line, followed by the definition of function func1. This definition is inside the diff-hunk, so the diff-hunk begins before the function. Presumably, above the blank line we'll find more of the code of func2. That's the con...
64,375,299
64,375,396
YAML file found, but unable to parse content
I'm trying to parse a YAML configuration file using yaml-cpp (https://github.com/jbeder/yaml-cpp), Visual Studio 2019 Community. #include <iostream> #include "yaml-cpp/yaml.h" int main(int argc, char* argv[]) { YAML::Node config; try { YAML::Node config = YAML::LoadFile("conf.yml"); } catc...
You have variable shadowing: YAML::Node config; // This is the config you print out at the end try { // The below config is local to the narrow try-scope, shadowing the // config you declared above. YAML::Node config = YAML::LoadFile("conf.yml"); } Correction: YAML::Node config; try { config = YAML::...
64,375,741
64,378,656
Make a String Variable a Class Name in C++
I'm working on a program in C++ to make schedules for me, since I have a hard time focusing on school work. The code will make priorities of assignments based on the due dates, duration to do the assignments, etc. Anyway, I've run into a massive problem. I'm trying to assign a class variable's name to a variable! For e...
What you are looking for is an array of Assignment objects, eg: int main() { Assignment *assignments; int assignmentAmount; int userInput1; int userInput2; string userInput3; cout << "Enter assignment amount: "; cin >> assignmentAmount << "\n" << endl; assignments = new Assignment[assignmentAmount]; ...
64,376,003
64,376,216
Are Variables in C++ implicitly pointers
Am having a hard time trying to figure this out. When we type in c++ int a = 4; It is clear that the memory manager allocates 4 bytes to hold the value 4 and keeps that value in a specific address.. Giving the fact that "a" variable is just a name. Where is the variable "a" stored? Does it store it somewhere in memor...
Are Variables in C++ implicitly pointers No. Variables are not implicitly pointers. Where is the variable "a" stored? Somewhere (or nowhere) in memory. Allocation of memory for variables is responsibility of the language implementation. Does it store it somewhere in memory Yes (or nowhere). and points to the mem...
64,376,079
64,376,152
Why is the list shown Empty?
I am trying to get the data already assigned in the list, and if the data is <= -1 then the list must be shown as empty, otherwise print the assigned data. But, the problem is that my code prints the list is empty. I think it should print [ +2 ] instead of an empty list. Code: #include <iostream> #include <vector> usin...
std::vector::size() returns an unsigned integer (because the size of a vector can never be negative, and if it returned a signed integer it couldn't refer to as large a range of sizes). When you compare a signed integer (like -1) with an unsigned integer, the signed integer is converted to unsigned for the comparison. ...
64,376,172
64,390,964
Is it correct to use std::chrono::steady_clock time across the system?
I have a file with header time as std::chrono::steady_clock parameter. The different server will be writing them on the disk. During the usage of file, I will be comparing them to find the latest time. I am confused with https://en.cppreference.com/w/cpp/chrono/steady_clock Updates: Q: Whether the comparison provides m...
Q: Whether the comparison provides me the latest file or not? Answer: With reference to link shared above: "This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals." It does not seem appropriate for time stamping in a file. For example...
64,376,208
64,378,491
C++: Method into another method
I'm new to C++, so please don't be harsh on me. This is my header, cblock.hpp: #ifndef CBLOCK_H #define CBLOCK_H #include "ctime.hpp" #include <iostream> class CBlock { public: CBlock(); CBlock(short m_BlockNr,CTime m_Begin); short getBlockNr(); void print() const; void getEnd(); ~CBlock(){}; ...
It certainly is possible! The trouble is that your print() function is const, which means it can only access its class in a const way. getEnd() is not const, so print() can't call it. It's a bit weird for something called "get" to actually set; perhaps you'd like to return a fresh value from that function instead? You ...
64,376,214
64,378,886
How QT signals with parameters works
can someone tell me how exactly signals with parameters work? I mean... if i have declared signal f.e.: void sign1(int) how should i specify what integer i want to send with that signal? Also, can i declare signal with multiple arguments? Like: void sign2(int, int) And again... i want to send with sign2 two out of fo...
QObject::connect() works like this (in the general case, not using lambda): connect(obj1, obj1_signal, obj2, ob2_slot) Since there is no signal clicked(int, int) in the class QPushButton (which I assume you are using), it cannot be use for the connection. If you want to have the signal clicked(int, int) in a button, y...
64,376,547
64,376,781
Redefine this C++ variable
This variable keeps saying it's undefined, which is fine. But how do I redefine it? I need to redefine this variable. #include <iostream> using namespace std; int main() { string b1 = "undefined"; cout << "Schedule\n"; string p1; cin >> p1; if (p1 == "1") { string b1 = "ELA"; } else if ...
You cannot redefine variable, that's simply not possible in C++. Good news is, you don't need to. As the name "variable" suggests, you can change it: #include <iostream> using namespace std; int main() { string b1 = "undefined"; cout << "Schedule\n"; string p1; cin >> p1; if (p1 == "1") { b...
64,376,590
64,376,815
C++ idiomatic way of iterating over a container that itself is being modified
I find myself iterating over a container X that is being modified inside the loop. But in each iteration, the unmodified X is needed: for (int x : X) { // wrong, container X in iteration should be the "original" modify_X(); // X modified here } A solution is to iterate over a copy containerT X_copy(X); for (int x...
The last example in your question looks the simplest. However, from C++20, you could also do this: for (auto copy = X; int i : copy) { modify_X(); } Here's a demo. Note that in your first snippet, it's not only logically wrong, but it also invokes undefined behavior, as you are modifying a range that you're iteratin...
64,377,213
64,377,558
Is there an alternative to the 'system()' command in C++.?
I have read a lot of answers saying that the system() command is bad. First off, why is it so bad? Second off, is there an alternative that doesn't produce such a security hole? I mostly want to know if there is a way to clear screen in C++. In python I have a clear function that checks the os name and runs either syst...
system functions (across many language, including Python and C++) are not inherently "bad" but they present difficulties for correct use. Security You need to be absolutely sure that whatever you're executing via system is secure. If you write system("echo hello " + name) then you need to be absolutely sure that name c...
64,377,415
64,378,101
I have a list of world points(XYZ) and I want to show them in a openGL window
my points in x are between 0.25 and 1.21 , my points in y are between 3 and 4 and my points in z are between 99 and 101. here is my vertex shader #version 330 core // Input vertex data, different for all executions of this shader. layout(location = 0) in vec3 vertexPosition_modelspace; layout(location = 1) in vec3 vert...
You don't look towards your point cloud. The first argument of glm::lookAt is the position of the camera and the second argument is the point you are looking at. Hence the direction of the view is (0, 0, 0) - (4, 3, 3) = (-4, -3, 3). If the points are in range x: [0.25, 1.21], y: [3, 4], z: [99, 101]. The line of sight...
64,377,929
64,378,022
C++ - How can i split up 3 lines safed in string called "result" and create a oneline "synonym" for all 3 strings. - C++
So, Hello Guys. I have a function, which reads the Diskdrive Serialnumber. I get a output like this: SerialNumber A6PZD6FA 1938B00A49382 0000000000000 (thats not my serialnumber, just the format) So now, i want to split the 3 numbers, or strings, however i call it you know what i mean, and save it in in three indepen...
If you have the original text in a string variable, you can use a std::istringstream to parse it into constituent parts: std::string s = "SerialNumber A6PZ etc etc..."; std::istringstream iss{s}; std::string ignore, a, b, c; if (iss >> ignore >> a >> b >> c) { std::string synonym = a + b + c; ...do whatever wit...
64,378,572
64,378,658
"No match for operator>>" but I don't understand why. Could you explain me, please?
I have got the following code: #include <iostream> #include <vector> using namespace std; vector<int> Reversed(const vector<int>& v){ //vector<int> v; //[Error] declaration of 'std::vector<int> v' shadows a parameter int z; vector<int> copy; vector<int> working; working = v; z = working.size(); ...
It looks like you are asking the user to enter a list of numbers. std::cin (or just cin, since you've got use namespace std;) doesn't know how to receive a list of integers and turn that into a vector<int> for you. If you want to receive a vector from user input, I would suggest you ask the user for a list of numbers,...
64,378,577
64,380,293
What exactly are the positioning rules for text in Qt?
Here's a very basic piece of code which: Measures the size a piece of text would take. Draws the rectangle which corresponds to this size at coordinates (100, 25). Displays text at coordinates (100, 25). auto str = "Hello, World!"; auto metrix = window->fontMetrics(); auto text = scene->addText(str); text->setPos(100...
Solution Setting the document margins to 0, as @NgocMinhNguyen suggested, might seem to work, but it is not a real solution, because you lose the margins. It would be better, if you could get the actual geometry, including margins etc. For that purpose you can use QGraphicsTextItem::boundingRect() instead of QFontMetri...
64,379,202
64,379,816
How to rotate an QGraphicsPixmapItem in Qt
I am trying to rotate an image in Qt. If you try this game, you can easily see how the arrow is rotating: https://www.friv.com/z/games/killcovid19/game.html?Desktop-x-x-w-x-x-xx Assuming my image is in a QGraphicsPixmapItem, how should I make it rotate?
First, you need to set the rotation point (bottom-right/left in your case) void QGraphicsItem::setTransformOriginPoint(qreal x, qreal y) And then perform a rotation around the transform point void QGraphicsItem::setRotation(qreal angle)
64,379,833
64,379,973
delete abstract non virtual dtor c++
I have an interface that represent Abstract Data Type 'Bag'. To implement that abstract data type i used Array based and Linked based implementation. Here the definition of class edit As you indicated, i've added virtual destructor to my Base class template<class ItemType> class BagInterface{ public: virtual int g...
Right now, when you run this code : delete bagPtr; the destructor from the link based implementation isn't called. template<class ItemType> class BagInterface{ public: ..... virtual ~BagInterface() = default; }; You need this destructor if you are going to delete a class derived from BagInterface through a pointer t...
64,379,876
64,379,983
Giving an erroneous answer for my if statement
The problem is my code is giving a wrong answer when the user inputs less than 40 hours worked .It is supposed to use the statement (max_Minimum_Pay = hours_Worked * MINIMUM_PAY_RATE)but instead it looks like its skipping over that and multiplying 0.10 * sales amount? //Declaring variables// double hours_Worked; ...
It looks like you want all the lines after the else to be executed only in case hours_Worked > OVERTIME_THRESHOLD here: if (hours_Worked <= OVERTIME_THRESHOLD) max_Minimum_Pay = hours_Worked * MINIMUM_PAY_RATE; else reg_Minimum_Pay = OVERTIME_THRESHOLD * MINIMUM_PAY_RATE; ov...
64,380,162
64,403,810
list.cc: No such file or directory
When I try to run following code I get a segmentation fault: #include <iostream> #include <list> #include <vector> using namespace std; class HashTable { private: vector<list<pair<string,string>>> values; int cap; int r = 31; public: HashTable(int capacity) { cap = ...
Jerry Coffin has solved this problem: At first glance, it looks like you really want resize where you've called reserve. That may not fix all your problems, but it at least provides a reasonable explanation for what you're currently seeing. I changed values.reserve to values reserve.resize
64,380,241
64,380,410
C++ table with names of data types
I would like to implement a table that will consist of some names of data types so that I will be able use them in loop to cout my function. How to do it? I have already tried with the table that is in my code but it doesn't work. Probably it's something with pointers. #include <iostream> #include <limits> #include <...
I think you are taking a terrible route in doing what you're doing. You should probably refer to Boost.TypeIndex library instead. Look at this: #include <iostream> #include <boost/type_index.hpp> class Widget { }; int main() { Widget w1; Widget& w2 = w1; Widget const w3; Widget const& w4 = w1; std...
64,380,492
64,380,835
When should you use CrtAllocator vs MemoryPoolAllocator in RapidJSON?
I know that the CrtAllocator is the C runtime allocator and uses malloc/realloc/free, and I know that the MemoryPoolAllocator is the default allocator and allocates memory sequentially. I don't understand why the MemoryPoolAllocator is considered more efficient than the CrtAllocator. Does the MemoryPoolAllocator just d...
If you're simply grabbing a huge block of memory once and implementing your own memory pooling, just use the crtAllocator. Otherwise use the MemoryPoolAllocator which effectively borrows memory from the system and subdivides it as and when required. Using a memory pool means that when a memory grab request is made, yo...
64,380,654
64,381,117
I was wondering if its possible to check what an if statement evaluates to before stepping into it using debugger visual studio code
I have this C code that I was working on and honestly I do not understand how it exactly works (I never used if statements like this before). Here is the code: #include<stdio.h> int main(int argc, char const *argv[]) { int x = 2, y = 0; if (x = ++y) { printf("%d is equal to %d\n", x,y); } else { prin...
Here is a semantic fix of your code: #include<stdio.h> int main(int argc, char const *argv[]) { int x = 2, y = 0; if (x = ++y) { printf("y has been incremented and copied to x, which is now non-zero\n"); } else { printf("y has been incremented and copied to x, which is now zero\n"); } } and #incl...
64,380,786
68,117,493
SecByteBlock to ECDSA<ECP, SHA256>::PublicKey and reverse in CryptoPP
As the title says is there a way to transform a Key in SecByteBlock to ECDSA<ECP, SHA256>::PublicKey and the reverse? From what I have read I just managed to transform PublicKey to strin using: PubicKey pubKey; string s; StringSink ss(s); pubKey.Save(ss);
//To string string encoded; // Pretty print key encoded.clear(); StringSource(key, key.size(), true, new HexEncoder( new StringSink(encoded) ) // HexEncoder ); // StringSource PublicKey string_to_publicKey(strin...
64,380,888
64,391,005
Extracting all words separated by non-alphabetical characters
Given a string such as: std::string word = "Hello World!it's@.-/sunday"; I want to extract all the words which are separated by non-alphabetical letters stored in a container like a vector, so for this case it would be: Hello, World, it, s, sunday My initial try was to use isalpha() along with an index count to subs...
You can try the following code. It constructs the words char by char. #include <string> #include <iostream> #include <vector> int main() { std::string phrase = "Hello World!it's@.-/sunday"; std::vector<std::string> words; std::string tmp; for (const char &c:phrase) { if (isalpha(c)) { ...
64,380,911
64,383,378
Issue with trying to create a thread
I am attempting to make a function that takes in an std::function and a vector of values and will return a vector which contains the functions output for these values, and makes use of threading in order to speed it up. When I compile my code it is saying that it is unable to specialize the function template for std::i...
According to cppreference for std::thread: The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g., with std::ref or std::cref). Think what would happen if you started a thread with a reference and the object was ...
64,381,415
64,381,587
Why can't you use relaxed atomic operations to synchronize memory, if there is a thread join in between?
I'm watching this Herb Sutter talk: https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-2-of-2 Looking at two examples (around 1:15 mark), one makes sense to me and the other does not. First example (makes sense): Note count is an atomic int. Here, using relaxed memory ordering for...
Around 1:17:25, he says "now, because you happen to know I've got a release-acquire by joining the threads, I've injected a release-acquire in there; that may be good enough and you can just go to relaxed". So he seems to be saying, in the end, that it's actually fine if dirty is accessed with relaxed memory ordering.
64,382,077
64,385,397
How to dynamically create multiple threads with multiple corresponding classes for solving many sudoku puzzles
My task is to write a multi threaded program that solves a set of sudoku puzzles by dynamically determining the maximum number of threads that can run on the machine, then allocate that many threads to grab single puzzles from the file with all the sudoku puzzles. Something like: we have determined that 8 threads can r...
To address your question directly (ie. not helping you with the logic of solving the puzzle, but just helping you with allocating and managing threads to methods), this is a minimalistic example of how to set up objects to do some work on different threads: #include <iostream> #include <random> #include <thread> struc...
64,382,598
64,383,575
How can I tell compiler there is some struct not defined but will?
#include<vector> struct EDGE { VERTEX* from; VERTEX* to; int weight; }; struct VERTEX { std::vector<EDGE*> edges; }; struct MAP{ std::vector<VERTEX> vertex; bool directed{ false }; }map; I want to make class with these data. How can I use undefined class but will be define?
What you need is a technique called forward declaration. The code would look like this: #include<vector> // forward declaration of VERTEX struct VERTEX; struct EDGE { VERTEX* from; VERTEX* to; int weight; }; // actual definition of VERTEX struct VERTEX { std::vector<EDGE*> edges; }; struct MAP{ ...
64,382,603
64,386,178
Qt error involving moc files not fixed by cleaning project
What is the code I am trying to learn Qt c++ with the book learn Qt 5. This is the follow along code. The particular section that is giving the error is for writing a preset welcome message. The Qml code uses the Q_PROPERTY macro in the header file to access this function. This is the function definition in the actual ...
As we see in https://doc.qt.io/qt-5/properties.html Q_PROPERTY have to have (READ getFunction [WRITE setFunction] or MEMBER memberName [(READ getFunction | WRITE setFunction)]) You are trying to use both parts of this code. Also : A MEMBER variable association is required if no READ accessor function is specified. T...
64,382,666
64,383,483
How to echo input within a void function and do-while loop C++
I need some advice on how to echo the input from the user. A bit of background on the program that this is needed first. I created this program so that it asks the user how many values they would like to enter and then they enter the number in positive integers. Then the program computes to figure out if the numbers ar...
I believe that this much code will be sufficient : #include <algorithm> #include <iostream> #include <iterator> #include <vector> int main() { std::size_t n; std::cout << "Enter number of elements : "; std::cin >> n; std::vector<int> v(n); std::cout << "Enter the numbers now : "; for (auto &i ...
64,382,708
64,382,892
C++17 pointer array to a std::any of tuple
I am writing a function that stores a parameter pack into a std::any of tuple, and I need to allocate a pointer array void* arguments[] to each item of the tuple. How can I do that at compile time? template <typename... ArgsT> void func(ArgsT&&... args) { // any will be the storage for the argument std::any any = s...
Full example including test cases with a few minor changes (e.g., static in func) to help with testing/lifetime issues, but I think I hit your requirements. #include <any> #include <iostream> #include <string> #include <tuple> namespace { namespace detail { template <std::size_t INDEX, typename ...Ts> ...
64,383,062
64,384,991
Compiling SQLite amalgamation file with C++ file using minGW-w64
I'm just beginning to experiment with C/C++ and SQLite, and installed the minGW-w64 compiler and was able to get the little "Hello, world." code to compile to an .exe file and run it. Then I added the sqlite3.c amalgamation file to the directory and attempted to compile it with the helloworld.c file, and the first resu...
Yes, bundling sqlite like that is intended behavior. You can compile sqlite3.c with a C compiler first and link the result into a binary: gcc -O2 -c sqlite3.c g++ -O2 sqlite3.o myapp.cpp -o myapp.exe I strongly suggest automating this project with a simple makefile or Cmake.
64,383,157
64,383,272
it is a binary search code and i m not able to figure out the problem
Here is my code.The code is running but not getting the right results. For ex- searching 3 in the program is getting output "not found" even though present. #include<stdlib.h> #include<iostream> using namespace std; int Bsearch(int arr[],int item,int n) { int low,mid,up; low=0;up=n-1; while(low<=up && item!=arr[mi...
Here is the problem: if(item==arr[mid]) return mid; else if(item<arr[mid]) low=mid+1; else up=mid-1; just change the conditon of choosing low and up index according the value of mid index arr[mid] like: if(item==arr[mid]) return mid; else if(item<arr[mid]) up=mid-1; else ...
64,383,455
64,383,725
Is there a shorthand way to print a different variable if one variable is empty in C++?
I'm trying to write a minified FizzBuzz program in C++ as I am just now learning it. I wondering if there's a shorthand way to say "If this string exists, return this string, otherwise, return this next part" In JavaScript, using the || operator works the way I'm thinking of: function fizzbuzz() { const maxNum = 20...
In C++, you can just use a ternary operator. Ternary operators work like this (very similar to ternary in JavaScript): condition ? "truthy-return" : "falsey-return" ^ A boolean ^ what to return ^ what to return condition if the condition if the condition is truthy is falsey Th...
64,383,493
64,383,814
Returning the local reference versus local variable of the reference-returning-function
I know that for the functions that returns the reference, it is an undefined-behavior to return the reference of the local variable. For example, int& test(int a) { return a; } Compiler will emit <source>: In function 'int& test(int)': <source>:4:9: warning: reference to local variable 'a' returned [-Wreturn-loca...
But surprisingly, if I define the reference inside of the function and returns it, compiler does not complain anymore. I guess the big question here is: what compiler? Doing a quick test with g++ (9.2), I get: trash9.cpp: In function 'int& test(int)': trash9.cpp:3:12: warning: function returns address of local variab...
64,384,404
64,384,692
How can I ask GCC to use a different standard library?
I have a debug version of libstdc++ 6 in /usr/lib/debug/usr/lib/x86_64-linux-gnu/. I would like to tell gcc/g++ to use this library instead of the standard library version without debug symbols. I tried using -nostdlib and passing the library path explicitly with -L, but get linking errors such as /usr/bin/ld: CMakeFil...
You should make use of LD_LIBRARY_PATH environment variable like: export LD_LIBRARY_PATH=/usr/lib/debug/usr/lib/x86_64-linux-gnu/ This variable can be used to change the dynamic linkers search paths so, instead of searching for libstdc++ in the system's library paths, libstdc++ will be searched along LD_LIBRARY_PATH.
64,384,496
64,384,651
autotools, stdc++fs, false positive
I am trying to conditionally use std::filesystem if it's available. Check for header file works, via AM_CHECK_HEADERS first, then AC_TRY_COMPILE (the latter due to some combinations of Xcode/OSX having the header, but firing static assert on actual acompilatilon). Should all those checks pass, HAVE_FILESYSTEM is set. H...
Your test only declares a variable that is not being used. Therefore, the test program is not calling any function from std::filesystem, thus it will always pass the linking stage. You are also using AC_TRY_LINK, which is an obsolete macro, prefer using AC_LINK_IFELSE instead. Last, it seems like the variable you set i...
64,384,600
64,384,836
How does this allocator play the role of debugging?
When I read the source code of SGI/STL, I notice that template <class _Alloc> class debug_alloc { private: enum {_S_extra = 8}; // Size of space used to store size. Note // that this must be large enough to preserve // alignment. public: static void* allocate(si...
This allocator uses an 8-byte header in front of every allocation to record its size. It is common to store metadata like this next to the actual allocation. Even though the header contains a 4-byte int, 8 bytes ensure that the returned pointer is aligned to 8 bytes, a common requirement for larger types.. As you can ...
64,384,912
64,389,791
Problem with installing Shark machine learning library
I am Installing Shark machine learning library in my Laptop which its config is : CPU: CoreI7 10th generation GPU: Radeon RX640 OS: Windows 10 IDE: Visual studio 2019 according to shark website help, Boost library must be installed before any action . I got the Boost library boost_1_74_0-msvc-14.2-64 from its boost w...
Boost is a collection of libraries. Some must be built, others are header-only (just #include). Visual Studio is common enough that Boost provides a link to pre-built libraries. You downloaded the correct MSVC 14.2 build for VS2019. Since Boost is a collection of libraries, sometimes library A needs library B. CMake kn...
64,384,982
64,385,040
class declaration in C++
I have a Class : class RTC_EXPORT PeerConnectionInterface : public rtc::RefCountInterface { ... }; RTC_EXPORT is defined as #ifndef RTC_BASE_SYSTEM_RTC_EXPORT_H_ #define RTC_BASE_SYSTEM_RTC_EXPORT_H_ // RTC_EXPORT is used to mark symbols as exported or imported when WebRTC is // built or used as a shared library. // W...
The macros is defined in your snippet: #ifdef WEBRTC_LIBRARY_IMPL #define RTC_EXPORT __declspec(dllexport) #else #define RTC_EXPORT __declspec(dllimport) #endif That allows to use the same class declaration for both dynamic library and the caller code. The dllexport and dllimport storage-class attributes are Micros...
64,385,021
64,385,119
Wrong output after removing character from string
I have the following code to remove all vowels in a string: #include <iostream> #include <string> using namespace std; bool checkVowels(char s); int main() { string s; cin >> s; for (int i = 0; i < s.size(); i++) { if (checkVowels(s[i])) ...
I think that checking and modifying the string while iterating on its size might be the problem here. After each erase, the string indexes/character are "moved" down, so when the next loop iteration start, the next character is not checked. Might want to use a temporary string to hold "non vowel" characters, but it mig...
64,385,129
64,385,387
How can I use a function to write LCD text? - Arduino
I'm trying to create a sort of number picker. It'll show you 0 to 9 and using an X, which I will write over the number you can choose a number. As an example 01234567x9 or 0123x56789. I'm struggling however with printing this to an LCD. I'm using a tinkercad so all of my pin connections are predefined and pretty much c...
Seeing your code, you have a global char array that holds what is going to be written, and PrintText() will take its input from there: char lcdtxt[] = "0123456789 x"; void PrintText(){ lcd.print(lcdtxt); lcd.clear(); } void loop() { PrintText(lcdtxt); } So, PrintText() won't take any arguments, and you're ...
64,385,206
64,385,481
How to Initialize all Variables in the program to zero without doing it explicitly in c++
I want to make all the variables which I create in my program to have initialization to zero without doing it explicitly. For example suppose if I create a variable like below: int i; We know that it must contain any garbage value and to make it have value 0 by default we need to declare it like int i=0; but I want m...
Default initialization and some words regarding the complexity of initialization in C++ To limit the scope of this discussion, let T be any kind of type (fundamental such as int, class types, aggregate as well as non-aggregate), and the t be a variable of automatic storage duration: int main() { T t; // default in...
64,385,568
64,385,824
C++ Adjacency List Representation of Graphs
What is an efficient way to implement Adjacency List Representation of Graph in C++? vector *edges; list *edges; map<int, int> *edges; map<int, map<int, int>> edges; In my opinion, it should be option 3 or 4, but I could not find any cons in using that... Are there any? Can someone please help me, which will be the m...
What is an efficient way to implement Adjacency List Representation of Graph in C++ Many typical graph problems apply to a given static graph that will need to be represented once whereafter the given representation can be re-used whilst solving the related problem. In this case, std::unordered_map<int, std::vector<i...
64,385,825
64,385,904
Qt correct unowned QObject return semantic
I have a QObject SystemdDBusManager that can return other QObjects (Unit class). Those objects do not have any reason to be owned by SystemdDBusManager, but according to the Qt documentation, this can imply that the returned object is owned by SystemdDBusManager. class SystemdDBusManager : public QObject { Q_OBJECT pu...
You can return a shared pointer or a unique pointer to the Unit object, depending on how you are going to use the object. That way, the caller will not have to care about the lifetime of the pointer.
64,385,837
64,385,976
"expression must have class type" but when checking the type it does have a class of char?
I was just doing a simple coding challenge for c++ as I am relatively new to the language, I wanted to compare two strings to each other lexicographically, so as to print out 1 if the first string entered was lexicographically bigger than the second one, and to print out -1 if the opposite was true. As I was looping, I...
It's because first_str[i] is a char. Char doesn't have a .tolower() method. So instead of: first_str[i].tolower() you should use: tolower(first_str[i])
64,385,916
64,412,199
How to rotate an object always tangent to a circular path?
I recently started to learn computer graphics and I need some help. I'm trying to reproduce a rotation of a "stick" around a circular path in a way that the stick is always tangent to the path. I provided an image to help to illustrate the desired behaviour: I tried some approaches but never in a successful way. Below...
I could reproduce the behaviour I wanted by translating the Z coordinate of the stick instead of the X: //small cube as reference XMMATRIX mScale = XMMatrixScaling(0.1f, 0.1f, 0.1f); g_World1 = mScale; //stick rotating around the small cube XMMATRIX mScale2 = XMMatrixScaling(3.0f, 0.3f, 0.3f); XMMATRIX mOrbit2 = X...
64,386,016
64,386,230
Any satisfying iterator recursion to replace a for loop of the type $a[i]=b[i]*c[i]$
I am attempting to make my code more readable and avoiding for loops with indices, as iterators are more flexible. fictive data time a b 0 6 7 0.5 2 1.5 1.0 9 3 1.5 0 2 now in order to calculate the vector c I would normally introduc...
If you want readability use STL algorithms: // Initialise result vector vector<double> c(a.size()); // Iterate through a & b and push the result of the binary func into c std::transform(a.cbegin(), a.cend(), b.cbegin(), c.begin(), std::multiplies<>{}); Godbolt link
64,386,138
64,386,459
How does memory allocation work and when does it happen?
I'm new to C++ and I'm trying to understand memory allocation. I want to know if the memory is allocated during runtime or after the code gets compiled, and when runtime starts, my operating system will already know that I need X memory to run the program. If the memory is allocated during runtime, then what is the poi...
I need to know if the memory is allocated during runtime or after the code gets compiled... It's at runtime, hence the name dynamic. ...and when runtime starts, my operating system will already know that I need x memory to run the program... No, the memory is allocated at runtime, the system can't know how much wil...
64,386,363
64,438,579
Subset a Variadic template given a constexpr boolean selection function
Suppose we have a variadic templated class like template<class...Ts> class X{ template<size_t I> constexpr bool shouldSelect(); std::tuple<TransformedTs...> mResults; // this is want I want eventually }; where the implementation of shouldSelect is not provided, but what it does is that, given an index i referring to ...
If you're able to use C++17, this is pretty easy to implement using a combination of if constexpr and expression folding. Start with some helper types, one with parameters to track the arguments to X::shouldSelect<I>(), and the other with a type to test. template <typename T, size_t I, typename...Ts> struct Accumulator...
64,386,996
64,400,811
Cannot compile: error: expected primary-expression before '(' token
I cannot get this compile: // main.cpp #include <boost/multi_index_container.hpp> #include <boost/multi_index/composite_key.hpp> #include <boost/multi_index/indexed_by.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/tag.hpp> using namespace boos...
You need to put a couple of templates here: template<typename FromArgs, typename ToArgs> std::pair<attr_iterator, attr_iterator> fetch_range(FromArgs&& from, ToArgs&& to) const { return std::pair<attr_iterator, attr_iterator>( _container.template get<by_attrs>().lower_bound(from), _contain...