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,241,801 | 64,245,277 | I need the option of passing in a vector of objects, or brace-enclosed list, to a constructor | My constructor originally took a std::vector<> but I couldn't figure out how to get a braced list to initialize it. I got it working after changing to an std:initializer_list<>. I found two ways: 1) passing the initializer_list in as a parameter to the array constructor (commented out in code below) and 2) using the ... |
On that third line of code it works with replacing initializer_list with vector, true. But I don't want to pass around a whole vector as an arg.
You're going to construct a vector anyway (One::athree_). So just move the vector passed to the constructor rather than copy it:
class One: public Base {
public:
One(Two... |
64,241,907 | 64,242,083 | Output is correct but SPOJ gave me wrong answer | Quick question. This is the code that I wrote to finish a problem in SPOJ. The output is correct but it gives me wrong answer. Whats wrong with my code? This is the link to the question: https://www.spoj.com/problems/SUMUP/
#include <iostream>
#include <iomanip>
using namespace std;
void cal(int n){
long double a... | In the lines:
for(z = 0; z < NUMS; z++){
scanf("%d", &bobo[n]);
cal(bobo[n]);
}
You should use z instead of n when calling scanf() and cal()
|
64,242,067 | 64,253,858 | std::atomic<bool> lock-free inconsistency on ARM (raspberry pi 3) | I had a problem with a static assert. The static assert was exactly like this:
static_assert(std::atomic<bool>::is_always_lock_free);
and the code failed on Raspberry Pi 3 (Linux raspberrypi 4.19.118-v7+ #1311 SMP Mon Apr 27 14:21:24 BST 2020 armv7l GNU/Linux).
On the cppreference.com atomic::is_always_lock_free refer... | 1 means "sometimes lock free" in the standard. But really that means "not known to be lock free at compile time".
Without compiler options, GCC's default baseline includes ARM chips so old that they don't support the necessary instructions for atomic RMWs, so it has to make code that could run on ancient CPUs, always ... |
64,242,437 | 64,242,459 | In C++ the fgets() function is not working | why is fgets function not working?
error: C++ argument of type is incompatible with parameter of type
#include <cstdio>
using namespace std;
int main()
{
int indis = 0;
char *g, firma[50];
cout << "firma adı giriniz: ";
fgets(firma, 50, g);
g = firma;
while (g[indis] != NULL) {
cout... | Because you're using it wrong.
fgets is for reading from a file (or stream).
You have no file (or stream).
Did you perhaps mean fgets(firma, 50, stdin);?
Consult some documentation for the functions that you use.
|
64,242,639 | 64,246,407 | c++ lambda with implicit return? | In below code, with c++17 std::find_if, the return in the comparison predicate is necessary.
auto it = find_if(V.begin(), V.end(), [](int i) { return i == 1; });
In situations where the return type of the lambda can be inferred (like here where it acts as a predicate), it would seem logical to be able have an implicit... | There was a proposal for "abbreviated" lambdas with the syntax:
auto it = find_if(V.begin(), V.end(), [](int i) => i == 1);
^^ abbreviated-lambda operator token
However, this was rejected for a number of reasons, chief among them that it would have introduced an inconsis... |
64,243,036 | 64,243,156 | Invoking a method from null pointer in the lambda | Consider this piece of code:
struct A {
bool f() { return true; }
};
// ...
std::vector<A*> v = {new A(), nullptr, new A()};
std::find_if(v.begin(), v.end(), [](const A* object) { return object->f(); });
If we invoke a method from nullptr object, is this an undefined behaviour? If yes and I want to resolve this is... | As per this post, yes, that would result in undefined behaviour.
If you wish to avoid the undefined behaviour, which happens if the code attempts to do something which is not defined by the standard, then yes, you will avoid UB if the code doesn't execute, which can be avoided with a condition.
|
64,243,246 | 64,243,669 | Find a pointer T* in std::unordered_set<std::unique_ptr> (C++20) | As pointed out in Using a std::unordered_set of std::unique_ptr, it is not easy to find a pointer T* in std::unordered_set<std::unique_ptr<T>>. Prior to C++20 we were forced to construct an instance of std::unique_ptr<T>.
Thanks to the Heterogeneous lookup for unordered containers proposals (http://wg21.link/P0919r3 an... | You can shift the verbosity into std::to_address (thanks to @Caleth for pointing that out) and the existing std::hash, which is specialized for std::unique_ptr to return a hash based on the raw address (thanks to @Mikhail for the hint). Then, implement hash and equality types with member function templates (note how yo... |
64,243,264 | 64,243,782 | C++: How can make each of the answers of my calculation program align? | Here's my code:
#include<iostream>
int main() {
int width, length, sq_cm, sq_m{}, sq_in, sq_ft, cm, m, in, ft;
std::cout << "Find the Area and Perimeter of a Rectangle \n\n";
std::cout << "Input the length of the rectangle : \b";
std::cin >> length;
std::cout << "Find the width of the rectangle : ... | To format your text texts try something like this:
using \t to "tab" the output.
And like Sugar sad in the comments, is better to use "\n" instead of endl
#include<iostream>
int main() {
int width, length, sq_cm, sq_m{}, sq_in, sq_ft, cm, m, in, ft;
std::cout << "Find the Area and Perimeter of a Rectangle \n\... |
64,243,316 | 64,244,203 | Pointer-interconvertibility: reinterpret_cast derived to base | When do a base subobject and a derived object have the same address and it's guaranteed by the Standard? Is the standard-layout class object is only the case? Consider the following code:
#include <iostream>
struct InterfaceB { virtual void b() = 0; };
struct InterfaceD1 : InterfaceB { virtual void d1() = 0; };
struct... | No, it would be undefined behaviour to attempt to use a pointer casted in such a manner.
[basic.compound] ¶4
Two objects a and b are pointer-interconvertible if:
[...] one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data member... |
64,243,389 | 64,243,612 | C++ Segmentation fault error when storing integers as int arrays | I'm having a segmentation fault error, and I'm not sure why:
I have this code:
entierlong.h
const int MAXCHIFFRES = 1000;
typedef int tabEnt[MAXCHIFFRES];
struct EntierLong
{
bool Negatif;
tabEnt Chiffres;
};
EntierLong addition(EntierLong n1, EntierLong n2)
{
int retenue,somme,i;
n3 = Convertir(0);
if... | If you have memory allocation issues you can replace your EntierLong type by
struct EntierLong
{
bool Negatif;
std::vector<int> Chiffres;
EntierLong()
{
Chiffres.resize(MAXCHIFFRES,0);
}
};
The constructor will allocate Chiffres array on the heap.
|
64,243,411 | 64,269,541 | GCC: libstdc++.so: Error adding sybols: file in wrong format | I am trying to compile for a gd32v chip using gcc(the riscv version on the arch community repo).
Compiling seems to work fine, however when trying to link the objects into an elf file, I get the error:
Linking ELF target: main.elf
riscv64-linux-gnu-g++ @_linker_flags -o main.elf ../../bmptk-RISC-V/targets/risc_v/gd32v/... | To see exactly the mapping/switches of the libraries supported by your compiler you can use : riscv64-linux-gnu-g++ -print-multi-lib. If you compiler was compiled with multilib enabled you can choose an rv32 libs without hard float otherwise it will not link also since you are compiler for rv32imac.
If your compiler w... |
64,243,493 | 64,243,578 | Hash function result and bucket number in unordered_set | Suppose I have an std::unordered_set<T> mySet initialized with my own hash function hashFunc(T item). What I want to do is first insert some items into mySet, and then have a function search(T item) that takes an item, finds which bucket b it would go if it were to be inserted (but does not insert it) and finally retur... | The bucket method on unordered_set takes a key and returns the bucket index that an element with that key would go into. For example:
#include <iostream>
#include <string>
#include <unordered_set>
int main() {
std::unordered_set<std::string> x = {"foo", "bar", "baz"};
std::cout << "foo: " << x.bucket("foo") << "\... |
64,243,570 | 64,243,647 | I wrote operator* for singly linked list in c++. When I write what function contains in main, it works, but when I call the function, it doesn't | Polynomial& Polynomial::operator*(double k) {
Polynomial result;
Node<double>*current = first;
if (!current) {
throw "Can't do this operation with empty polynomial. /n";
}
for (int i = 0; i < length(); i++) {
result.insertAt(i, k*current->info);
current = current->next... | Polynomial result;
A local variable called result gets defined in this function. Like all other local variables it will get destroyed, and will no longer exist, when this function returns. That's how local function variables work in C++.
return result;
This function is declared as returning a reference on object. Thi... |
64,243,661 | 64,244,661 | call masm function with arguments from c++ code | here is assembler code:
.386
.model flat, stdcall
_asmFunc proto arg1: dword, arg2: dword
.data
.code
_asmFunc proc, arg1: dword, arg2:dword
mov eax, arg1
add eax, arg2
ret
_asmFunc endp
end
and here is c++ code:
#include <iostream>
extern "C" int asmFunc(int, int);
int main()
{
std::cout << asmF... |
The calling convention in the .model directive must match the calling convention in the C function declaration. For the default cdecl calling convention, just use .model flat, c
As a result of specifying the language type in the .model directive, name decoration is performed automatically. This means you should not a... |
64,243,751 | 64,243,856 | C++ Comparing argv[1] with a char of the same value always returns False | I am writing a simple program that compares a single character from argv[] to a character in a char array. This is done using a for loop to check if argv[1] is any of the characters in the character array, which is to serve as an input error check.
What I have done to implement this is below:
#include <iostream>
using ... | argv is an array of char pointers. In order to compare and get the size of the actual value, you'll have to dereference the char object.
For example, to get the size:
if(*argv[1] == '0'){
// Do Something
}
Checks if the first argument(argv[0] is the command itself), is equal to the character '0'. Here I dereferen... |
64,243,813 | 64,247,517 | disable function template specialization or overload with constexpr variable | I have in an upstream library a templated function that I want to specialize:
/// glog/logging.h
namespace google {
template <typename T>
inline void MakeCheckOpValueString(std::ostream* os, const T& v) {
(*os) << v;
}
} // namespace google
I did so by defining in my code
namespace google {
template <>
i... | std::enable_if_t<false> is invalid (for any specialization).
To make it SFINAE friendly, you have to make the condition dependent:
constexpr bool SWITCH = false;
namespace glog {
template <bool b = SWITCH>
std::enable_if_t<b> MakeCheckOpValueString(std::ostream* os, const Duration& v) {
(*os) << v.count();
}
}
|
64,243,814 | 64,283,683 | Outline of pixels after detecting object (without convex hull) | The idea is to use grabcut (OpenCV) to detect the image inside a rectangle and create a geometry with Direct2D.
My test image is this:
After performing the grab cut, resulting in this image:
the idea is to outline it. I can use an opacity brush to exclude it from the background but I want to use a geometric brush in ... | For anyone interested, the solution is OpenCV contours. Working example here.
|
64,243,830 | 64,243,831 | Google Test Adapter in Visual Studio: How to use local build of googletest/googlemock | To use googletest/googlemock in Visual Studio, I installed the Test Adapter for googletest. When creating a new Google Test project, the actual implementation (lib) of googletest is included by a NuGet-Package. The packages.config file shows the name of the NuGet-Package.
Unfortunately, in my case, this is a googletest... | First remove the NuGet-Package from the project by using the NuGet package manager.
Then include paths of the googletest install directory to the project: In VC++ Directories at Include Directories add googletest install dir \include and at Library Directory add googletest install dir \lib. Finally in Linker at Input a... |
64,243,838 | 64,248,008 | The std::filesystem current_path returns the root one | I just wanna to print the current path and its content, via std::filesystem::path::current_path (the compiler is emcc this one). Some code below:
//... some stuff ...
namespace fs =
#if defined(_MSC_VER) || defined(_WIN32)
std::filesystem;
#else
std::__fs::filesystem;
#endif
//... some stuff ...
cfg::Config::Conf... | I found a solution, so it's may be useful to others. Thanks to @Sugar I dug in the Emscripten Filesystem API. The emscripten creates its own virtual filesystem and uploading there files used in c++ code. According to this issue the way to fix it is to add the -s NODERAWFS=1 as flag, whilst compile.
|
64,243,965 | 64,243,990 | How can I convert a vector iterator to an int value to print it? | I keep getting an error while running this code. I've searched for a solution for similar errors, but as a junior programmer, I can't understand solutions meant to be for different codes.
Here is my code. Please give me a solution with demonstration.
#include <iostream>
#include <vector>
#include <numeric>
#include <al... | Iterators mimick pointers. You can dereference the iterator to get the element:
cout << *min_value << endl;
Note that in general algorithms often return end (the iterator you passed as second parameter) to signal that no element was found and then you need to check that you have a valid iterator before dereferencing i... |
64,244,226 | 64,244,706 | Auto is not allowed here for lambda class in header file | I'm using c++14, auto is working fine on .cpp file, however when i try to create generic lambda in my class it generates error "Auto is not allowed here"
What did i do wrong?
Code:
class MyClass{
private:
// Works
std::function<void(MyClass&)> assign = [&](MyClass& other){
//do something
};
//... | Your two attempts fail for different reasons. Let's look at the second one first:
auto assign = [&](auto other){
//do something
};
This could work in theory: the lambda expression has a definite type that could be deduced and used. However, as addressed in this Q&A (for C++11 but still relevant), the language simp... |
64,244,397 | 64,244,934 | How can I create a any-type pointer constant in C++? | I would like to have an integer constant that can be assigned to any pointer. I intend to use this special value to mark recently deleted pointers (just for the debugging purposes). I thought of creating a struct and then overriding the assignment operator= with a template handling every possible LHS pointer and my RHS... | template<typename T> operator T*() will be useful:
struct TPointerConst{
TPointerConst(std::uintptr_t v) :value(v){};
template<typename T>
operator T*() const{
return reinterpret_cast<T*>(value);
}
private:
std::uintptr_t value;
};
int main(){
TPointerConst a = 0xCDCDCDCD;
int* b... |
64,244,421 | 64,244,563 | Allow function of variadic argument count as template function argument | In C++ we can pretty easily define template function arguments as seen in this question. However, this only allows functions with a defined parameter list and return value.
We can make those types template parameters like this:
template<typename R, typename P, R(*Func)(P)>
R proxy_func(P arg)
{
// do some stuff...
... | In some sense, the Q&A you link is the complicated way. The simple way is:
template <typename F>
void foo(F f) {
f(); // call the function
}
In your case the return value can be deduced and the argument types can be deduced from the parameters to foo. Note that they need not necessarily match exactly the argume... |
64,244,578 | 64,244,601 | do while loop that ends when n doesnt equal 1 or 22 | this is my first time posting so I hope that I am doing this right. The instructions for this assignment are
Write a C++ program that implements the following algorithm:
input n
print n
if n = 1 then stop
if n is odd then n <-- 3n+1
else n <-- n/2
goto step 2
Example: given the input 22, the following sequence of num... | n != set1 || n != set22 will be always true because set1 and set22 have different values and n cannot be equal to both of them at once.
Use n != set1 && n != set22 instead of that.
|
64,245,726 | 64,245,871 | Why do I get "use of undeclared identifier" even when using constexr if? | play with the code.
template<typename T>
T f() {
if constexpr (std::is_same<T, int>::value) {
T t = 10;
}else {
T t;
}
return t;
}
My understanding of the above code is that the body of f will either be
int t = 10;
return t;
or
T t = // some default value for T
return t;
depending o... |
My understanding of the above code is that the body of f will either be
int t = 10;
return t;
or
T t = // some default value for T
return t;
No. A more valid comparison is that it will be either, for the true branch:
{
int t = 10;
} // end of scope for 't'
return t; //
or, for the else branch:
{
T t;
}... |
64,245,869 | 64,246,279 | Can I instantiate a member class template with member variables? | class NDArray{
private:
Context ctx_;
typeFlag dtype_;
std::vector<size_t> shape_;
std::shared_ptr<TBlob<dtype_, ctx_.dev_type_, ctx_.dev_id_> > data_;
public:
// constructor
NDArray();
NDArray(const NDArray &obj);
explicit NDArray(const size_t ... | This is the closest thing I can think of to what you want, but I don't know if it will be useful to you. Note there is a slight overhead due to virtual methods. I used a more simple example but it should be more or less equivalent.
#include <memory>
#include <utility>
#include <iostream>
// Base interface class for th... |
64,245,909 | 64,246,027 | Can the class member can be changed depending on the template args in c++ | I want the class member can be changed depending on the template args.
I want something like follow
template<int value>
class MyClass
{
public:
void print()
{
// using the member
std::cout << sizeData() << std::endl;
for (int i=0;i<sizeData();i++)
{
std:cout << data[i] << std::end... | You can use std::conditional to pick which member you would like to have like
template<int value>
class MyClass
{
public:
static int sizeData()
{
return (value == 1) ? 3 : 6; // needs to be improved
}
static int sizeArray()
{
return sizeof(array) / sizeof(array[0]); // size of array divide... |
64,245,966 | 64,246,237 | Use base class interface in templates | I'm supposed to use base-class as a caller:
void use(Base& b)
{
int i = b.size();
b.create();
}
void do()
{
Subclass sub{5};
use(sub);
}
But why shouldn't I use templates to eliminate run-time overhead:
template<typename T>
void use(T& sub)
{
int i = sub.size();
sub.create();
}
void do()
{
... | Do not use this as an optimization. The compiler may perform devirtualization on its own if it sees fit. Use what's appropriated in your code.
That said, nothing prevents you to do that. It may or may not apply to your needs.
For example, if use is a virtual function or a function you need to store the object somewhere... |
64,246,003 | 64,246,209 | Class member access through out of bounds access to array member | I've seen a very experienced programmer do something like:
#include <iostream>
#include <string>
using namespace std;
typedef int BOOL;
BOOL is_max(int a) {
return a&3;
}
class Foo
{
public:
inline Foo() {}
inline ~Foo() {}
int min[3];
int max[3];
};
int main()
{
Foo foo ... | There are two problems, first of all, it is out of bounds access if b is larger then 1 and that is undefined behavior.
Another problem is, that the compiler only sees foo.max[i] = i+3; but has no indication in your code that max is used at any point after that loop. So from the perspective of the optimizer and because ... |
64,246,413 | 64,248,041 | Segmentation fault | calculating factorial | Out of Index | I have been getting this segmentation fault in many problems that I solve on online IDE's, but am not able to completely understand this issue and thus resolve it. Kindly help me with the same.
I understand it can occur due to stack overflow sometimes, therefore, I should use heap memory. But how to do that?
One exampl... | arrLeng crossing the limit of Hardcoded MAX 500.
You should always have a check on the index. It should not cross the MAX limit. This is not the problem of memory allocation on stack or heap.
|
64,246,718 | 64,295,744 | Converting 32 bit dll to 64 bit | I had to switch to Office 64 bit (2019, Professional Plus). I have a large number of VBA scripts and most of them make calls to an old 32 bit dll written in plain C language and compiled with the very old Developer Studio 97. I managed to recompile it with Visual Studio 2019 as a C++ dll at 64 bits and I faced 2 proble... | Finally, thanks to rustyx's intuition, I discovered I was using a "Solution" suitable for "app" development. (The string _APP inside the called dll name indicated just that!) I managed to switch to "Desktop" solution, and now the dll's loaded are without the _APP suffix. The MessageBox function works fine, without the ... |
64,246,737 | 64,247,371 | How inject shellcode loaded from file? | I have a big problem that stuck me and today makes tree days trying solve. How i can load a shellcode from a binary file and inject correctly in a target process? When tested only with shellcode on own source code of program example this works fine.
Why this not works when the shellcode comes from a file? Someone alrea... | It is because you are using sizeof(xcode). In first case it is a string constant with size known at compile time. In your case, the second one, the sizeof (xcode) returns 4 (or 8 depending on architecture). You should use file_size_in_byte instead. See this piece of code:
pointer_after_allocated = (DWORD)VirtualAllocEx... |
64,246,999 | 64,247,080 | casting int * const to long int * const warning | This may well have been asked in some other way before (I would be surprised if its not) but I am struggling to find it if it is.
Given:
#include <iostream>
#include <string>
int main()
{
int * const pi = new int(1);
long int * const pl = reinterpret_cast<long int * const>(pi);
std::cout << "val: " << *pl ... | long int * const is an immutable pointer to mutable data.
reinterpret_cast returns a temporary object. On most temporary objects (including this one), the immutability of the top-level type is irrelevant.
this:
long int * const pl = reinterpret_cast<long int * const>(pi);
is the same as
long int * const pl = reinterp... |
64,247,216 | 64,247,347 | Error making tuple containing a unique_ptr | I am trying to create a function func that returns an std::tuple of an std::unique_ptr<A> and a double. However, when I try to create the tuple I receive errors. The code follows:
#include <tuple>
#include <memory>
class A {
public:
A() : data (3){}
private:
double data;
};
std::tuple<std::unique_ptr<A>, dou... | A std::unique_ptr is not copyable. You are attempting to copy a std::unique_ptr to the tuple, and that will not work. The compiler error message is kind of cryptic, IMO, but that is basically what seems to be the problem.
However, a std::unique_ptr is moveable, thus you can use std::move:
std::tuple<std::unique_ptr<A... |
64,247,376 | 64,247,726 | Convert binary char array without losing leading 0's using C++ | I'm trying to convert an mp3 into a binary fstream (or hexadecimal, I can use both). I've figured out how to open the file and output the contents to the console. But in both binary and hex, the leading 0's are removed. Therefore, if I create a new mp3 from the fstream it will be missing many bits. Any help in preservi... | Probably the easiest way to do this is to use std::bitset to do the conversion.
Oh, and using namespace std; and std::endl are both better avoided. Given that you're reading what you assume to be a binary file, std::getline doesn't really make much sense either. Oh, and error messages should normally be written to the ... |
64,248,054 | 64,249,587 | assignment operator overloading in arrays | I tried the below code but I got error.
I am getting error in that overloading assignment operator..
SO, please do check what my mistake is:
Is my syntax of operator overloading correct?
I want that particular thing to be solved.
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
class comp... | There are many errors in your code.
The reason for most of them is that since you have using namespace std; compiler mistakes your complex with its own complex library so the
In member function 'complex complex::operator=(complex *) [Error] no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostr... |
64,248,111 | 64,248,422 | OpenGL Draw Multiple Vertex Arrays | I want to draw multiple vertex arrays. This is the initialization:
unsigned int va1;
unsigned int vb1;
void init_va1() {
glGenVertexArrays(1, &va1);
glBindVertexArray(va1);
glGenBuffers(1, &vb1);
glBindBuffer(GL_ARRAY_BUFFER, vb1);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(vec2), nullptr, GL_DYNAMIC... | glBufferSubData changes the data of the buffer that is currently bound to the specified target. The current ARRAY_BUFFER is a globale state. you need to bind the proper buffer object when you want to update the data store of the buffer:
glBindBuffer(GL_ARRAY_BUFFER, vb1);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(a1),... |
64,248,131 | 64,249,114 | How to get rid of "Time Limit Exceeded" | I try to solve some problems in a online website. And I've a solved a problem with simple C++ it worked well but it sometime throw a "Time limit exceeded" error. How to get rid of this?
Here is the question that I solved
There are two integers A and B. You are required to compute the bitwise AND amongst all natural n... | If you have two numbers, X and Y, they are represented by a finite sets of bits:
X = Bx(1), ..., Bx(n)
and
Y = By(1), ..., By(n)
The bitwise AND between the two can be computed as
X ^ Y = (Bx(1) ^ By(1)), ..., (Bx(n) ^ By(n))
A B A ^ B
0 0 0
0 1 0
1 0 0
1 1 1
We observe that:
all the bits can be computed ... |
64,248,852 | 64,250,312 | Is there a "clean" way to pass a large number (say, 20+) arguments to a class constructor? | Suppose I have some class, myClass, with a class constructor that takes 20 arguments, and simply assigns the passed values to class variables. Here's a smaller example, in case that's not clear
class myClass{
float a, b, c;
public:
myClass(float _a, float _b, float _c) : a(_a), b(_b), c(_c) {}
};
Is ... | A) The builder pattern
You can use the builder pattern. I am not going to strictly follow the pattern. For official details I refer you to the numerous available online resources on design patterns. The basic idea is that you enable the caller to write instead of
MonsterClass m{ a,b,c, ....... d,e,f };
the nicer
auto... |
64,248,876 | 64,249,390 | Is there a cleaner way to define my copy ctor with a mutex? | I have a POD struct like so
struct foo {
std::mutex m_foo_mutex;
int a;
int b;
int c;
//......
};
It has more fields than this but the structure should be apparent. The default copy ctor is, of course, ill formed because std::mutex's copy ctor is delete.
It's perfectly fine for my uses to copy this object, a... | You could wrap just your mutex in a copyable class:
struct CopyableMutex {
std::mutex mutex;
CopyableMutex() = default;
CopyableMutex(const CopyableMutex&) {};
CopyableMutex& operator= (const CopyableMutex&) {
return *this;
};
};
struct foo {
CopyableMutex m_foo_mutex;
int a;
int b;
... |
64,248,957 | 64,250,449 | c++ get values of an unordered_map of vector of unordered_map | I have a C++ program that has one unordered_map (unmap_graph) with a vector in its value (vector_id_as2), and this vector is another unordered_map (unmap_id_as2) with a vector of int in its value. Look at C++ code below:
typedef unordered_map<int, std::vector<int>> unmap_id_as2;
typedef vector<unmap_id_as2> vector_id_... | You have
typedef unordered_map<int, std::vector<int>> unmap_id_as2;
typedef vector<unmap_id_as2> vector_id_as2;
typedef unordered_map<int, vector_id_as2> unmap_graph;
So looping over an unmap_graph happens in the reverse order:
for (auto& [my_int, my_vector_id_as2] : map1)
for (auto& my_unmap_id_as2 : my_vector_i... |
64,249,022 | 64,249,694 | Parent-Child class relation in C++ with pointers | How should I go about implementing a parent-child relation in c++? I want a parent to have a single active child at a time, but I also want the child to "know" who its parent is.
The child class is abstract and therefore only a pointer to it can be declared in Parent.
Child has a protected pointer to its Parent, but I... | Assuming each Child-derived object will be destroyed when the parent is destroyed, you just need to use a std::unique_ptr<Child>. For convenience, you can provide a set_child function that passes through the pointer to the parent for the child to store, instead of doing it in higher-level code. You might expand that ... |
64,249,489 | 64,250,001 | vUsing a object of a type created in main.cpp in a different .cpp file | I'm trying to use a vector of Node nodes which was created in main. The class Node is also contained in main.cpp. I have a separate .cpp and .h file for my DFS search function (my professor requested it be structured like this). The return type for my function is going to be a vector<Node>, but the compiler can't figur... | Header files
Your main function shouldn't hold the functions/classes but merely control them. The right way is to declare it in a header file and then #include "headerfile.h" in any other place you would like to use them.
Example:
Good practice
headerfile.h
#pragma once
class Entity
{
private:
int num;
public:
... |
64,249,728 | 64,249,795 | Initializing a vector of vectors of ints in C++17 | I have tried creating a vector of vectors in a class with a fixed size using the solution from the following thread but to no avail. Initializing a vector of vectors having a fixed size with boost assign
Since it's 7 years old, I'm thinking it could be something to do with C++17 changes, but I'm unsure where the issue ... | You can use squiggly brackets to let the compiler know you're trying to call a constructor:
std::vector<std::vector<int>> sudoku_field{9, std::vector<int>(9, 0)};
Alternatively, you could do this work in the initialization list of your default constructor:
SudokuSolver() : sudoku_field(9, std::vector<int>(9, 0)) {}
A... |
64,249,832 | 64,295,708 | What is the best way to disable implicit conversion from pointer types to bool when constructing an std::variant? | Consider the following:
struct foo {
};
struct bar {
};
int main()
{
foo f;
bar b;
std::variant<foo*, bool> v;
v = &b; // compiles in Visual Studio 19 v16.7.3
}
As discussed in comments, I believe the above is legal C++17. There is a proposal, P0608R3, that was accepted into the standard addressing t... | I think the cleanest way to handle implicit conversion doing surprising things with respect to variants is to use a "strong variant" type if the behavior of std::variant is a problem; i.e., implement a variant type that enforces construction only using types that are exactly the types in the variant.
It is easy to test... |
64,250,002 | 64,250,301 | Subclass as argument in superclass's member function, C++ | I'm new to OOP and I'm working on a C++ project. I isolated my problem to make answering easy but here's the real scenario:
I have a superclass member function, that modifies values inside the object that called it. The modification is based on a value coming from another object of the same class. This object is given ... | You could make test2 a template, and ensure that it's only used with types derived from Base:
template<typename Derived>
void test2(Derived &example)
{
static_assert(std::is_base_of_v<Base, Derived>);
std::cout << example.getNumber();
}
Here's a demo.
|
64,250,174 | 64,250,413 | Sending a POST using HttpSendRequestA fails with ERROR_HTTP_HEADER_NOT_FOUND? | I'm trying to post data to a test .php script using XAMPP on my local machine, but it always fails with ERROR_HTTP_HEADER_NOT_FOUND. I check the server logs and no request was sent to Apache. I can manually do it via a web browser and the php script runs as expected.
Here's the C++ code that doesn't work. Can someon... | I see two mistakes in your call to HttpSendRequestA():
The value of headers needs to be changed from "application/x-www-form-urlencoded\r\n" to "Content-Type: application/x-www-form-urlencoded".
sizeof(headers) needs to be changed to either -1, sizeof(headers)-1, or strlen(headers). You are expected to pass in eithe... |
64,250,270 | 64,250,682 | How to fix "no operator " != " matches these operands"? | When I ran the below program, it gave me an error:
no operator "!=" matches these operands
The error line is while (infile.get(ch) != 0).
#include <iostream>
#include <fstream>
#include <process.h>
using namespace std;
int main(int argc, char* argv[])
{
if (argc != 2)
{
cerr << "\nFormat:otype filena... | while (infile)
{
infile.get(ch);
cout << ch;
}
I solved with this way
and
while (infile.get(ch))
cout<<ch;
this way.
|
64,250,940 | 64,251,111 | Parameter order in callback function | I was watching this C++Con talk https://www.youtube.com/watch?v=e8SyxB3_mnw&t=2933s&ab_channel=CppCon
where something like the following code was given (https://godbolt.org/z/av4Tbn):
struct Handler {
void handle(int x, int y, int z);
static void callback0(void *instance, int x, int y, int z) {
static_cast<Han... | In callback0(), the arguments are being passed in via CPU registers in the exact order that handle() is expecting them to be, where instance becomes handler's this pointer, so there is no need to rearrange any of values, hence why the jmp is used by itself.
In callback1, the arguments have to be rearranged into the cor... |
64,251,219 | 64,283,386 | UE4 C++ Getting a reference to HUDClass after it has been initialized | In my Game Mode Base class I create an object that is assigned to HUDClass. The HUD works properly but then I cannot seem to access any of its member functions that require sending code back. I have tried absolutely everything at this point and am completely stuck. It seems whatever I do the pointer to the object seems... | I figured out a solution to get a reference to both any actor object and the HUD from within the Game Mode Base class, this works in Unreal Engine 4.25 using C++. After initializing the HUDClass and the DefaultPawnClass using a place that they will be initialized (I personally put them in the Game Mode Base Constructor... |
64,251,365 | 64,251,438 | Why can't I generate all permutations with std::next_permutation? | I'm trying to obtain all permutations of binary values (which, in this case, are represented by integers 0 and 1) using the std::next_permutation from the C++14 STL.
However, I do think that I found a bug in this method.
If the vector has one or more zeros on its end, then one cannot obtain all permutations of the vect... | From the reference:
Permutes the range [first, last) into the next permutation, where the set of all permutations is ordered lexicographically with respect to operator< or comp.
So iterating through the permutations will only give you the lexicographically increasing sequence from the initial range.
Note that the exa... |
64,251,565 | 64,251,642 | C++ How to replace rows and columns in 2D array? | I want to replace rows with columns in 2D array, but that doesn't work. The numbers are different in each of the two arrays.
And also in the second array, on second row, and fourth column there is always this same number (4253936).
How can i write it, so i can replace these rows and columns, without any number getting ... | The methodology you describe is called Transpose, which your code appears to implement.
The "weird" number that you see was because your code was invoking Undefined Behavior (UB), by having one of its indices goes out of array bounds, thus printing a garbage value.
The index that was going out of bounds was j in your ... |
64,251,685 | 64,251,870 | How do I have a const member move-only object without making my object copyable? | #include<algorithm>
#include<vector>
#include<memory>
class Foo {
public:
Foo();
#if 1
// Destructor for rule of 5.
~Foo(){}
// Move constructor yes.
Foo(Foo&&) noexcept = default;
// Move assignment probably won't actually be created because const member variable.
// Do I need it though? Why would v... |
How do I have a const member move-only object without making my object copyable?
Having a move-only member object makes your class implicitly non-copyable, so there is nothing in particular that needs to be done to achieve that.
I get the error
But why?
Because your class is not satisfy the requirements of being M... |
64,252,077 | 64,253,791 | Why can't I declare a concept at class scope? | Consider this code:
struct A
{
template <typename T>
concept foo = true;
};
It doesn't compile. My Clang 10 gives me error: concept declarations may only appear in global or namespace scope, and GCC says something similar.
Is there a reason why it's not allowed? I don't see why it couldn't work, even if the en... | The fundamental difficulty that would arise is that concepts could become dependent:
template<class T>
struct A {
template<T::Q X>
void f();
};
Is X a non-type template parameter of (dependent) type T::Q (which does not require typename in C++20), or is it a type template parameter constrained by the concept T::Q?... |
64,252,680 | 64,252,780 | Passing int as bool argument in C++ | could someone explain what happens in this code:
example here: https://ideone.com/1cFb4N
#include <iostream>
using namespace std;
class toto
{
public:
bool b;
toto(bool x)
{
cout<< "constructor bool:" << (x ? "true": "false")<<endl;
b = x;
}
~toto() {}
};
int main()
{
toto t =... | In this declaration
toto t = new toto(0);
the object t of the class type toto is initialized by the pointer returned by the expression new toto(0). As the returned pointer is not equal to nullptr then it is implicitly converted to the boolean value true.
So in fact you have
toto t = true;
except that there is a memor... |
64,252,801 | 64,253,044 | Is it guaranteed that std::chrono::steady_clock never wraps around? | Basically:
auto p1 = std::steady_clock::now().time_since_epoch().count();
... // do smth for unspecified period of time
auto p2 = std::steady_clock::now().time_since_epoch().count();
assert(p2 >= p1); // is this guaranteed?
?
If yes -- how it this guaranteed? By making sure no C++ program ever runs for longer tha... | Like many things in this topical area, it's complicated...
Yes, it is guaranteed that steady_clock::now() never wraps, as it is guaranteed that it always increases:
http://eel.is/c++draft/time.clock.steady
Objects of class steady_clock represent clocks for which values of
time_point never decrease as physical time a... |
64,253,353 | 64,253,609 | Getting wrong file name while pattern matching in makefile | The directory structure of my project is something like this:
|-build
|-src
|-lib
|-libfile1.hpp
|-libfile1.cpp
|-libfile2.hpp
|-libfile2.cpp
|-libfile3.hpp
|-Makefile(lib)
|-examples
|-pingpong
|-main.cpp
|-ping.cpp
|-ping.hpp
|-M... | The problem is here:
$(LOCOBJECT): $(LOCSOURCE) $(LOCINCLUDE)
mkdir -p $(dir $@)
$(CC) -c $< -o $@
LOCSOURCE contains main.cpp ping.cpp, so this rule makes both source files prerequisites of each target. Whether Make is trying to build main.o or ping.o, the prerequisite list is the same: main.cpp ping.cpp ping... |
64,253,492 | 64,257,571 | How to make a lower class call a method of its parent? | I have followed this turorial Qt Creator + OpenGL and everything is going well.
I have added a QPlainTextEdit on top of the Quit button and I would like to have GLWidget send info back to MainWindow.
How can I make GLWidget call a function of the MainWindow?
Here is some code:
// GLWidget.h
class GLWidget: public QGLWi... | Here is the answer to your immediate question, How to make a lower class exploit a function in it's parent?:
All QObject subclasses hold a reference to their parent object, accessible through the parent() method.
Include the header of the parent's class, e.g Foo.h
Call the parent() methodd to obtain a pointer to the o... |
64,253,510 | 64,253,529 | Nested While Loop Runs Once More Than Expected | I am new to C++ (have been using it for around 2 weeks), and right now I am trying to write a program that will roll a dice and give a random number between 1 and 6, then count how many rolls it takes to get a 6. After that, it will ask user if they want to continue with a positive and exit with 0.
If the input here is... | After reading the value of x, you can compare it to 0 and break out of the loop immediately:
do {
cout << "possitive to continue, 0 to exit" << endl;
cin >> x;
// Add this check
if (x == 0)
break; // if this is reached, the inner `do-while` is not executed
do {
// ...
} while (... |
64,253,605 | 64,482,724 | Windows API for DNS change notification | I am looking for a way to receive a notification whenever the configured DNS server address of a network interface changes, using native Windows APIs (C/C++). For both performance and reaction time reasons, I'd obviously want to avoid polling.
There is, for example, the NotifyIpInterfaceChange API in Iphlpapi.dll. In ... | Actual credit for this answer should go to RbMm, but he's not posting the answer and seems to have gone MIA.
To receive DNS change notifications, the only non-polling solution seems to be using the RegNotifyChangeKeyValue WinApi to monitor for changes under the HKLM\SYSTEM\CurrentControlSet\Services\Tcpip[6]\Parameters... |
64,253,622 | 64,253,649 | C++ 17: How to use parameter packs to clarify the order of parameters in a function which all have the same type | I'm using C++ 17 and want to use template parameters to specify the ordering of the function arguments which all have the same type.
The function has a varying number of arguments and the sorting of these arguments varies too.
I have tried to use the following (simplified) code to which uses parameter packs to implemen... | I have now discovered (after multiple hours) that I was simply missing a typename keyword before the Outers::Inner type.
A functional code is attached below in the hope that it might help somebody in the future:
// Example program
// In .hpp file
#include <iostream>
#include <string>
struct TheInner {};
template<type... |
64,253,865 | 64,254,178 | What's the difference between std::endl and '\n' | I've read the difference between std::endl and '\n' is that std::endl flushes the buffer and '\n' doesn't. However, as far as I know stdout on linux is line-buffered anyway, so does it mean that std::cout << ... << std::endl is the same as std::cout << ... << '\n'?
| std::ostream os;
os << std::endl; // more concise
os << '\n' << std::flush; // more explicit about flushing
Those two lines have the exact same effect.
The manual flushing is often a waste of time:
If the output stream is line-buffered, which should be the case for std::cout if it connects to an interactive termina... |
64,254,023 | 64,254,065 | What's the meaning of "C6993: code analysis ignores OpenMP construct" in omp? | I am using omp with visual studio 2019 and c++. But it keeps giving me the hint "C6993: code analysis ignores OpenMP". Does that mean omp will run the program in a single thread? Why? Following is the code. I have measured the time before and after I add omp, it does seems to run in parallel, then why it gives me the c... | Microsoft describes this warning as follows:
This warning indicates that the Code Analyzer has encountered Open MP pragmas that it cannot analyze.
At least as I read it, this means the code should still run in parallel, but the Code Analyzer (a sort-of separate thing) doesn't understand the OpenMP pragmas, so it isn'... |
64,254,275 | 64,255,215 | How should I solve this c++ sorting problem | #include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string.h>
#include<map>
#include<functional>
using namespace std;
map<string, int> m;
vector<pair<pair<string, int>, int>> v;
vector<pair<pair<string, int>,int>> v3;
vector<pair<pair<string, int>, int>> v2[1001];
int N;
int idx;
bool cmp(... | The comparison functions cmp2 and cmp3 have undefined behavior - they don't return a value for every input. So, they won't really sort the vector.
I suspect you might be trying to use all three comparison functions together, but they are actually completely re-sorting it 3 different times. You need to put the entire be... |
64,254,285 | 64,254,490 | C++ templated subclass arguments to templated function | I have a free function that I would like to overload/specialize for a large number of possible types, plus a degraded "fallback" using a template. Some of the classes I want to pass as arguments are themselves templates, or are descended from template-classes.
My problem is that compilation is favoring my fallback temp... | You can constrain the specialization to exactly accept template types that are derived from Alice with the same template parameter:
// specialization
template <typename T, template<typename> typename Child>
typename std::enable_if_t<std::is_base_of_v<Alice<T>, Child<T>>, char>
bar(const Child<T>& e) { return 'E'; }
... |
64,254,440 | 64,257,462 | Custom istream operator always returning false | I have this issue where my custom overloaded >> operator always evaluates as 'false' when I check for success. I think it may have to do with the fact that my istream is infact a redirected ifstream (meaning I passed an ifsteam to the isteam), though I'm unsure how to solve it.
Here's the code snippet, simplified as mu... | You have a couple of issues.
while(std::getline(is, random.my_str));
will always keep reading and discarding lines until it encounters an error. This may be what you intended but seems odd? After this loop the stream will be in a failed state (normally with eof set).
is.setstate(std::ios::failbit);
correctly sets the... |
64,254,569 | 64,254,895 | Invalid data after load executable file to char vector | I'm trying load a executable file (.exe) in a vector<char> but never is loaded complete data, only MZx string. How fix?
vector<char> buffer;
ifstream infile;
infile.open("putty.exe", ios::binary);
infile.seekg(0, ios::end);
size_t file_size_in_byte = infile.tellg();
buffer.resize(file_size_in_b... | Given vector<char> buffer then buffer.data() returns a char*. Consequently ofs << buffer.data() is sending a char pointer to the stream. The << overload for a char pointer handles it as a string - a sequence of characters that end with a null terminator. That isn't what you want for handling an arbitrary set of bytes (... |
64,254,764 | 64,254,991 | c++ deciding the dynamic template type | Inside a template function, is there any way that I can tell the type of the template being used. I'd like to do something as follows:
For example:
template <typename T>
void function(T t) {
if (T instancof int) auto object = IntObject();
else if (T instanceof string) auto object = StringObject();
}
Int... | Looks like all you need is to make a CreateObjectWithKey template function, then add some full specialization to it.
template <typename T>
auto CreateObjectWithKey();
template <>
auto CreateObjectWithKey<int>() {
return ObjectWithIntKey();
}
template <>
auto CreateObjectWithKey<std::string>() {
return ObjectW... |
64,255,056 | 64,259,514 | writing file bytes to a file client side c++ | I have a server (python) that sends bytes from a file to a client in c++. I am using libcurl to make requests to the python server and flask to do all of the "hard" work for me in python. After i get the file bytes from the server, i want to write it to a zip file on the client side. Initially, i was going to use libcu... | The third parameter in fwrite is a count of items to write. So sizeof doesn't seem to be the thing you need. response_information.first.c_str() is a pointer, so sizeof(response_information.first.c_str()) returns a pointer size. Here it should be:
fwrite(response_information.first.c_str(), sizeof(char), strlen(response_... |
64,255,216 | 64,255,468 | How to not repeat the if statements and allow it to look them up somehow? I am very new, im sure this is basic | I am very new and was wondering if there was a way to make the code look up the if statements rather than having to copy and past them
Also any other tips on how to clean this up is much appreciated, not a serious project just playing around and trying to learn
This code is done on mbed using Nucleo board to get the ou... | you could always make a void function like this before the main function, this will let you call it, run what ever is inside and then return back to the main function.
void play(){
if( greenLED == 1 ){
buzz.playTone("C");
}
if( blueLED == 1 ){
buzz.playTone("D");
}
if( redLED == 1 ){
... |
64,255,315 | 64,257,650 | C++ Invalid New Expression Of Abstract Class Type | I get this error when using c++. I tried other solutions such as using a shared pointer but with no avail. Here is my code :
Main.cpp:
int main() {
game_init();
cout << items.at(0).name << endl;
while(true) game_tick();
return 0;
}
Item.h:
#ifndef ITEM_H
#define ITEM_H
#include "../Rooms/Room.h"
#incl... | You are trying to instantiate a class (Item) with a pure virtual function (use). This is not allowed. To fix this you could
Create a subclass that implements the use function and then instantiate that subclass instead of Item.
Make the function virtual but not pure virtual, i.e., remove the = 0 and then provide a defa... |
64,255,322 | 64,255,689 | Struct does not provide a subscript operator | I'm trying to loop through my adjacency list in my DFS search class, but its giving me this error: type 'AdjList' does not provide a subscript operator. I feel like it might be the way i saved adjList constructor for DFS but I'm not sure. I saw other solutions saw it has to be passed as a pointer so I changed AdjList l... | When you say adjList[i], C++ looks for an operator[] in the type of adjList which is AdjList. As this type doesn't have such a member function you get the error message that it's missing.
Supply a
std::list<Node>& operator[](std::size_t i);
std::list<Node> const& operator[](std::size_t i) const;
and return adjList[i] ... |
64,255,333 | 64,255,471 | (Issue With Nested For Loop) Multiple Column 2 Per Column 1 | I can't figure out how to implement THIS PARTICULAR nested for loop (I have used them before for a similar task). I need 4 user inputs (range of length and radius) and then I have to display a table of calculated values like so:
Radius Length Volume Area
1 1 *.** *.**
1 2 *.** *.**
1 3 ... | I think what's tripping you up is trying to reason about this in terms of rows and columns. The loops you need don't map to rows and columns so I'd throw that mental model out. This problem's easier if you work directly with radii and lengths.
The trick with nested loops is that for each iteration of the outer loop you... |
64,255,459 | 64,255,878 | C++ Numerical Input Validation | I'm used to Python and I'm now learning C++ which is a bit more complicated to me. How can I modify the input so that it fits the description in the comment at the top of my code? I tried to include if (input[0]!='.' &&...) but it just returns 0. I want it to be included as part of the number. Same with the characters ... | Writing parsing code is tricky. When parsing, it is easy to make a mess of the control flow. I suggest dividing up the I/O from the validation code: make a separate function bool IsVaildInt(const std::string& s) that returns whether s is a valid input, and do the prompts outside in a calling function.
It helps to think... |
64,255,461 | 64,255,550 | display all the Prime numbers which are less than certain number | I've been learning C++ for few weeks, however, I got stuck, I have a function isPrime(), works great to show if the number is prime or no, I need to display all the Prime numbers which are less than 200. But it's not working see line marked with comment
#include <iostream>
using namespace std;
// Function Prototypes... | You added the loop in the wrong place. That function is only for checking a particular number. Either you would need to make another function to print all the prime numbers which are less than 200 or you can directly add the loop in the main() function, like i did.
#include <iostream>
using namespace std;
// Function ... |
64,255,497 | 64,255,609 | Does using the * operator on a pointer create a copy? | I've been curious about this for some time. Say we have the following cases for accessing a data member of a class stored in dynamically allocated memory:
class C {
public :
C() = default;
int a = 4;
}
int main () {
C * ptr = new C();
std::cout << "pointer->::" << ptr->a << std::endl;
std::cout... | In both C and C++, *p (dereferencing) and p->m (member access through pointer) are "lvalue expressions". An lvalue "evaluates to the object identity". *p or p->m does not (by itself) create a copy, it refers to a variable that already exists.
|
64,255,549 | 64,255,712 | Undefined behaviour when entering `char` for integer variable with `std::cin` | I have this while loop, just to check if the entered number is 2. If the user entered by accident a letter instead of a number the loop goes to infinity even though I've added isdigit, but didn't fix the loop from going crazy if the input is a character. This is code:
int num1;
bool cond {false};
while(!cond){
cout... | I would suggest trying something a little more straightforward instead of your current code:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int num1;
cout << "Please enter the number 2:";
cin >> num1;
while (num1 != 2)
{
cin.clear(); //Clears the error flag on cin.
... |
64,255,931 | 64,257,170 | Why doesn't std::enable_shared_from_this use a mutable std::weak_ptr? | I understand that most std library implementations choose to implement std::enable_shared_from_this by storing a std::weak_ptr in the base class. This leads to the following:
#include <memory>
class Foo : public std::enable_shared_from_this<Foo>
{
public:
std::shared_ptr<Foo> GetSharedBar() const
{
// ... | These both fail to compile:
class Foo : public std::enable_shared_from_this<Foo>
{
public:
std::shared_ptr<Foo> GetSharedBar() const
{
// error: could not convert from 'shared_ptr<const Foo>' to 'shared_ptr<Foo>'
return shared_from_this();
}
};
class Bla
{
public:
Bla* getThis() const
... |
64,256,032 | 64,256,161 | Changing the rotation point along with object moving in OpenGL? | I'm trying to build a hammer weapon that can move along with the X-axis and rotate around Z-axis. Right now I have a problem with the hammer. The hammer can rotate around Z-axis on a fixed pivot point, but when I move the hammer to a new position then I rotate the hammer, the hammer still rotates around the old pivot p... | You have to move the pivot, too:
float pivot_x = 0.5f + xr;
glTranslatef(pivot_x, 1.0f, -1.0f); //Back to original point
glRotatef(zr, 0.0f, 0.0f, 1.0f); //Rotating
glTranslatef(-pivot_x, -1.0f, 1.0f); //The rotation piovt point
|
64,256,141 | 64,256,279 | Is there any other way to make pascal triangle? | I'm trying to print out the pascal triangle.
and this is a normal one
int pascal(int l, int n) {
if (l == n || n == 0)
return 1;
else
return pascal(l - 1, n) + pascal(l - 1, n - 1);
}
but I want to use only one pascal function for recursion like
int pascal(int l, int n) {
return pasc... | Yes, you can do by memoization because there is an overlapping subproblem.
int pascalTriangle(int row, int col) {
if (col == 0)
return 1;
if (row == 0)
return col;
return row * pascalTriangle(row - 1, col - 1) / col;
}
|
64,256,166 | 64,256,200 | Does list::insert break the iterators in c++? | If i have:
std::list<int> mylist = { 3 };
auto it = mylist.begin();
but i start to do a lot of adds:
mylist.insert(it, 5); mylist.insert(it, 7);
is there any possibility that it could be breaked? (for example, by realocation of the std::list) what about push_back? can this other function make a pointer invalid?
| There's no reallocation for std::list; insert won't invalidate any iterators, and same for push_back.
No iterators or references are invalidated.
|
64,256,401 | 64,260,167 | Drawing a sphere with OpenGL | Can someone please tell me which part of the code I'm messing up?
In glDrawElements, I got like only 1/3 of the sphere with "indices.size() / 3" , which was how most tutorial was conducted, but when I tried indices.size(), I got segmentation fault and nothing showed up.
vector<GLfloat> vertices, normals, texCoords;
vec... | The correct is indeed indices.size() / 3, because you must pass the number of triangles, not the number of indices.
The correct is indeed indices.size(), because you must pass the number of elements in the array you are passing. I don't know why the tutorials you saw used / 3 variation.
As to the problem of the missing... |
64,256,501 | 64,257,139 | How to get a list of Window Rectangle from EnumChildWindow and store them? | I used EnumChildWindows and I can get the Handle, ClassName and WindowText of all the child windows. But I also want to get all the child windows' Rectangle. Is it possible?
This is my code:
#include <iostream>
#include <windows.h>
using namespace std;
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
char... | For your first question, you may have a look here.
For your second question, you may define a structure with the fields you need, e.g.
#include <iostream>
#include <windows.h>
#include <vector>
struct MyWindow {
HWND handle_;
std::string name_;
std::string text_;
RECT rect_;
MyWindow(HWND handle, const std::strin... |
64,256,538 | 64,257,354 | Pass string literal to the function argument which constructor only takes std::string_view | Suppose I have an object only has std::string_view constructor:
struct OnlyStringViewCtor {
std::string str_;
OnlyStringViewCtor(std::string_view str) : str_(str) {}
};
and there is a function that takes const OnlyStringViewCtor& as parameter:
void f(const OnlyStringViewCtor&) {}
when I call f("hello") directly t... | As the other answer explained, the compiler won't do multiple implicit conversions.
But, you can use a template to bridge the gap:
struct OnlyStringViewCtor {
std::string str_;
template<typename T, std::enable_if_t<std::is_constructible_v<std::string, T>, int> = 0>
OnlyStringViewCtor(T str) : str_(str) {}
};
htt... |
64,257,564 | 64,257,780 | Why does the C++ optimizer use different delete when deleting the same pointer | I've come accross a strange issue when gcc 7.3 optimizes some code I'm using from the google test library. The issue's been fixed in google test but I'm still puzzled by the question: are there more global delete operators with the same signature for some reason?
My code is here: https://godbolt.org/z/86Eevc and what's... | The explanation is simple: you invoke undefined behaviour (dereferencing a null pointer) and thus anything can happen. A tell-tale sign for this kind of thing is that optimization level influences the result as you note.
The address you are seeing is rubbish in both cases. As to why exactly they are different, you'll n... |
64,257,615 | 64,257,770 | C++20 concept syntax - what does the requires parameter variables mean? | Many articles give examples like this:
template<typename T>
concept Equal = requires(T a, T b) {
{ a == b } -> std::same_as<bool>;
};
Does it make any difference if I write:
template<typename T>
concept Equal = requires(T a) {
{ a == a } -> std::same_as<bool>;
};
If it doesn't, why was the syntax designed lik... |
Why do they ask me to declare these variables like a or b? Why not even something like..
You aren't asked or required to use the variables. You are given the option because it's much more readable. There's little difference, as far as checking the constraints goes.
The reason the articles give examples like that one ... |
64,257,714 | 64,257,811 | How does the C/C++ compiler distinguish the uses of the * operator (pointer, dereference operator, multiplication operator)? | How, in C and C++ languages, can the compiler distinguish * when used as a pointer (MyClass* class) and when used as a multiply operator (a * b) or when is a dereferencing operator (*my_var)?
| It depends from the context in which it is used, for a simple resolution it looks at the left and right word to understand what a symbol is.
The language's syntax is defined by a tree of grammatical productions that inherently imbue a priority or "precedence" to the application of certain operators over the application... |
64,258,182 | 64,258,260 | How can return json string when value contains quotation mark (") | Imagine that I have this json:
{
"a":"b"
}
If I have a function in C++ that returns this json in string format, such as std::string getjson(), it would return stringified version of this json like:
"{\"a\":\"b\"}"
To be complete:
std::string getjson()
{
return "{\"a\":\"b\"}";
}
myfavourite_jsonparser.parse(ge... | Just as you escape a quote with a backslash (\" results in "), a backslash can be used to escape backslashes as well. So \\ results in \.
So if you want to output \", then escape like this: \\\".
|
64,258,557 | 64,275,160 | Access violation error while attempting to transfer a large file using HTTP / REST server | Using a REST library, I am trying to set it up as a file sharing server, but am running into issues when transferring large files.
As I understand it, the file transfer should mean opening a stream to the file, getting its buffer in a stringstream,then write it within a response body. This seems to work with small file... | The root cause of this error was std::fstream not reading the entire file because it was opened in text mode. In windows, this makes reading stop at a end of file (0x1A) character.
The fix is to open the file in std::ios::binary mode.
|
64,258,707 | 64,265,877 | Need help to optimize dynamic programming problem solution |
The problem statement:
Given two arrays a and b with sizes n and m respectively. All numbers in these arrays are in the range of 0 to 9 inclusive. Lets create a matrix with size of n x m where values in row i and column j is equal to ai * 10^9 + bj. Find the path from square 1,1 to n,m with the maxium sum. You're allo... | It's possible to solve this problem without dynamic programming, and with O(n+m) memory and time requirements.
As pointed out by @Botje in the comments, the reward for higher values in a is overwhelmingly large. An optimal path will therefore remain in the leftmost column until it reaches the largest value in a (which ... |
64,258,996 | 64,278,514 | Libtorch C++ - no matching member function for call to 'size' for InterpolateFuncOptions | Using Libtorch 1.6.0 in C++, I get the following error:
error: no matching member function for call to 'size'
My line is the following:
image = F::interpolate(image, F::InterpolateFuncOptions().size({target_height, target_width}).mode(torch::kNearest));
But in the documentation it seems correct... Any idea?
Thanks in... | You should wrap it with std::vector like this:
image = F::interpolate(image,
F::InterpolateFuncOptions()
.size(std::vector<>{target_height, target_width})
.mode(torch::kNearest));
Reason for this is size has no overloaded call for std::initializer_list that you were trying to use (see size doc... |
64,259,306 | 64,259,433 | Address of This changes during execution. why? | As you can see, from my output results, the address of this changed during execution for me, I thought I could make use of Pointer comparison for achieving a Tree system without having a child list inside Node and I want to be able to compare parent for each element inside a nodo list for further functionality. but the... | If you add an element to the vector and the resulting size exceeds its current capacity, the vector needs to allocate more memory. It allocates a new memory block and moves all existing elements into this memory block, then adds the new element. The old memory block is then freed.
If you want to have stable adresses, y... |
64,259,329 | 64,259,392 | How to make CMake use clang for CUDA to support c++17 | According to this question, it is possible to use c++17 with cuda by using clang. However, I couldn't find how to setup CMakeLists.txt to accomplish this.
I enable c++17 with
add_compile_options(-std=c++17)
Out of the box with the following
enable_language(CUDA)
nvcc complains
nvcc fatal : Value 'c++17' is not... | Try
set(CMAKE_CXX_STANDARD 17)
|
64,259,334 | 64,259,789 | How to save a file with different extension according to Boolean value | I want to save files according to the value of a Boolean I have in my program. if Boolean true extension must be (".me") and if false extension will be (".you").
I am using this line of code to filter my extensions:
QString Save = QFileDialog::getSaveFileName(this, "Save File to:", QDir::currentPath(), tr("DIAG (*.me *... | You can do it like this:
QString save = QFileDialog::getSaveFileName(this, "Save File to:", QDir::currentPath(), bool_value ? tr("DIAG (*.me)" : tr("DIAG (*.you)"));
|
64,259,413 | 64,259,497 | Combining predicates in a functional way | Does Boost Hana provide a way to combine predicates with logical operators?
I'm referring to something roughly like this
constexpr auto both = [](auto&& f, auto&& g){
return [&f,&g](auto&& x){ return f(x) && g(x); };
};
that could be used like this:
int main() {
std::vector<int> v{1,2,3,4,5,6,7,8,9,10};
au... | You could use demux like:
auto both = hana::demux(std::logical_and<bool>{});
// Or for any number of predicates
auto all = hana::demux([](auto const&... x) noexcept(noexcept((static_cast<bool>(x), ...))) { return (true && ... && static_cast<bool>(x)); });
ranges::views::remove_if(v, both(less_than_7, more_than_3));
|
64,259,619 | 64,260,009 | How to add include directories to a swig cmake target without adding them globally? | How do you specify include_directories for a swig target in cmake? I see that to add a swig target you do:
swig_add_library(swg_target
TYPE STATIC
LANGUAGE python
SOURCES swg_src_files.i swg_src_files.h swg_src_files.cpp
)
but following this with the usual
target_include_directories(swg_target... | Under the hood, swig_add_library must eventually invoke add_library and set some properties, but there is something curious in the documentation:
Target library properties can be set to apply same configuration to all SWIG input files.
SWIG_USE_TARGET_INCLUDE_DIRECTORIES
If set to TRUE, contents of target property INC... |
64,260,019 | 64,260,193 | How a child thread can kill another child thread of same process in cpp | Let's say we have the parent thread Tp which starts two child threads Tc1 and Tc2 in the same order and waits for Tc2 to join (Tc2.join()).
Tc2: It starts and waits for the user input by invoking a shell.
Tc1: It starts and runs a time counter and after a specified time if no input is given by the user in Tc2 child thr... | Although some Operating Systems allow violent termination of threads, this is almost always a bad idea. This is because threads share memory and you have no idea what a thread is doing at the moment of termination. There is a good chance of deadlock, memory-leaks and crashes.
What you do need is a way to ask a thread t... |
64,260,301 | 64,370,435 | Returning pointer to intent(in) argument | I try to better understand the difference between const from C/C++ and intent(in) in Fortran in the context of classes.
C++:
If I const the implicit this argument to a member function and I return references to members of this, these references have to be const T*.
So the const does not only apply to the scope of the f... | After reading the comments and answers regarding the C++ part of my question and consulting the Fortran 2008 standard, I think I can answer my own question:
C++:
It is not possible (without hacky tricks like const_cast) to create a T* pointer or T& reference to a const T variable of type T. The pointers/references have... |
64,260,878 | 64,260,956 | Easy way to check whether there is data pending in istream | Is there any standard, non-reading way to check if there is any char pending in the input stream? I can always try something like
char buffer[256];
std::cin.get(buffer, 256, '\n');
if (!std::cin.fail()) {
// use buffer
}
but it condemns me to playing with ios flags, using C-strings and so forth. Isn't there any simple... | The function peek is the solution.
As said by the cppreference:
If good() == true, returns the next character as obtained by
rdbuf()->sgetc()
Otherwise, returns Traits::eof().
|
64,260,888 | 64,261,105 | C++20 converting between string/u8string and string_view/u8string_view | C++20 introduced char8_t and accordingly u8string, u8string_view etc. for mainly supporting cleaner interfaces and better differentiation between narrow execution and utf-8 character sets.
One of the downsides is that the old code might not work any more.
Say I have interfaces which work with utf-8 encoded std::string ... | char8_t has the same size and alignment as char, and is implicitly convertible.
Instead of casts and c_str(), just use the iterator constructor.
u8string u8s = u8"test";
string s(u8s.cbegin(), u8s.cend());
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.