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,897,735 | 61,899,817 | Pass in vs assign const reference in C++ | const string& x = functionA();
functionB(x); // depends on x is string or const string&
string str = x;
We have const ref x:
Pass into functionB, so basically we make a copy of the value of x and pass into functionB? (No, depends on x is reference or not)
Assign x to str, so here we also make a copy of value of x? O... |
Calling 'functionB' with 'x' we are just passing that value, which this reference holds.
By the way, references behave closely to pointers.
It's similar to have:
void func(int val);
int a = 11;
int *ptr = &a;
func(*ptr); // same as functionB(x);
So whether you will pass it by copy or not is really ... |
61,897,991 | 61,898,290 | Is there a way to call a function with different number of variables? | I would like to design a way to call one of many very similar functions - where the only difference is the number of arguments. Bare in mind this is a minimal example of my larger issue. I have lots of functions for doing different tasks. Each function prototype is very similar - except they have a different number of ... | Pass the vector itself to the wrapper lambdas, and let them extract the int values to pass along to their target functions, eg:
#include <vector>
#include <map>
#include <functional>
#include <iostream>
#include <stdexcept>
enum class test_type {t0, t1, t2, t3, t4, tn};
class tester
{
public:
void run(test_type t... |
61,898,077 | 61,898,221 | I want to declare a pyramid like structure in C++ in a particular way but cannot | I am essentially trying to declare something like this but I am unable to because of "too many initializer variables".
int** a = { {1},{2,3},{3,4,5} };
As a side question, if this were to work with some slight modification would it have the size of 9 (3x3) or 6 (1+2+3)?
I can implement this behavior with vectors such ... | Using a double pointer in C++ statically has a different memory arrangement than using new dynamically. The difference is that a static ** takes continuous memory automatically at compile time, where a dynamic one will not. Static multidimensional arrays are stored continuously, as discussed here.
Related: my question ... |
61,898,086 | 61,898,474 | Class template with array or vector arguments | I need to write a class template definition with two template parameters (type , functor) and two template arguments (array/std::vector , int) that can execute the following code:
const char* message= "Message";
const transform<char, firstFunctor> first(message, lengthOfMessage);
transform_view<int, secon... | you wrote the definition of the constructor incorrectly.
transform<A, B>(A[], B) {...}; you will pass a vector, so why did you write A[] as a parameter type?
You need something like the following
#include <iostream>
template <typename T>
struct functor{
void operator()(const T array [], size_t sze) {
for (... |
61,898,230 | 61,970,094 | Using Rcpp to expose a constructor that takes a pointer to an object as a parameter | I have the following very simple code that defines a class B that takes as a parameter a pointer to an object of class A.
The code works perfectly if I compile it as standalone C++, but I haven't been able to expose class B using Rcpp. I must be doing something wrong in the line .constructor<A>() near the end. Have t... | Let's try to be stubborn: Your constructor for B expects a reference to an A, so we should expose it as such, i.e. .constructor<A&>(). Doing so I get the error
invalid user-defined conversion from ‘SEXP’ {aka ‘SEXPREC*’} to ‘A&’
Basically we want to create something that's callable within R (the constructor for B), ... |
61,898,434 | 61,918,537 | How to print students name in ascending according to marks | I had sort the mark for all tests, quizzes, assignments and final exam in ASCENDING order. But I don't know how to display all student's name in ascending order based on their mark for each tests, quizzes, assignments and final exam.
Below are my code to sort each mark for tests, quizzes, assignments and final exam in ... | #include <iostream>
#include <string>
using namespace std;
//global constant
const int NUM_STUDENTS=5;//row
const int NUM_SCORES=4;//col
string name[5]={"Hani","Haziq","Aiman","Farah","Sabrina"};
string mark[4]={"test","quiz","assignment","final exam"};
struct student {
};
//Function prototypes
void ascenDescen(dou... |
61,898,608 | 61,899,413 | pass shared_ptr i.e. shared_from_this() as a void* | In a C++ class, I am trying to use shared_ptr, but instead of using this I am trying to use shared_from_this(). In the constructor, I am trying to create an object of a struct which expects a void*. I am not sure how I can convert a shared_ptr to a void* which can be passed as the parameters to the struct which is ex... | You cannot call shared_from_this in a contructor. You also don't need to because what you wanted was void*. this implicitly converts to void*. You don't need access to the shared pointer in the first place.
This is very simple:
A(): mCobj{5, this} {
Note that if you make a copy of A, then the copy will point to the ob... |
61,898,686 | 61,900,062 | Why when i try to print a map content i get the adresses not the value ? in c++ | I have a class Servicii that is empty and 2 classes Car and Book(I will use later for renting more types of services) that extends this class. Also I have another class Person .
After that I declared a map std::map<Person*,Servicii*> servicii; and this function:
template<class T>
void rentService(Person *p,T service)
{... | Direct answer:
Since your map's key value pairs are pointers and the pointers are addresses which point to a address, when you are printing pointers you get a hexadecimal value which represent the address of the pointer
Recommendation:
If you want to print customized information , what you can do is overload << opera... |
61,899,292 | 62,176,419 | IncrediBuild - Error: First character of string should be '0' or '1' | Update: This issue is in a C++ (non-cli) project. Unfortunately, there is no error info other than what was presented to me via the IDE. I was required to upgrade my IDE from VS2017 to VS2019; when importing a project from VS2017 everything was fine until I tried to do a build. I received the following error/build fai... | This can also be fixed by forcing IncrediBuild to use MSBuild. You can do this by adding a registry key in Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Xoreax\IncrediBuild\Builder called UseMSBuild and setting it to 1.
|
61,899,299 | 61,899,548 | What happens at the "Primitive assembly" stage in OpenGL | I'm little bit confused when read graphics pipeline about primitive assembly. In documentation says, that
Primitive assembly is the process of collecting a run of vertex data output from the prior stages and composing it into a sequence of primitives. The type of primitive the user rendered with determines how this pr... | There are different types of primitives, and each stage can take different types of primitives as inputs, and produce different types of primitives as outputs.
The tesselation evaluation shader takes patches as input. So you cannot put normal primitive assembly before the tesselation evaluation shader, since primitive... |
61,899,651 | 61,907,530 | Filtering directories displayed in a QFileDialog | I have an existing QFileDialog using the getExistingDirectory method that I'm trying to modify to filter out certain directories. Right now, all directories at the target location are shown, but I'm going to have a list/array of directory names that I need to filter for (ie: I want to show only these directories, not o... | Have you checked if setting a name filter on the QFileDialog will work?
https://doc.qt.io/qt-5/qfiledialog.html#setNameFilter
Something like:
auto dialog = QFileDialog(parent, tr("Select Training"), library, "dir1;dir2");
dialog.setFileMode(QFileDialog::Directory);
dialog.setOption(QFileDialog::ShowDirsOnly | QFileDial... |
61,899,709 | 61,901,096 | struct nested in union nested in struct in C | I want to demonstrate an employee class who can have two types of payments; salaried or hourly. Based on user input, the employee's pay type is defined and I use one of the sructs in the union. I wrote this code for it:
struct Employee {
int Id;
char Dept;
int Age;
char PayClass;
union PayType
{... | Yes your way of accessing the MonthlyRate is acceptable but if you want a cleaner way, you should use a mutator/setter.
I have also inserted a condition which will check if the MonthlyRate is positive or not.
#include <iostream>
using namespace std;
struct Employee {
int Id;
char Dept;
... |
61,899,917 | 61,899,977 | extracting a template parameter pack with different types into a vector of doubles produces warnings | I am trying to convert a load of classes that are basically the same but take different number of parameters into a single template class. So I have create a template class example (not real code - just for example):
// The template type
template<typename... Args>
class tester_template
{
public:
void process(Args..... | Yes, you can cast the arguments easily:
std::vector<double> args_vect = {static_cast<double>(args)...};
and there are no warnings emitted.
Here's a demo.
As pointed out in the comments by @NathanOliver, if you just want to print all the variadic arguments, you could do:
void process(Args... args)
{
((std::cout << a... |
61,900,391 | 61,900,421 | Trouble coming up with a solution to a circular reference in C++ | I have two base classes, valuationFunction and SimulationEngine where I believe I have created a circular reference that I'm not sure how to sort out. Originally I only had SimulationEngine include ValuationFunction, but then I created the enum RiskFactor in SimulationEngine that I need ValuationFunction to recognize, ... | Create RiskFactor.h. Stick the enum in there. Include it in both headers.
|
61,900,458 | 61,900,480 | Wrong class function is being called | I have a class called Smartphone that defines a few variables and functions:
class Smartphone : public Computer {
int contactNum = 0;
string contacts[15];
int contactIndex = 0;
public:
void call();
void text();
void addContact();
void InitalizeContacts();
void increaseContactNum();
} Mo... | Your if condition is incorrect, it needs to be:
if (userAction == "Call" || userAction == "call") {
// ...
You've made the same mistake in another if condition. Again, it needs to be:
if (userAction == "Text" || userAction == "text") {
// ...
|
61,900,668 | 61,901,766 | C++ Expression tree traversal to change expression to NNF in place | I want to transform an expression into negation normal form. For this, I have a binary expression tree using smart pointers. The problem is that removing double negations is not working when they occur in binary expressions although the function removeDoubleNot() is called at the right time. So e.g. ¬(A∨¬B) becomes ¬A∧... | When you call evaluate(ret->getLeft()) you are not using the return value, thus you never change your current child expressions.
So you need to change this to:
ret->setLeft(evaluate(ret->getLeft()));
The same goes for right.
You might want to consider using [[nodiscard]] to get compiler warnings on mistakes like these... |
61,900,966 | 61,901,066 | Pointers for Member Functions | I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I want to use a pointer for the array. How do I go about doing that. Should the pointer be initialized in int main or the class. Any suggestions appreciated.
#include <... | equip is a very large object. About 14 gigabytes in fact.
Automatic variables such as equip rocket are allocated on the execution stack. The default size of the execution stack on most desktop systems is about 1 to few megabytes.
A 14 gigabyte object will most definitely overflow a 1 megabyte stack.
Solution: Always us... |
61,901,302 | 61,901,543 | sscanf() with two string parameters | I want to create the command /kick playername reason in C++, so I tried it:
if (IPlayer.IsOnline() && IPlayer.GetAdmin() >= 3
&& sscanf(command, "/kick %[a-z | A-Z | 0-9/<>|.,~*;`:!'^+%&/()=?_-£#${[]}€] %[a-z | A-Z | 0-9/<>|.,~*;`:!'^+%&/()=?_-£#${[]}€]",
&playername, &reasonkick) == 2)
But nothing happens... | sscanf() does not support regular expressions. The way you are using the %[] placeholder is indeed wrong syntax. Try this instead:
if (IPlayer.IsOnline() &&
(IPlayer.GetAdmin() >= 3) &&
(sscanf(command, "/kick %N[^ ] %Ms", playername, reasonkick) == 2))
{
...
}
Where N and M are the max widths of the playe... |
61,901,610 | 61,901,688 | couldn't deduce template parameter ‘U | I have a following function I want to use:
template <typename T>
template <typename U>
TypedData<U>* convert(T min, T max) const;
Here's how I used it in the code:
const TypedData<unsigned short>* B = A->convert((float)0,(float)65535);
where A is the following type:
const TypedData<float>*
The complier gives me t... | You need to provide the U template parameter to convert as well:
const TypedData<unsigned short>* B =
A->convert<unsigned short>((float)0,(float)65535);
Note that this means you can avoid specifying the template parameter on the left hand side:
const auto* B =
A->convert<unsigned short>((float)0,(float)65535... |
61,901,659 | 61,902,233 | Errors in Hackerrank compare the triplets code | I was doing the hackerrank triplet sum question and I found these errors but I dont know why these errors are coming. Can someone please give a little more insight about it and if possible link a video about the topics I should read in order to atleast get the code correct.
The code
#include <iostream>
using namespace ... | These first two errors occur because the compiler thinks you're trying to redefine the arrays a and b, which you've already initialized the at the beginning of main. When you call compareTrip() , you just need to pass in the names of those arrays as the two arguments.
The error control reaches end of non-void function... |
61,902,050 | 61,902,238 | Why is my array being passed with an incorrect size? | I am just starting to learn C++ and I was playing around with functions. I am trying to pass an integer array as a parameter, and have the function print every element of the array. My issue however is that I have an array initialized to a seize of 10, but when I pass it to the function it only reads it as a size of 2.... | When an array is passed by value it is implicitly converted to pointer to its first element.
On the other hand a function parameter declared as having an array type is adjusted by the compiler to pointer to the array element type.
So for example these function declarations
void Max(int Arr[]);
void Max(int Arr[1])
void... |
61,902,070 | 61,903,172 | C++ comparing a string to a word | I'm trying to build an program that takes a word input from user and then converts it to a number for the system to work off.
int FunctionName(string WordInput)
{
int ReferenceNumber;
if (WordInput.find("Specific Word"))
{
return ReferenceNumber = 0;
}
else if (WordInput.find("Spe... |
if (WordInput.find("Specific Word"))
std::string::find() returns a value of type size_t. It gives you the position of the search term in the string. If the search string isn't found it returns string::npos.
Instead of a long list of if and else if statements, you could use a map here. The lookup will be faster, and... |
61,902,097 | 61,902,258 | using libraries with the same defines in one file | I have a project in which I want to use both grpc and ncurses and I stumbled across a strange error
I have a function
grpc::Status test(){
...
return grpc::Status::OK;
}
which works fine without ncurses, however if I add
#include <ncurses.h>
The whole thing breaks with this error
src/main.cc:32:26: error: ex... | Seems like you can just #undef it.
|
61,902,140 | 61,902,196 | c++ run a loop for several unordered maps | I'm a C# coder, but I need to fix something in older c++ code. I have 3 unordered maps, and a for loop that needs to run over each map. I don't want to repeat the loop code 3 times, obviously. In c++, how do I assign references to each map, ony by one, and run the loop (so that changes to the maps persist)?
std::unorde... | You might do:
for (auto* m : {&m_A, &m_B, &m_C}) {
for (/*const*/ auto& p : *m) {
// ...
}
}
|
61,902,240 | 61,930,914 | how do i fix the qt extension for visual studio? | i have installed qt for open source users and the qt extension for visual studio code. At first I was able to create projects but they will not match the real paths to the corresponding libraries / header files, and after doing so it will give me a qmaker error. After uninstalling and reinstalling the extension and qt ... | You can uninstall your qt extension, and try to download qt-vsaddin according to your vs version. After installing the extension, you can add new qt version in the same way.
PS: Re-downloading qt extension in visual studio is useless (I have met the same problem like you)
Hope to help you
|
61,902,275 | 61,902,416 | Compiler giving error: format specifies type 'float *' but the argument has type 'double' [-Wformat] | I wrote a scanf("%f"), x (x is a float). And the compiler gives the error that is on the title. Both %f and %e are giving the same result.
| You must address the floating point variable with an ampersand to tell the compiler it's being stored in the memory.
You've done:
scanf("%f", x); // will obviously throw you a fatal warning
Consider:
scanf("%f", &x); // correct statement
That's it.
|
61,902,351 | 61,902,549 | Passing vector to member function of class | I am trying to pass a vector to a member function, but keep coming up with these errors:
27 28 [Error] 'double equip::calcmass' is not a static member of 'class equip'
13 19 [Error] invalid use of non-static data member 'equip::time'
27 24 [Error] from this location
28 1 [Error] expected unqua... | Your code is not working because you defined a a class equip, but never created an instance of it in main, and then you try to read a file content into a member of class time. Also, your function calcmass in the class definition has no arguments, but later you declare it with argument of undetermined type time. Remove ... |
61,902,380 | 61,902,764 | Iteratively read bytes from standard input in c++ | So I want to read a certain amount of bytes from standard input however my code does not read next bytes, it only reads a set amount of bytes and exits.
while(1) {
char c [100];
if( read(0, c, 100) < 1) break;
for(int i; i<100;i++){
cout << (c[i]);
}
}
This code only prints out the first 100 c... | The flaw in my code was a logical one. It did run over the whole file however infor(int i; i<100; i++) i was only incremented on first run, after that i stayed at i=99 so the rest of the reads did not actually print out because i was not running over the characters read into the buffer.
Thank you everyone who attempted... |
61,902,404 | 61,902,450 | Windows 7 applications run slower when not focused | I'm attempting to run two applications simultaneously on windows 7, however, I'm finding that when I do this, whichever has focus runs at a normal speed but the other is clearly running at a far slower speed. (For reference, one is a unity application and the other is a C++ direct X application). Has anyone ever encoun... | Windows automatically offers less system resources to unfocused programs no matter their complexity or requirements. I don't believe you can disable that.
|
61,902,449 | 61,902,643 | Read a binary file until the end c++ | I have class player that contains some attributes.
I m filling a file with player's data but i want to assign a new id number every time the function is called in a way that the new player's id will be increased every time.
So i made this while loop to read number of players and update the player's new id but this does... | I'd recommend storing the players in a text file that you parse instead of storing them as binary data.
This has a lot of advantages.
The biggest difficulty with your approach is that you need to design a binary format for your player object.
Something like
id+N1+'fullname'+N2+'email'+N3+'ingame-name'
4 bytes id, N1 ... |
61,902,452 | 61,902,500 | Is using compound assignment operator (+=, ...) on uninitialized variable NOT a UB in C++? | I am trying to create a simple tool to detect the use of uninitialized variables based on Clang AST. What I know is that the thing actually causes UB with uninit variables is an lvalue to rvalue cast that happens implicitly.
Now what I noticed while examining the AST of a basic example program is that all compound ass... |
Is using compound assignment operator (+=, …) on uninitialized variable NOT a UB in C++?
No, it is UB (except for in cases where standard says it's not).
Standard quotes (from latest draft):
[expr.ass] The behavior of an expression of the form E1 op= E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only... |
61,902,690 | 61,902,845 | Initialization of static class member raises "does not name a type" error | Compiling the following code with g++ outputs the following error:
main.cpp:51:19: error: 'running_id' in 'class MyContainer<int>' does not name a type
51 | MyContainer<int>::running_id = 0;
| ^~~~~~~~~~
main.cpp:11:16: note: 'MyContainer<int>::running_id' declared here
11 | static int... | You need to define the static member like this:
template <typename T>
int MyContainer<T>::running_id = 0;
now this will work automatically for every T as you want.
|
61,902,697 | 61,902,776 | Why does the `const` modifier applied to a variable holding a struct value make the struct values immutable? | struct S { string s; }
void method()
{
const S s = { "s" };
s.s = "l"; // Error
}
I can't understand why a compile-error is being generated here. From my understanding, making a struct-referencing variable const should make the variable itself immutable (only s = { "m" } after s initialization should generat... | It's not "a variable referencing a struct instance". There's no indirection. The value of s is a struct S, which includes all of its fields.
|
61,902,865 | 61,903,104 | Need assistance with loop to iteratively add to sum variable in Assembly | I'm trying to convert the following C++ code into Assembly (MASM, Irvine32):
const int SIZE = 10;
int numbers[SIZE] = {10,60,20,33,72,89,45,65,72,18};
int limit = 50;
int index = 0;
int sum = 0;
while( index < SIZE )
{
if( numbers[index] <= limit )
{
sum = sum + numbers[index]; // sum += array... | Your conditional branch that implements the if is wrong. It should look like:
top:
...
cmp [esi], ecx
ja L1 ; conditional jump *over* an ADD instruction
add eax, [esi] ; [esi] is array[index] if you increment ESI properly...
L1: inc index
jmp top
In your C++, you can see that if num... |
61,902,902 | 61,902,971 | Are compound assignment operators less precise than in c++? | According to this thread Why don't Java's +=, -=, *=, /= compound assignment operators require casting?, the i+=j is safer but less precise than i=i+j in JAVA due to typecasting.
Is it also true in case of C++?
EDIT:
Assumption: int i; long j; i.e.the variables are of different datatypes
| In C++ if both operands i, j are of the same type then no conversion is done.
If they are different then the lower range (e.g. int) is promoted to higher range (e.g. long or float or double)
This promotion, from down to up, most times doesn't lose precision. But some int-to-float conversions may lose some digits.
There... |
61,903,064 | 61,903,189 | Is it possible to return an a reference to the data in an std::vector, and preserve that reference after the vector goes out of scope? | I am used to programming in C, and in that language I would just return a pointer to the data, and then the caller would be responsible for freeing the data, however, from what I've read, the vector's destructor will be called as soon as it goes out of scope, causing it's data to be de-allocated.
Once the reference is ... | Good (safe and fast) solution for the use case that you describe: Don't return a reference, return the vector to the outside of the scope instead.
Is it possible to return an a reference to the data in an std::vector, and preserve that reference after the vector goes out of scope?
Yes... if you use static storage. Th... |
61,903,194 | 61,903,242 | Callback functions in C++ dynamic linked library | I have a dynamic linked library in C++. What I want to do is have a callback function declared in the library and leave it to the user to define in their code that uses the library. Pseudo-code example:
//in library
void userDefinedFunction();
void libraryFunction() {
//do stuff
userDefinedFunction();
//do... | Of course. Your library could accept a function pointer to a user defined function or a reference to a functor given by the user. The void libraryFunction() will just use that to call the user function.
|
61,903,216 | 61,903,316 | obj vector to member function | I can't seem to understand how to pass a vector from a class to a member function. What am I doing wrong here? My errors are:
line column
27 8 [Error] prototype for 'double equip::calcmass(std::vector)' does not match any in class 'equip'
17 10 [Error] candidate is: double equip::calcmass()
60 21 [E... | Within your class you define double calcmass(); which takes NO arguments and returns a double but later you try to declare it as double equip::calcmass(vector<double> time) which takes a vector of doubles and returns a double. You should change the declaration within the class to double calcmass(vector<double> time);
I... |
61,903,221 | 61,903,274 | Is it undefined behaviour to std::memcpy a struct into a std::vector<char> that has enough capacity? | Will the following program give undefined behaviour?
#include <vector>
#include <cstring>
struct Data
{
float a;
float b;
int z;
};
int main()
{
std::vector<char> allMyData;
Data someStuff({.2f,.3f,1});
allMyData.resize(sizeof(Data));
std::memcpy(&allMyData[0], &someStuff, sizeo... | There is no undefined behavior in the particular example you have showed. However, things would be quite different if Data contained pointers to external data, or non-POD class types like standard containers, etc.
|
61,903,705 | 61,903,777 | Why won't this signal handler catch SIGHUP or SIGQUIT? | I am starting to practice handling signals and wanted to see if I can prevent the use of SIGHUP or SIGQUIT in stopping a process that was executed within the same program as the sigaction structure. But the below function doesn't seem to prevent me from sending either SIGHUP or SIGQUIT through the command line to stop ... | We'll start by re-reading what sa_mask does, which you set with the intent to block the signals in question, however that's not exactly what that does.
From the sigaction(2) manual page:
sa_mask specifies a mask of signals which should be blocked (i.e.,
added to the signal mask of the thread in which the si... |
61,904,160 | 61,905,228 | why should we bind a key to a memory block by pthread_setspecific rather than just keep the pointer to that block? | As usual, we use pthread_setspecific to bind a dynamically allocated block to a global key.
void do_something()
{
//get thread specific data
int* glob_spec_var = pthread_getspecific(glob_var_key);
*glob_spec_var += 1;
}
void* thread_func(void *arg)
{
int *p = malloc(sizeof(int));
*p = 1;
pt... | You can indeed implement your own thread-specific storage by allocating it within the thread start function, then passing a pointer to it to every thread function, and freeing it on thread exit.
The advantage of the pthread_setspecific() / pthread_getspecific() interface is that it lets you avoid that bookkeeping - in ... |
61,904,203 | 61,904,274 | Is there a relationship between printf %p format and basic_ostream format? | As far as I know %p used in printf writes an implementation defined character sequence defining a pointer.
But is it always supposed to write the same character sequence than
basic_ostream& operator<<( const void* value );
?
I have not found any information concerning a potential relationship between the two formats a... | std::basic_ostream::operator<< for pointers uses std::num_put::put, which is defined to work the same as std::printf() with %p plus locale-specific conversion and padding.
|
61,904,728 | 61,904,812 | Create array/vector of items with different constructor arguments per item | I want to create an array/vector (indifferent to which one) of class instances. I have the following constraints:
Each instance is constructed with a different argument (e.g., Item(0), Item(1), Item(2), ...).
The Item class has both its copy and move constructors deleted.
Constraint #2 above seems to rule out using a... | Given
struct Item
{
Item(int);
Item(const Item&) = delete;
Item(Item&&) = delete;
};
You have some options:
smart pointers
You can use smart pointers, in this case std::unique_ptr:
auto test()
{
std::vector<std::unique_ptr<Item>> v;
v.emplace_back(std::make_unique<Item>(1));
v.emplace_back(std... |
61,904,940 | 61,907,642 | Post Data to Elastic Search from a C++ program | I am trying to post some JSON data to Elastic Search from a C++ program where i am executing the cURL command using system.
#include<iostream>
#include<string>
using namespace std;
int main()
{
system("curl -XPOST \"http://localhost:9200/test/_doc\" -H \"Content-Type:
application/json\" -d\"{\"drop\... | You are not escaping the json string correctly in the system call. I think its the curl command or the shell capturing them?
What you end up sending to the server looks like {drop : 40, @timestamp : 2020-05-20T03:05:30}
Note: there are no quotes around drop - exactly what the error message is telling you.
To fix try u... |
61,905,182 | 61,905,252 | Why Is The Value Of An Uninitialized Memory Location Give The Value Of -842150451? | I was messing around with memory allocation. I was testing to see that, like Java, this program with give an exception.
int main() {
int* a = nullptr;
int b = *a;
std::cout << b;
}
Which indeed it does. Then I tested using malloc as a pointer to a, but not initializing a.
int main() {
int* a = (int*) m... | -842150451 is the two's complement representation of the value 0xCDCDCDCD, which is a common Visual Studio debugger value for heap-allocated uninitialized memory.
Uninitialized variables or memory have indeterminate values from the C++ specifications perspective, and using such values lead to undefined behavior. If you... |
61,905,273 | 61,906,499 | How to create an object creation function that will be called by the name associated with it? | I have a class inheritance hierarchy: Figure -> Circle, Point, Line, Rectangle.
I need to create a function to create a Circle graphical object from a given hierarchy, by the name associated with it. The function should return unique_ptr to the object. The parameters of the function are the name of the object and its c... | The standard approach to solve your problem is to use an Abstract Factory design pattern.
Based on a "key". like a name (for example "Circle") or an id, like the integer "3", the required class will be created.
So, factory has always a "create"-method, and a container stores all "create"-methods. To store all methods, ... |
61,905,539 | 61,906,117 | what is the use of using the typedef and what does it signifies? | I came across the code and it was kind of strange to me I am unable to understand what it means.
typedef struct alpha *Abc;
this is where Abc is defined;
struct alpha{
Abc s;//what does this mean
}
also some where in function it is used like this
Abc iAmFunc(Abc beta,int a){
some thing is performed
... | Note, this is for C and not C++. Maybe it's applicable for C++ too, but I don't know.
typedef a b makes b an alias for a
What typedef struct alpha *Abc; is to make Abc an alias for struct alpha *. After you have created this, these two are equivalent:
struct alpha *ptr;
Abc ptr;
There are a few different uses for this... |
61,906,034 | 61,906,329 | If i want to give any input to my function using cout... how can I give | int do_something(int num)
{
//stuff happens.
}
do_something(5)
Here we have given the input directly to the parameter, but if I want to give input to this using cout...
Like It asks me to give input and it directly store in the (int num)....
How can I give... Please suggest me
| cout is an output stream. It is not to take input from. You can use cin (which is an inputs stream) to take the input and then pass it to your function.
int n;
std::cin >> n;
do_something(n);
|
61,906,282 | 61,906,463 | Specialize variadic template member function | Is there a way to get this "fake overloading" argument specialization to work?
#include <iostream>
class Foo
{
public:
template < typename T, typename ... Args >
T* bar (Args&& ... args);
};
template <>
int* Foo::bar()
{
std::cout << "int* bar()\n";
return new int;
}
// error: template-id ‘bar<>’ for ‘doub... | The parameter type of the specialization double, doesn't match the parameter type of the primary template Args&&, as the error message said.
The primary template is applying forwarding reference, which could instantiate as both lvalue-reference or rvalue-reference. For rvalue-reference (which matches the usage in main(... |
61,906,286 | 61,909,359 | How to access DirectWrite inherited interfaces in C++? | I am using C++ to work with DirectWrite but I cannot seem to figure out how to use methods that are in inherited interfaces. For example, the " GetUnicodeRanges" method/function in the IDwriteFont1 interface.
The IDWriteFont1 interface/object is not accessed by any other DirectWrite interface/object, including IDWriteF... | You should be able to do IUnknown::QueryInterface from IDWriteFont interface pointer and get IDWriteFont1 provided that it is available and implemented there in first place of course.
That is, some pseudo-code:
IDWriteFont* Font = ...
assert(Font);
IDWriteFont1* Font1 = nullptr;
if(SUCCEEDED(Font->QueryInterface(__uuid... |
61,906,404 | 61,907,727 | Failure to create C++ arrays recursively | I want to test a recursion method and the following code has a compilation error. I've double checked the subscripts variables, and they should be correct. I really couldn't figure it out, can somebody help me?
#include <iostream>
#include <array>
using namespace std;
template <typename T, size_t Size>
void fn(array<T... | First of all, let us understand where the problem comes from.
The error you get
/usr/lib/gcc/x86_64-pc-cygwin/7.3.0/include/c++/array: In instantiation of ‘struct std::array<int, 2305843009213693952>’:
GuessNumber.cpp:15:9: recursively required from ‘void fn(std::array<_Tp, _Nm>&) [with T = int; long unsigned int Siz... |
61,906,547 | 61,906,785 | Can you call a void function of array when it is in between two loops? | I wrote code which take size of an array and enter the elements of an array and then cyclically rotate an array.
INPUT : 1 2 3 4 5 //elements of an array
Correct Output: 5 1 2 3 4
//I made rotate function for the program but when i called it ,the program run but didnt show me the correct answer instead when i wrote th... | arr[0]=arr[x];
should be
arr[0]=x;
arr[x] is potentially an out of bounds array access, giving your programs undefined behaviour.
|
61,907,201 | 61,907,517 | Error meaning; printing a number in binary form | I used the code here, but the compiler gives me the error:
conversion to 'long unsigned int' from 'short int' may change the sign of the result [-Werror=sign-conversion]
Why?
#include <cstdlib>
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
char a = -58;
std::bitset<8> x(a);
std::... | There are two issues: First, the compiler is warning about an implicit type conversion in the code. Second, the compiler is treating warnings as errors, causing the build to fail.
The bitset takes a parameter of type unsigned long int, but you are attempting to pass a (signed) short int. You know it will promote the si... |
61,907,503 | 61,908,277 | Unable to initialize a function returning pointer to a structure | I am relatively new to programming, so please pardon me as this is a very simple and basic question. I am working in visual studio 2019. I made a class Sphere and inside it I created a structure:
struct point{
vec3 coordinate; //I am using glm library
};
struct triangle{
point p1, p2, p3;
};
Now when I declare a f... | I will sum it up:
It you defined an inner-struct triangle (you should call it Triangle by the way!). In order to call it from outside the class you must specify its complete name, thus, the following signature is not valid:
Triangle* Sphere::returnTriangle(Triangle T)
Because it is looking for a struct with a name Tri... |
61,907,826 | 61,911,203 | What are the rules for ordering concept constrained functions in C++20? | I just learned that C++ concepts are much more superior than SFINAE because functions constrained by concepts are ordered, meaning a more constrained function is considered a better match than a less constrained one.
How exactly are the rules used by the compiler to estimate how much constrained a function is?
How do t... | To make simple..., during the overload resolution process:
First, all functions that would be viable without the constraints but whose constraint are not satisfied are considered not viable.
So the set of viable overload contains functions, template functions and constrained templated function with satisfied constraint... |
61,908,068 | 61,908,231 | Why does the loop direction of my filter change my result? | I have designed a simple dual channel filter to remove some noise at a given frequency.
#include "../include/Filter.h"
void Filter(int DataIn, int* DataOut, bool Enable)
{
static coef_t Coefficients[] = {
0.0076925293, -0.039817952, 0.018740745, 0.013075141, -0.052312399,
0.052374545, 0.017... | if(i == 0)
{
ShiftRegRight[0] = DataIn & 0x0000FFFF;
ShiftRegLeft[0] = (DataIn & 0xFFFF0000) >> 0x10;
}
else
{
ShiftRegRight[i] = ShiftRegRight[i - 1];
ShiftRegLeft[i] = ShiftRegLeft[i - 1];
}
When you count down i==0 evaluates to ... |
61,908,176 | 61,908,306 | Inserting objects into binary search tree - C++ | I'm pretty new to binary search trees. I've created a template class for a binary search tree so that it can handle class objects. Now I'm trying to test it in main, and I'm reading in dates from a text file into a 'Date' object of class Date, using a while loop until the end of the file. After the first iteration, I c... | The test firstDate==secondDate compiles to:
operator==(firstDate, secondDate)
which calls your bool operator==(const Date& firstDate, const Date& secondDate) ad infinitum. You need to compare the components of the Date object.
I don't know how it is defined, but maybe something like the following:
bool operator==(cons... |
61,908,313 | 61,908,438 | Running a C++ code and a Python code consecutively | I know it's a very general question but I am open for different options.
Let me clarify what my codes do:
The C++ code produces multiple .png files as output as follows
./Debug/mycpp input1path input2path output parameter1 parameter2
The python code takes those png files to do image processing and returns them a... | Python is perfect for such scripts, it has a complete support for such scripts.
You should look at subprocess and os modules for the complete command set for it.
|
61,908,407 | 61,908,583 | class with unknown struct as member | Is it possible to assign an unknown struct to a class in c++? Something like a virtual function maybe? Or assigning a pointer to a struct? The struct would be assigned at construction and then never change.
class Class{
void someFunction(){
//do something with the struct
};
struct unknownStruct;
};
struct S... | You can use a template
template<class StructType>
struct Class {
void SomeFunction() { ... }
StructType myStruct;
};
or a variant if the number of structs is limited
struct S1 { };
struct S2 { };
struct Class {
void SomeFunction() { ... }
std::variant<S1, S2> myStruct;
};
or polymorphism
struct Base {... |
61,908,431 | 61,908,860 | How to assign a derived class object to a base class pointer using a function (not the constructor) | Problem summary
I don't know how to create an object of a derived class with the new-operator through a function (not a constructor), and have a base class pointer point to it.
Setup
I have an abstract base class and a derived class in my project:
class Base
{
// stuff
};
class Derived : public Base
{
//stuff... | Return a pointer from func might be the best option, but if you cannot modify func then ptr = new Derived(func(args)) might work. This requires that Derived has a copy constructor or a move constructor.
|
61,908,904 | 61,909,044 | How to insert from QUEUE to 2D LIST | I have a pretty basic question. How to push from QUEUE to LIST. I am pretty much copying from queue to list. Here is my example:
list<list<BoardingTicket>> boardPassenger(queue<BoardingTicket>& waitingLine){
list< list<BoardingTicket>> combinedList;
while(!waitingLine.empty()){
combinedList.push_bac... | If u want to use iterators on std::queue<T>, it isn't possible. There are no iterators for them.
If u want to use the iterator of the list but I think push_back() is easier and more clear.
Use the following
list<list<BoardingTicket>> boardPassenger(queue<BoardingTicket>& waitingLine){
list<BoardingTicket> combined... |
61,909,401 | 61,911,410 | Is this a bug or expected behavior of glGetTexParameterIuiv? | I have a problem with OpenGL code that only appears with Intel UHD GPUs/drivers (tried with different UHD and driver versions (Builds 26.20.100.7810, 27.20.100.8190)).
Basically glGetTexParameterIuiv(name, GL_TEXTURE_TARGET, &textureTarget) seems to not work at all. It always gives a GL_INVALID_ENUM error.
The driver r... | I have checked your code sample on AMD, NVIDIA and Intel (HD Graphics 630) drivers at hand - and only the latter one failed with error on calling glGetTextureParameterIuiv(), and I also don't see from function description a reason for this misbehavior. Tested with GL_ARB_debug_output, which doesn't give more informatio... |
61,909,634 | 61,909,725 | returning this from function in c++ | I have recently seen a question on stack overflow that how to get derived object from function,
some suggested that create local object and return copy from function. how about returning this from function?
I just wanna know, is that good coding practice?
Thank you for your assistance and time.
below is my example code... | You could use your code like this
Derived d;
Derived* d_ptr = d.func(123);
Seems easier to just write this (assuming a suitable constructor)
Derived x(123);
Derived* x_ptr = &x;
But maybe you were thinking of something else.
|
61,909,735 | 61,910,170 | CMake's VS_PACKAGE_REFERENCES not adding a reference to VS2017 project | I'm trying to automatically add (nuget) references to my (C++) visual studio 2017 project using CMake.
In this question, VS_PACKAGE_REFERENCES is suggested, available from CMAKE 3.15. So, I've added the following to my CMAKE code:
set_property(TARGET MyApplication
PROPERTY VS_PACKAGE_REFERENCES "BaseUtils.Native.Dy... | Hmm, apparantly, C++ projects are not supported by PackageReference according to learn.microsoft.com
ASP.NET apps targeting the full .NET Framework include only limited
support for PackageReference. C++ and JavaScript project types are
unsupported.
This makes the whole VS_PACKAGE_REFERENCES option from CMake inap... |
61,910,159 | 61,910,288 | What is the meaning of the line - " vector<long long> distance(n, std::numeric_limits<long long>::max()); "? | Actually I have to find shortest paths from the source vertex to all the other vertices. For this I have been provided with the code template given below. I want to implement " Bellman–Ford algorithm ".
#include <iostream>
#include <limits>
#include <vector>
#include <queue>
using std::vector;
using std::queue;
using ... | vector<long long> - the type of the variable
distance - the variable name
(n, std::numeric_limits<long long>::max()); - the constructor parameters
std::numeric_limits<long long>::max() - std::numeric_limits is a class which requires a type parameter (here long long) and it has static functions, which return values spec... |
61,910,725 | 61,923,474 | How to transform a boost::hana::map into lambdas | I have the following code
template <typename T>
void my_func(T& /*var*/)
{
};
auto my_types = hana::make_map(
hana::make_pair(hana::type_c<std::uint32_t>, hana::integral_c<std::uint8_t, 1>),
hana::make_pair(hana::type_c<std::uint16_t>, hana::integral_c<std::uint8_t, 1>)
);
using my_variant = std::variant<std::uin... | It's not clear why you are trying to use hana::map. hana::map is not a Functor and has no implementation for hana::transform. It is, however Foldable so you could use hana::unpack and return a new tuple of lambdas if you needed to.
As for hana::first along with other accessors including hana::at, hana::at_key, etc.; Th... |
61,911,472 | 61,911,595 | Is there a way to check if value sent to variable is right type while it is already under that var? | I couldn't find a way to check if the value that was passed into variable is right type.
For example: I have passed char into int variable and I would like to check if it is int inside int(?). I thought about checking if argument that was sent is in ascii table, but i don't find this as optimal solution. Some code:
M... | If you want to distinguish between characters and integers, then you could use overloading of the Martice constructor. So you have one constructor taking an int, and one taking a char.
If you want to disallow passing of char, then you could mark the char overload as deleted:
explicit Martice(char) = delete;
If you wan... |
61,911,702 | 61,915,299 | Should I keep this function for finding nth prime or can this be optimized? | We have a coding homework related to prime and my friend wrote this code. Its long and I dont understand it that much and has goto which is I think frowned upon so I don't know. Can help decide if we should we keep it?
int getNth (int nth){
vector<int> prime;
int sievelmt = nth*10;
int i,j;
func:
ve... | The heart of the algorithm is this line:
for ( j = 1; i*j <= sievelmt; j++) sieve[i*j]=j;
For a given i that fills locations of array sieve that are multiples of i, with the rank of the multiple. Imagine i=7, then sieve[7]=1, sieve[14]=2, sieve[21]=3, etc.
This is the base of Eratosthène's sieve, a very very old algor... |
61,911,765 | 61,912,013 | Manipulating byte vector through float pointer | Is it possible to manipulate an std::vector<unsigned char> through its data pointer as if it were a container of float?
Here is an example that compiles and (seemingly?) runs as desired (GCC 4.8, C++11):
#include <iostream>
#include <vector>
int main()
{
std::vector<unsigned char> bytes(2 * sizeof(float));
au... | Legal answer
No, this is not permitted.
C++ isn't just "a load of bytes" — the compiler (and, more abstractly, the language) have been told that you have a container of unsigned chars, not a container of floats. No floats exist, and you can't pretend that they do.
The rule you're looking for, which is known as strict a... |
61,911,806 | 61,916,855 | Avoid memory leak when removing last node from deque using linkd list | For my homework, I need to make methods that add (append) and remove (serve) nodes from a Deque. However, when trying to serve the last node I struggle with memory leaks since I don't know how to retrieve the node that's not being used anymore to the system.
Here's the code for the method.
void Deque::serveAtRear(int &... | Generic answer to how avoid leaks is: avoid manual memory allocation.
For example you can use smart pointers, e.g. std::unique_ptr and instead of calling new DequeNode call std::make_unique<DequeNode>(). Compiler will then point places where your code needs to be adapted, as you will limit yourself so that each of your... |
61,912,001 | 61,912,245 | Create std::function which returns variant with a value of a function member. Segmentation fault | I am writing a wrapper class to wrap custom struct member variables into variants.
Given a reference to a struct object, std::function must return a variant, that contains a value of a specific member - with which std::function was initially created. That means, I need to Save a pointer to the specified class member on... | Your WrapGet function takes a pointer to a member function by value, and inside your function that you're capturing that pointer as a reference inside a lambda. That means that after the function ends using the reference inside the lambda is dangling and using it invokes UB.
To avoid it capture it by value instead to ... |
61,912,304 | 61,912,420 | C++ Variable declaration of type class does not name a type? | Im having a problem involving declaring variables that are of a type class.
Example code
class Party{
public:
string partyName;
Leader leader;
Candidate candiate;
nationalcompaignManager nationalManager;
natioanlfinancialManager financialManager;
compaignMananger newcompaignMananger;... | Just declare Leader above Party to make it "visible" to Party class.
class Leader
{
};
class Party
{
Leader leader;
};
|
61,912,879 | 61,914,295 | Automatic move from local variables when variable is rvalue reference | According to cppreference, in return statement, local rvalue references should be moved from in C++20:
Automatic move from local variables and parameters
If expression is a (possibly parenthesized) id-expression that names a variable whose type is either
a non-volatile object type or
a non-volatile rvalue reference ... |
Is this something which haven't been implemented yet in compilers?
Not implemented yet (look for P1825), you understand the rule correctly. But let's go through it to be sure. The specific standard text here is in [class.copy.elision]/3:
An implicitly movable entity is a variable of automatic storage duration that i... |
61,912,991 | 61,915,503 | Merge sort same output C++ | I wrote the below code for merge sort but it's not working, And I am unable to find out problem!
Every time the output becomes same as input, I think that problem may occur due to vector reference.
I think mergeSort is not creating a new vector for sub array. But I am still confused.
input vector: 5, 4, 3, 2, 1
output... | The code posted does not seem to have a problem.
Executing it produces the expected output: 1 2 3 4 5, so there is something else going on that could cause your observations: you might be running an executable produced by a previous or at least different version of the code.
|
61,913,257 | 61,913,418 | Do functions go to the heap or stack if the class is on the heap? | class Foo{
public:
void foo(){
int x, y; // go to the HEAP or the stack?
}
};
int main(){
Foo *f = new Foo();
f -> foo();
delete f;
}
if I create a class instance on the HEAP and activate a "class method" where is the function local variables and "metadata" stored? on the... |
Do functions go to the heap or stack if the class is on the heap?
The C++ language does not have such thing as "heap" or "stack".
Automatic variables have automatic storage. Dynamic objects have dynamic storage. Static variables have static storage. Thread local variables have thread local storage.
Functions do not h... |
61,913,406 | 61,913,678 | c++ : OOP : How do you update an array in a separate header file? | I'm new to c++ and am trying to create a basic maze game. Currently, I'm trying to enable the player to move about the maze, in which the player's movement function updates the characters in the grid array. The grid array is in Grid.h and the Player is in Player.h and I've included the headers in each file but they sti... | First: grid.h and player.h include each other. This should be avoided and in this case, grid.h doesn't need player.h.
Actual issue: there is no Grid object that can be used by your player. Ideally, Grid and Player should be members of a Game class and a reference to the Grid object should be passed to Player. so it can... |
61,913,470 | 61,913,761 | Using parameter packs to automate dynamic_cast checks | I'm trying to implement a communication system inside of a GUI. I would like to avoid the visitor pattern for maintainability reasons. Likewise making a dynamic_cast if else statement is not maintainable. The closest I've come is implementing multiple dispatch with tables from Scott Meyers' More Effective C++.
So far I... | You might do something like:
template <typename ... Ts>
void Distpatcher::Dispatch(BaseCommand* pCommand)
{
(DispatchUnique<Ts>(pCommand), ...); // C++17
}
so
m_Distpatcher->Dispatch<DerivedCommand1,
DerivedCommand2,
DerivedCommand3>(pCommand);
would be equivalent t... |
61,914,086 | 61,915,160 | Implicit move constructor and assignment operator | What does it mean that implicit move constructor does a member-wise move and implicit move assignment operator a member-wise assignment?
From https://en.cppreference.com/w/cpp/language/move_constructor:
For non-union class types (class and struct), the move constructor
performs full member-wise move of the object's ... | If you look further down you linked page, you will see that your classes compiler generated move constructor (and move assignment operator) will actually be Trivial:
Trivial move constructor
The move constructor for class T is trivial if all of the following is true:
it is not user-provided (meaning, it is implicitly... |
61,914,658 | 62,021,130 | How do I get the compiler to read a downloaded library? | I've downloaded OpenMesh for Linux Ubuntu. I successfuly compiled it following instructions at
https://www.graphics.rwth-aachen.de/media/openmesh_static/Documentations/OpenMesh-8.0-Documentation/a04067.html
using cmake, then make. The result is a "build" folder containing, among other things, a makefile and .o files. I... | The correct way to do it is to open CmakeLists.txt in qt creator, which organizes everything correctly.
|
61,914,831 | 61,915,454 | Call a C-style function address with std::bind and std::function.target using a method from object | I have a C-style function, which stores another function as an argument. I also have an object, which stores a method that must be passed to the aforementioned function. I built an example, to simulate the desired situation:
#include <functional>
#include <iostream>
void foo(void(*f)(int)) {
f(2);
}
class TestCla... | This is a dirty little hack but should work
void foo(void(*f)(int)) {
f(2);
}
class TestClass {
public:
void foo(int i) {
std::cout << i << "\n";
}
};
static TestClass* global_variable_hack = nullptr;
void hacky_function(int x) {
global_variable_hack->foo(x);
}
int main() {
TestClass t... |
61,915,319 | 61,992,807 | Per-file (ideally per-section) clang-format style override | I would like to mark part of a file with something like:
// clang-format -style="{ SomeSetting: NewValue }"
...
// clang-format -style="{ SomeSetting: OldValue }"
that would override the global settings in the root .clang-format file. If not possible, specific formatting a single file would also do as I could work a... | What you want is currently (clang 13) not possible, but is certainly a nice feature to add to clang-format.
Current documentation on Clang-Format Style Options states nothing about entering style options in code. As you said, the closest we can get is using // clang-format off and // clang-format on hints.
|
61,915,474 | 61,915,751 | Difference between const reference and reference | void setage(const int&a);
void setage(int&a);
What is the difference between this two functions?
When this function is called?
| Given the overload set:
void setage(int&a) { std::cout << "&"; }
void setage(const int&a) { std::cout << "&c"; }
the first function is called only with variables that are non-const:
int a = 42;
setage(a); // prints &
The second function is called if you pass it a variable that is const, or if you pass it a literal v... |
61,915,623 | 61,915,740 | Error when trying to link GLFW from source to project on c++ via CLion on Ubuntu | I'm trying to add GLFW from source to my project. I did as stated in the documents, but I get an error.
Error:
/usr/bin/ld: CMakeFiles/mancala_graphics.dir/main.cpp.o: in function `main':
/path/to/clion/mancala_graphics/main.cpp:47: undefined reference to 'glClear'
collect2: error: ld returned 1 exit status
make[ 3 ]:... | From the GLFW documentation:
Note that the glfw target does not depend on OpenGL, as GLFW loads any OpenGL, OpenGL ES or Vulkan libraries it needs at runtime. If your application calls OpenGL directly, instead of using a modern extension loader library, use the OpenGL CMake package.
find_package(OpenGL REQUIRED)
targ... |
61,915,654 | 61,916,014 | C++ Accessing if statements if they are inside for loop | Im writing snake in c++, and i came across some problems. My printBoard method just prints the map for the game. It has access to array where the clean map is sitting. But the most important part is that it checks if coordinates of current field are the same as Food coordinats or one of snake's body coordinates. Obviou... | If you just replace the loop with an appropriate algorithm, then you can use an if-else statement quite easily:
for(unsigned int i=0; i< BOARD_HEIGHT ; i++)
{
for(unsigned int j=0; j< BOARD_WIDTH; j++)
{
if (std::any_of(std::begin(player1._snakeBody), std::end(player1._snakeBody),
... |
61,915,688 | 61,916,811 | C++ how can I balance the brackets after the macro call? | #define function(...) [](){ DO_STUFF(__VA_ARGS__)
Because of the open bracket in the macro, I'm left with an ugly usage with either a missing bracket or an extra bracket. Is there a way to fix this?
function(a, b, c)
foo();
}
function(a, b, c){
foo();
}}
| You can make use of lambda capture initializers which were introduced in c++14:
template <class...Args>
int do_stuff(Args&& ... args)
{
((std::cout << args),...); // <-this requires c++17 and is just for illustration.
return 1;
}
#define myfunction(...) [dummy##__LINE__=do_stuff(__VA_ARGS__)]()
int main() { ... |
61,915,960 | 61,916,477 | C++ How to cin and cout in same line? | So I'm trying to code a program for my project and I'm pretty much done. Now all I want to do is make the console look a little more designed for example:
cout<<"\t\t\t\t\t\t Please Login With Admin Credentials!"<<endl;
cout<<"\t\t\t\t\t\t ==================================="<<endl;
cou... | You can't use backspace to get back to previous lines, but you can use cin during execution.
If you consider the following:
std::string something, something2;
cout<<" Please Login With Admin Credentials!"<<endl;
cout<<" ==================================="<<endl;
cout<<" ... |
61,916,433 | 61,916,928 | How can I redefine array size in a subclass? | I have a base class in which I define an array of structs (of base types) and some methods that act on its objects; I never instantiate directly this class, just created varius sublasses of it. Now, in each subclass I would like to redefine the array size to the subclass particular needs.
Consider that I would like to ... | With template, you might do something like:
template <std::size_t N>
class ItemsArray {
DataItem dataItems[N];
};
using classA = ItemsArray<50>;
using classA = ItemsArray<15>;
|
61,916,465 | 61,916,763 | Implicit move constructor | What is exactly the implicit move constructor doing? For example how would the implicit move constructor look like for the following class (could you provide some example implementation of this implicit constructor):
struct A
{
A() = default;
A(A && other) = default;
int a;
};
struct B : public A... | From cppreference.com:
For union types, the implicitly-defined move constructor copies the
object representation (as by std::memmove). For non-union class types
(class and struct), the move constructor performs full member-wise
move of the object's bases and non-static members, in their
initialization order, usi... |
61,916,573 | 61,916,687 | why this code gives Unhandled exception failure | I used a vector because I don't know the number of inputs, but it doesn't work. What should i do?
vector <string> str;
str[0] = "entity1 ABCDE 2x2 infected";
std::istringstream ss(str[0]);
std::string token;
vector<string> genes;
while (std::getline(ss, token, ' ')) {
genes.push_back(token);
}
for (int i = 0; ... | In this code:
vector <string> str;
str[0] = "entity1 ABCDE 2x2 infected";
str is empty, so you have undefined behavior when you access the first element (at index 0). You could fix this by allocating space for one string in the vector:
vector <string> str(1);
or by directly creating a vector with one string (which wi... |
61,916,691 | 61,920,722 | Pointer being freed was not allocated (while implementing stack as a linked list) | Here's my stack:
template <class Type>
struct Node {
Type value;
Node* next;
Node(Type n_value)
: value(n_value), next(nullptr)
{ }
static Node<Type>* Add(Node<Type>* head, const Type value) {
if (!head) { head = new Node<Type>(value); }
else { head->next = Add (head->next, v... | I am unable to reproduce your results, so instead of an answer, I am providing a nudge on how you might proceed.
I changed the parameter of DisplayElements to 'lhead' (for local head), because the 'head' declaration shadow's the one in the outer scope. You also have some other shadows ... so I recommend you add -Wsha... |
61,916,965 | 61,917,515 | Return object of certain class from vector of objects | I need a function to find components of a class type from an array of components in another class.
This function doesn't work and gives "type name is not allowed" when used...
template<typename T> auto* GetComponent(T& comp)
{
for (int i = 0; i < Components.size(); ++i)
{
if (static_cast<T*>(Components.... | Here is an example using dynamic_cast rather than static_cast, as suggested by Jarod42. Two templates, For to perform a functor on each matching type, and GetComponent which is closer to the provided code snippet in the question.
#include <iostream>
#include <memory>
#include <vector>
namespace {
struct Animal { vir... |
61,917,144 | 62,261,399 | Dependencies with conflicting header versions of the same library | I compiled a simple program that uses the tensorflow C api, so I link it against the c_api.h headers and the libtensorflow.so. It compiles and links to program just fine.
When I check the library dependencies of the executable with ldd program I get the direct dependencies and their locations:
linux-vdso.so.1 (0x00007... | My workaround was to specify a different OpenCV path that has a compatible protobuf version:
# Finds installed opencv with incompatible Protobuff
# find_package( OpenCV REQUIRED )
# Finds the opencv with compatible Protobuf in my system
find_package( OpenCV REQUIRED PATHS /usr/local NO_DEFAULT_PATH)
Explanation
Bot... |
61,918,158 | 61,927,499 | How is float_max + 1 defined in C++? | What is that actual value of f?
float f = std::numeric_limits<float>::max() + 1.0f;
For unsigned integral types it is well defined to overflow to 0, and for signed integral it is undefined/implementation specific if I'm not wrong.
But how is it specified in standard for float/double? Is it std::numeric_limits<float>::... | In any rounding mode, max + 1 will simply be max with an IEEE-754 single-precision float.
Note that the maximum positive finite 32-bit float is:
3 2 1 0
1 09876543 21098765432109876543210
S ---E8--- ----------F23----------
Binary: 0 11111... |
61,918,273 | 61,918,351 | Overloading ostream << operator with pointer as parameter resulting with memory adress on output | I have some trouble with overloading ostream operator. There are 3 classes, abstract base class Packet another abstract class Sequence which inherits from Packet and class TimeHistory which inherits from Sequence.
class Packet
{
//some stuff
};
template <typename T = double>
class Sequence : public Packet
{
std::vecto... | std::unique_ptr::get will return a pointer to the managed object. If you want to get a reference to managed value use
std::cout<< *channel1;
To overload operator<< for an abstract class you can use a reference instead of a pointer:
friend std::ostream &operator<<(std::ostream &out, Packet &A);
|
61,918,461 | 61,918,840 | C++ Explicit Template instantiation with double and long double | So I wrote this template function which is for floating points.
In h:
template <typename FloatingPointType>
double nextLow(FloatingPointType a);
In Cpp:
template <typename FloatingPointType>
FloatingPointType nextLow(FloatingPointType a)
{
return std::nextafter(a, std::numeric_limits<FloatingPointType>::lowest());... | I found the Issue in the header file.
There it states:
template <typename FloatingPointType>
double nextLow(FloatingPointType a);
But of course it should be:
template <typename FloatingPointType>
FloatingPointType nextLow(FloatingPointType a);
Also the <> need to be dropped otherwise the compiler complains on usage o... |
61,918,462 | 61,918,665 | How to check whether isupper(cstr) worked? | I'm simply trying to do an if statement and then report to the console that my character string is now uppercase.
#include <iostream>
#include <cctype>
int main()
{
char str[] = "Stop";
if (isupper(str) == "STOP")
{
std::cout << "str now == STR" << std::endl;
}
}
I'm getting the error that an ... | This program will check until a lowercase letter is detected in the string:
#include <iostream>
#include <cstring>
int main(void) {
char str[] = "HELLO";
bool flag = true; // for verification
for (int i = 0; i < strlen(str); i++) // till string length
if (!isupper(str[i])) {
flag = fal... |
61,918,587 | 61,919,104 | Statement to determine the type of an object in C++ | Is there a statement s_type which allows to determine the type of an object in C++?
E.g.
s_type(int a); // int
s_type(&a); // int*
| #include <boost/type_index.hpp>
#include <iostream>
int main() {
using boost::typeindex::type_id_with_cvr;
using std::cout;
int a = 42;
int& b = a;
int* c = &a;
cout << type_id_with_cvr<decltype(a)>().pretty_name() << '\n';
cout << type_id_with_cvr<decltype(b)>().pretty_name() << '\n';
cout << type_i... |
61,918,768 | 61,919,291 | method overriding doesnt work as expected | sorry if the title isnt very good, i couldnt think of anything else
ive got this program:
class Animal
{
private:
int legs;
string sound;
protected:
Animal(int l, string s) : legs(l), sound(s) {}
public:
Animal() {}
string getClass()
{
return "Anim... | the reason that you're getting the current num of legs but not the animel name it because how constructor works,
when you create Dog class you calling the base class constructor with the "right" num of legs and
Dog() : Animal(4,"bark")
but when you calling printInfo Dog is looking for this function but cant find it so... |
61,918,777 | 61,919,007 | Menu choice error, couldnt find any solution. menu identifier not found | I have a question,
Im new to c++ and general with coding.
I have this problem Im coding right now an Loader for a game and want to make a choice menu.
I have this error and I dont know how to fix it.
If you could help I would be happy.
This is my code https://ghostbin.co/paste/x8hz3
int DLL();
int Beta();
int select()... | You don't need to return anything for select() seemingly. You should declare the main() and write there:
.
select();
.
Important: You haven't defined any proper definition for menu(). On the beginning of the code, just add a single line int menu(); and you're good to go.
|
61,919,152 | 61,938,366 | Running Keras DNN model (UNet) using OpenCV readNetFromTensorFlow: Error: Unknown layer type Shape in op decoder_stage0_upsampling/Shape | Python version 3.7
Keras version 2.3.1
TensorFlow version 1.14.0
I am wanting to run my UNet Keras model using OpenCV's readNetFromTensorflow in C++. I have successfully converted my HDF5 file to .pb per this issue:
How we can convert keras model .h5 file to tensorflow saved model (.pb)
However when I try and run the ... | I have solved my problem and will add my solution here for anyone else looking to perform inference with OpenCV on their own UNet.
Step 1:
Convert H5/HDF5 file to .pb as stated in my above question.
Step 2:
OpenCV must be upgraded to 4.2.0 (not sure if my solution is supported in anything else between 3.3.1 [my starti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.