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 |
|---|---|---|---|---|
70,486,437 | 70,486,469 | Equivalent in C++ of an array with unidentified length | Let us consider this line of code in C# :
int[] int_array;
What is its equivalent in C++?
Is it : int* int_array ?
| The equivalent in c++ is
std::vector<int> int_array;
|
70,486,532 | 70,487,027 | Unable to have 100 factorial with C++ on output screen(displaying 0) | Well I am stuck on this problem for quite a while:
Question:
You are asked to calculate factorials of some small positive integers.
Input:
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output:
For each integer n given at input, display a... | A 64bit integer will overflow with 23!
Therefore you need to do it with digits and a vector.
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 23!.
The answer wil... |
70,486,544 | 70,486,602 | CRT Detected that the application wrote to memory after end of heap in C++ | I have created a class of MyString. My code was working just fine but when I wrote the destructor for my class it is giving me the error at delete keyword. Please help me out where is the problem and what is the solution.
MyString Header File
#pragma once
#ifndef MYSTRING_H
#define MYSTRING_H
class MyString
{
private... | length = 0;
str = new char[length];
The Golden Rule Of Computer Programming states: "your computer always does exactly what you tell it to do instead of what you want it to do". Here, this is exactly what you told your computer: allocate an array with 0 bytes. In other words, an empty array that does not contain anyth... |
70,486,582 | 70,486,680 | Overrided method calling from base class c++ | I have 2 classes as NumberArray and PrimeNumberArray. PrimeNumberArray is subclass of NumberArray These classes have generate methods which generate array with random numbers. And I call these methods in NumberArray class. In main method I create PrimeNumberArray object and call the method "generateAndPrint" which shou... | The code below should get you started:
Make generate virtual void generate() in base class, and virtual void generate() override in derived class.
Create heap instances of PrimeNumberArray but assign them to NumberArray pointers; you can use smart pointers for this so you don't need to manually free the instances.
The... |
70,486,719 | 70,486,747 | How to call the function that accepts std::istream& | I am a beginner in C++. What is the correct way to call a function that expects std::istream&?
Tried it with read(std::cin);, but I get an error from the compiler.
typedef double Element;
template<typename T>
std::list<T> read(std::istream& i) {
Element input;
std::list<Element> l;
while(i>>input) {
l.push_... | This is not related to the std::istream& parameter.
The issue is that the function is a function template that requires an explicit template argument determining the type that is supposed to be read from the stream, e.g.:
read<int>(std::cin)
The error message from the compiler should be telling you something like that... |
70,486,930 | 70,487,270 | passing a lambda to a constructor while capturing variables | I have a compile-time error if I pass a lambda while capturing a variable.
Solutions out there are bound and tied to a specific class but essentially it's a use case with 1 to many class types (Observees). It's a kind of polymorphism.
Edit Richard in the comments pointed out the reason but I wonder if there's a workaro... | The first comment fundamentally answers your question:
A capturing lambda is not convertible to a function pointer unless the capture list is empty.
By using a std::function<void(int)> instead of a function pointer, this limitation is resolved.
#include <functional>
class Test {};
class AnotherTest {};
class Observer... |
70,487,013 | 70,487,093 | How is this object's destructor being called two times? | Can someone please explain how test1 is getting destroyed 2 times? Compiled with Visual Studio C++17
class test {
public:
test(int val):val_(val) {
cout << "test" << val_ << "constructor called\n";
}
~test() {
cout << "test" << val_ << " destructor called\n";
}
int val_;
};
int main... | The general implementation of swap is as follows:
template<typename T>
void swap(T& x, T& y) {
T tmp = std::move(x);
x = std::move(y);
y = std::move(tmp);
}
There is a temporary variable tmp, which is destroyed when it leaves the scope of swap.
Since it is initialized by x at the beginning, its value is 1, and ... |
70,487,105 | 70,487,133 | Deleting dynamic elements in a vector | I have a program that has a vector. The vector takes pointers to an object which I dynamically create in my program. I then wish to delete these dynamic objects from the vector. For example:
int main()
{
vector<Account*> allAccounts;
auto timeDone = chrono::system_clock::now();
time_t transactionTime = chro... | What you are doing is fine (assuming Account has a virtual destructor) and there is no memory leak. The size of the vector is not affected by deleting the pointers you store in it.
The destructor needs to be virtual to not cause your program to have undefined behavior.
I would recommend storing a smart pointer like std... |
70,487,499 | 70,487,716 | Need help, How to convert bool type data in C++ WriteFile()? | I'm having trouble rewriting files, I'm getting this error. maybe someone can tell me how to convert the datatype so that the file can be rewritten
.\wInaPi.cpp: In function 'INT main(INT, CHAR**)':
.\wInaPi.cpp:30:54: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
30 | PIMAGE_DOS_H... | I do not know what file_read is, but the compiler tells you that:
you should not try to cast it to PIMAGE_DOS_HEADER;
WriteFile needs a pointer as a second parameter: WriteFile( PEFile, &file_read,....
[Edit - new information added to the question]
file_read is the result of ReadFile which is a BOOL (success or fail... |
70,487,643 | 70,487,797 | Friend Function cannot access private members in C++ | I have created class and trying to overload ostream operator using a friend function but my friend is not able access private members of functions. Please help me figure out the problem. I have created another friend function named doSomething() from here I can call private member but not from overloaded function. Plea... | There are 2 problems with your code.
Mistake 1: You have not included iostream in MyString.h
Solution to mistake 1
MyString.h
#pragma once
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream> //ADDED THIS
class MyString
{
char* str;
int length;
public:
MyString();
MyString(const char*);
~MySt... |
70,487,931 | 70,488,073 | Arduino serial read and check | I am trying to learn some things about arduino serial reading from a bluetooth device. This is the code I found everywhere:
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only whe... | I think it is due to the usage of "r" instead of 'r'. The difference is that in first case you have string, which is char[], and in the second you have single char.
|
70,488,182 | 70,488,302 | How to pass an empty span object? | Is there a way to pass an empty std::span<int> to a function?
I have a function like below:
bool func( const std::vector<int>& indices )
{
if ( !indices.empty( ) )
{
/* do something */
}
...
}
// when calling it with an empty vector
const bool isAcceptable { func( std::vector<int>( 0 ) ) };
... | std::span's default constuctor is documented as:
constexpr span() noexcept;
Constructs an empty span whose data() == nullptr and size() == 0.
Hence, passing a default constructed std::span<int>() is well-defined. Calling empty() on it is guaranteed to return true.
Does std::span properly support all contiguous cont... |
70,488,184 | 70,488,220 | Strange behavior of reference in c++ | I'm little confused about reference type in c++, here goes my code snippet.
class data
{
public:
std::vector<int> Get() const
{
return vec;
}
private:
std::vector<int> vec = {1,2,3,4};
};
int main()
{
data dat;
auto const& a = dat.Get()[1];
auto const& b = dat.Get()[2];
std::cou... | You return a copy of the vector, as the signature
std::vector<int> Get() const
implies, as opposed to
std::vector<int> /*const*/& Get() const
which would return a reference, this is true, but that doesn't really explain why returning a copy is a mistake in this situation.
After all, if the call was
auto const& v = da... |
70,488,236 | 70,488,627 | How do i make a function with a variable number of parameters? | I have a function:
vector<int> prime(int num, ...) {
vector<int> mas;
va_list args;
va_start(args, num);
for (int i = 0; i < num; i++) {
int v = va_arg(args,int);
if (isPrime(v)){
mas.push_back(v);
}
}
cout << endl;
va_end(args);
return mas;}
It should detected prime numbers.
But when i call it, ... | First of all Variadic arguments from C are considered a bad practice in C++ and should be avoided.
There are plenty of better C++ solutions which are able to replace this C feature.
Old fashioned std::vector:
std::vector<int> filterPrimes(std::vector<int> a) {
auto end = std::remove_if(a.begin(), a.end(), [](auto x... |
70,488,470 | 70,537,160 | How to ignore compiler warnings for macros defined in third-party headers? | Currently it's possible to tell the compiler to ignore warnings from a given header by considering it a "system header", including the header via -isystem /path/to/dir.
However, this still won't work if the warning stems from a macro defined in such a header. Is there any way to ignore warnings also for macros? I'm mos... | The issue seems to be simply a bug in GCC/Clang. In general, warnings are expected to be ignored when coming from system macros, and most of them are ignored. I just happen to have come across very concrete use cases where the warning is not ignored.
In case someone is interested in the GCC issue, here's the bug report... |
70,488,711 | 70,508,398 | Create opengl context in SDL and C++ using singleton pattern | I'm trying to create a simple window with SDL and OpenGL using singleton pattern, but when I execute the code appears a white window and the usage of VGA does not increase also, any of the error handlers get nothing which means everything worked well.
Here when I take off the SDL_GetError comment I get the following er... | On the render function, I just needed to change the SDL_GL_SwapWindow reference that was SDL_GL_SwapWindow(window) that was referring to the window of the class StartScreen to SDL_GL_SwapWindow(SDL_GL_GetCurrentWindow()). I believe the reference has been lost since this function it's just used in other class (Manager)... |
70,489,004 | 70,489,108 | Overloading member operator,? | #include <iostream>
#include <vector>
struct Matrix;
struct literal_assignment_helper
{
mutable int r;
mutable int c;
Matrix& matrix;
explicit literal_assignment_helper(Matrix& matrix)
: matrix(matrix), r(0), c(1) {}
const literal_assignment_helper& operator,(int number) const;
};
s... | const literal_assignment_helper& operator,(int number) const;
The comma operators, both in the helper and in the Matrix, return a const reference. So to call a member on that reference, the member function/operator has to be const qualified.
If you remove all the constness, like
literal_assignment_helper& operator,(in... |
70,489,061 | 70,724,051 | undefined symbol: _PyThreadState_Current when using pybind wrapped C++ code | When I'm running bazel test ... the cpp code will compile, but Python gets stuck.
I read these before I wrote this question, but I can not find any solution:
https://github.com/pybind/pybind11/issues/314
undefined symbol: _PyThreadState_Current when importing tensorflow
https://github.com/carla-simulator/ros-bridge/iss... | There were two problems:
the first parameter of the PYBIND11_MODULE macro must be the same as in the pybind_extension
this environment variable must be set to: PYTHON_BIN_PATH=$(which python3)
fixed example
# BUILD
load("@pybind11_bazel//:build_defs.bzl", "pybind_extension")
pybind_extension(
name = "new_math",
... |
70,489,194 | 70,490,220 | Is it "correct" to specify class-member mutex 'mutable' for the purpose of much-more 'const' member functions? | In many cases, many member-functions could be specified 'const' - they don't modify any data-members of the class ...almost: they do lock/unlock the class mutex. Is it a good practice to specify, in that case, the mutex 'mutable'? ...otherwise, it will impossible to specify get_a(), get_b(), get_c(), get_d() 'const'.
-... | Not only is this correct, but also standard practice. A member mutex is described as "non observably non-const", which means it behaves as a constant to a "user" observer.
Herb Sutter has popularized the M&M rule:
For a member variable, mutable and mutex (or atomic) go together.
The rule's section related to your que... |
70,489,196 | 70,489,344 | How could I get address of the target object in smart pointer? | I'm trying to implement the linked list by indirect pointer, which introduced on the TED Talk.
I refer to felipec's implementation on github and made an version by raw pointer, this is the github link.
This is part of the full code, _find is a function that can find the indirect pointer of target node, which means *ind... |
How could I get the address of the target object in smart pointer?
I think you mean "the address of the pointer in the smart pointer", because the address of the target object is just what you get with .get(). std::unique_ptr does not offer any interface to access it's pointer member directly, so it is impossible.
D... |
70,489,820 | 70,490,278 | Getting a pointer with auto deduced return type on function template with default template argument | The following program makes the pointer x on function g<void>() having automatically deduced return type:
template<class=void>
void g() {}
int main() {
auto (*x)() = &g;
(*x)();
}
The program is accepted by GCC, but rejected in Clang with the error:
error: variable 'x' with type 'auto (*)()' has incompatible ... | This code
auto (*x)() = &g;
should be legal as per the changes made by P1972, in particular the change to temp.deduct#funaddr-1
... If there is a target, the The function template's function type and the specified target type are used as the types of P and A, and the deduction is done as described in 13.10.2.5. Other... |
70,490,249 | 70,490,287 | C++ overload >> operator with different interaction based on which side of >> | I was wondering if it is possible to have overload the C++ >> operator in this way
Account& operator>> (double left, Account &right)
{
right.deposit(left);
return right;
}
Account& operator>> (Account &left, double right)
{
left.withdraw(right);
return left;
}
I was wondering if the >> operator had th... | As described, this is not going to work for the following simple reason:
account1 >> 200 ...
When this gets evaluated this ends up calling the following overload:
Account& operator>> (Account &left, double right)
Your attention is drawn to the fact that this overload returns an Account &. That's declared right there,... |
70,490,333 | 70,490,440 | Constructor in double inheritance | I have a problem with my constructor. I have class vehicle, then I made class motorVehicle which inherited after vehicle and then I want to make class motorcycle which inherits after class motorVehicle and I can't make my default constructor because I have error:
Class vehicle and motorVehicle isn't changed by me and c... | Your base classes do not declare any constructor taking actual values. As these classes do declare a default constructor, aggregate initialisation doesn't work: there is a declared constructor, i.e., the class isn't an aggregate. If you want to directly initialise the base class you could use their implicitly generate ... |
70,490,584 | 70,490,627 | Having trouble with class in c++ | I'm obviously making a mistake here, but please help me.
#include <iostream>
#include <string>
using namespace std;
int main()
{
class Item
{
int Value;
int Use_On(Entity Target)
{
Target.HP += Value;
}
};
class Entity
{
int HP;
Item Slot;
... | The solution is to forward-declare the class, declare the class method first, and define it only after all classes have been declared.
class Entity;
class Item
{
int Value;
int Use_On(Entity Target);
};
class Entity
{
int HP;
Item Slot;
};
int Item::Use_On(Entity Target)
{
Target.HP += Value;
}
... |
70,491,020 | 70,491,058 | Destruction order between globals and static function locals | My understanding is that the order of destruction of objects with static storage duration is the inverse of the order of their initialization.
In this code snippet:
#include <iostream>
class LogValuesObj {
public:
LogValuesObj() {
std::cout << "LogValuesObj" << std::endl;
}
~LogValuesObj() {
... | It is well-known that objects with static storage duration are destroyed in the reverse order of their construction. But to be more specific—and since it matters in your case—they are destroyed in the reverse order of the completion of their initialization. See [basic.start.term]/3.
In your case, the initialization of ... |
70,491,088 | 70,491,106 | why doesn't assignment of int to std::map<string,string> produce a compiler error | Attempting to assign an int to a string
std::string s = 5;
produces the following compiler error:
error: conversion from ‘int’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested
however assigning an int to the value of a string in a map doesn't. For example the below code compiles, and... | This shouldn't be an error. m["test"] = 5; performs assignment, and std::string has an assignment operator taking char, and int could be converted to char implicitly.
constexpr basic_string& operator=( CharT ch );
On the other hand, std::string s = 5; is not assignment but initialization; and std::string doesn't hav... |
70,491,171 | 70,491,208 | What is the rule for type deduction for assignment using brace initialization? | In the following code, to my surprise, the { } appears to create a default initialized instance of int rather than of A.
struct A {
int i = 1;
A() = default;
A& operator=(const A& a) {
this->i = a.i;
return *this;
}
A& operator=(int i) {
this->i = i;
return *this;
}
};
int main() {
A a;
... | Firstly, the braced-init-list {} could be used to initialize both int and A, which are also considered as conversion, and the conversion from {} to int wins in overload resolution, since the conversion from {} to A (via A::A()) is considered as a user-defined conversion.
Assignment operator is not special, compilers ju... |
70,491,371 | 70,502,232 | Why the number stuck and doesn't increase anymore? | first of all, i'm new in programming.
This is just a simple fun project for me, but i met unexpectedly problem and i don't know why.
Background: This is something like "Groundhog Day", start loop from a month, by next loop the time decrease by one second. I'm trying to calculate the total years (by counting the total s... | You've surpassed the limits of your chosen numeric representation.
This might be surprising since most of the time, when mixing numeric types, C++ will convert to the type that can best represent the result. For example, adding an int and long long is calculated as a long long. Adding a float and double is calculated a... |
70,491,390 | 70,491,463 | Why does my c++ fibonacci sequence code give negative values after 46 iterations | The code also doesn't work whenever I try to take out the first two iterations out of the for loop. When I do, I get incredibly high numbers and then 0s for 11 iterations and my i value doesn't change. It has a vector size of 3 at the start of the loop for some reason as well, but it might have to do with the fact that... | The negative values should have been a big hint to you. An int has a maximum value of 2147483647. You overflow the int and it wraps around to being negative.
If you use a bigger type, like std::uint64_t, you can postpone the overflow by a decent amount. Its maximum value is: 18446744073709551615.
Finally, printing in t... |
70,491,519 | 70,491,712 | How to properly specify a recursive template class member function? | I want to unpack a variadic template parameter pack. As the function requires access to private members of the object, I decided to write it as a member function. To my understanding, according to the standard, a template function has to be specified in the same namespace as the enclosing class, I tried to separate dec... | Your first try didn't work because the declaration template<typename... Ts> void foo(); has to be matched with a declaration that looks the same, not template<typename T, typename... Ts> void foo() { // ..., which has different template parameters.
In C++17, it is pretty simple to "do something" for each thing in a par... |
70,491,663 | 70,491,714 | Syntax error for the code found in a tutorial? | I was learning to do a program online and found this solution and I wanted to execute and learn from it.
I am keep getting syntax error, can someone help with formatting it? I tried but couldn't understand the code that much to see where we need to provide indentation etc.,
I couldn't find a python example online for t... | You just need to import the modules you are using, exactly like Python, except the syntax is different:
#include <vector>
#include <string>
using namespace std;
class Node {
public:
...
And because it is using emplace_back, if you are using g++, you'll need to specify -std=c++11 on the command line.
Also, you ne... |
70,492,586 | 70,566,658 | Swig: How to change the accessiblity of the generated C# classes from `public class` to `internal class` | I am using swig 4.0.x to wrap a c++ file.
Everything is working fine except I want to change the accessibility of the generated C# classes from public class to internal class.
So far what I have tried is this:
In swig interface file
%module example
%{
#include "include/exampleapi.h"
%}
%typemap(csclassmodifiers) ... | Okay, so I have figured it out after asking this question on swig github repository. Following answer courtesy to William Fulton:
SWIGTYPE_xxx classes are called Type Wrapper Classes.
You need to use the C type for the typemap that causes the type wrapper class to be generated. For example SWIGTYPE_p_int is wrapping an... |
70,492,992 | 70,493,691 | what is this + before u8 string literal prefix for? | when I was reading codecvt example in cppref, I noticed this line:
std::string data = reinterpret_cast<const char*>(+u8"z\u00df\u6c34\U0001f34c");
Any idea what is that + before u8 for? Because I removed it and nothing changed in result.
| The + is "explicitly" performing the array-to-pointer implicit conversion, producing a prvalue const char8_t* (or const char* before C++20), instead of an lvalue array.
This is unnecessary since reinterpret_cast<T> (when T is not a reference) performs this conversion anyways.
(Possibly it was used to prevent confusion ... |
70,493,226 | 70,493,994 | Is this a real problem: warning C4172: returning address of local variable or temporary | The following code drops the warning C4172: returning address of local variable or temporary under Windows with MSVC. But im wondering is it a real error in this case or not? I know there is lots of similar topic here, and i have read lots of similar topics here from this warning. So in this case the returning value i... | Yes, this is a real problem. Your program's behavior is undefined. c is a different object from the pointer referenced by b, and its lifetime ends at the end of doWarning. Those two pointers point to the same A object (d), but that doesn't mean they're the same object.
To illustrate, I'll go more-or-less line-by-li... |
70,493,707 | 70,493,935 | Symbol names convention in libstdc++ | During building a library I got the following "undefined reference" error:
libtbb.so.2: undefined reference to `__cxa_init_primary_exception@CXXABI_1.3.11'
When I checked the symbols in my libstdc++ library I saw the following
nm -CD libstdc++.so.6.0.24 | grep "__cxa_init_primary_exception"
000000000008fdd8 T __cxa_in... | Maybe related to a known issue?
It's also mentioned here:
...current TBB has problems with gcc-libs, it’s compiled with gcc-libs 7.x so you will get this error if you try to build OpenCV with newest TBB
Proposed solution there:
This is also posted here, workaround is you should install TBB 2017_20170412-1 from Arch ... |
70,494,146 | 70,495,302 | How to Pass an ATL com object from c++ to c# | using ATl i have created a com object called "Comptes" ,that has properties like name,username. this is the idl file for the atl project
import "oaidl.idl";
import "ocidl.idl";
[
object,
uuid(15297371-6D05-4466-B80D-26207555CD28),
dual,
nonextensible,
pointer_default(unique)
]
interface Icompte : I... | Try to pass raw IUnkown* pointer to C# and then use Marshal.GetObjectForIUnknown to convert IntPtr to object and then cast this object to Icompte. You will need to add reference to the corresponding TypeLib into C# project to be able to perform such a cast.
|
70,494,373 | 70,494,469 | Is there a way to remove the "int main{}" in C++ | I've searched some but only found subjects based on C and not C++, here.
So I was wondering whether there is a way to remove the main function using some weird function or something to shorten one's code.
The purpose of this is for code-golf, which is shortening one's code to the absolute shortest. I found the int main... | There are two ways.
The first is to build a library instead of an application. You can't run it, but it will build your code to a library that can be linked by other applications. In g++, for instance, you do this with:
g++ -c my_file.cc -o my_file.o
g++ -shared -o libmy_file.so my_file.o
The other way is to modify ... |
70,494,426 | 70,494,557 | For constant expressions, why can't I use a use a pointer-type object, as standards says? | I was trying to figure out the restrictions of constexpr in cpp11/14. There are some usage requirements I found in CPP14-5.19-4:
A constant expression is either a glvalue core constant expression
whose value refers to an object with static storage duration or to a
function, or a prvalue core constant expression whose ... | In both
constexpr const void *x2 = global_var_addr1;
and
constexpr const void *x4 = global_var_addr2;
a lvalue-to-rvalue conversion happens from the variable global_var_addr1/global_var_addr2 glvalue to the pointer value they hold. Such a conversion is only allowed if the variable's lifetime began during the evaluati... |
70,494,728 | 70,495,272 | Performance of boost::mp11::mp_with_index compared to array of std::function | Consider the following two snippets:
// Option (1).
boost::mp11::mp_with_index<N>(i,
[&](const auto i){ function<i>(/* args... */); });
and
// Option (2).
inline static const std::array<std::function<void(/* Args... */)>, N>
functionArray{function<0>, ..., function<N-1>};
functionArra... | std::array<std::function<void(Args...)>, N> is likely to introduce some overhead compared to an array of pure pointers std::array<void(*)(Args...), N>.
Looking at the generated assembly at https://godbolt.org/z/a8z9aKs7P, the following observations can be made:
boost::mp11::mp_with_index is compiled to a branch table t... |
70,495,138 | 70,525,475 | Why Eigen C++ with MKL doesn't use multi-threading for this large matrix multiplication? | I am doing some calculations that include QR decomposition of a large number(~40000 in each execution) of 4x4 matrix with complex double elements (chosen from a random distribution). I started with directly writing the code using Intel MKL functions. But after some research, it seems like working with Eigen will be muc... | Please set the following shell variables before executing you program.
export MKL_NUM_THREADS="$(nproc)"
export OMP_NUM_THREADS="$(nproc)"
Also the build command (the first line run with $define EIGEN_USE_MKL_ALL commented out)
. /opt/intel/oneapi/setvars.sh
$CXX -I /usr/local/include/eigen3 eigen.cpp -o eigen_test -l... |
70,495,218 | 70,501,225 | How to bind a reference to either a const param or a new object? | Let's say I have this code:
void MyFunc(const std::string& param) {
std::string maybe_altered_param;
if (ConditionIsMet()) {
maybe_altered_param = AlterParam(param);
} else {
maybe_altered_param = param; // <-- unnecessary copy
}
// do stuff with maybe_altered_param
// maybe_altered_param does not... | With extra variables, you might do:
void MyFunc(const std::string& param) {
std::string maybe_altered_param;
const bool condition_met = ConditionIsMet();
if (condition_met) {
maybe_altered_param = AlterParam(param);
}
const std::string& ref =
condition_met ? maybe_altered_param : par... |
70,495,253 | 70,565,923 | Is there a way to detect the pixels of a sprite for a collision in SFML? | It doesn't have to be pixel-perfect collision, but I want it to be as close as possible to the actual pixels of the sprite. FYI, I created a 32 by 32 sprite but then I was only able to fill estimately half the amount of pixels, so the rest is just transparent.
| Most games out there don't use anything close to pixel perfect collision and it's usually not needed. Having some approximated rectangle or a combination of multiple rectangles is usually enough.
SFML itself provides intersects() and contains() functions for it's sf::Rect<T> class.
There's also some collision detection... |
70,496,043 | 70,496,495 | MISRA warning when overriding bitwise operator | I wrote a simple wrapper for the logging interface, so I can use left-shift operator<< to print log.
logger_wrapper.h
class LoggerWrapper
{
public:
LoggerWrapper(logging::LoggerInterface *logger, logging::LogPriority priority);
~LoggerWrapper();
bool log_enabled();
std::stringstream& get_stream();
... | The MISRA guideline essentially says that "For any binary operator (call it @), if you overload operator@() for your class then also overload the operator@=(), and ensure they behave consistently". The purpose is to ensure that (where x is an instance of your class).
x = x @ y; // @ may represent +, - , <<, *, /... |
70,497,535 | 70,498,682 | Makefile linking using g++ compiler with CUDA object files | I am trying to compile cuda object files with nvcc, and compile the final main script using the g++ compiler. I have seen this post but wasn't able to get my example working. The error I am getting seems to be a linkage error:
nvcc -c -g -I -dlink -I/usr/local/cuda-11/include -I. -L/usr/local/cuda-11/lib64 -lcudart -lc... | Your link line is wrong. All libraries (e.g., -lfoo) must come at the end of the link line after all the object files (e.g., .o files).
Not only that, but they need to be ordered properly (but I have no idea what the right order is so maybe they are correct above).
Almost all modern linkers are "single pass" linkers w... |
70,498,030 | 70,498,384 | Template function with template argument parametrized over int | Without using the features of C++11 and higher (I will accept them but would prefer C++98),
I have to write a template function with argument T which is an STL container of ints. It receives such a container along with another int which it tries to search for,
Right now I have this but it doesn't compile:
template <tem... | [NOTE] This answer uses C++20. @PatrickRoberts made me notice that you were preferably requesting a C++98 solution. I leave it anyway because it may be of any help to you.
You can just add a requirement for your template, checking the container's type is int.
[Demo]
#include <iostream> // cout
#include <list>
#include... |
70,499,066 | 70,499,069 | Vector push_back returns invalid conversion | Im new to cpp vectors and i keep encountering this issue
error: no matching function for call to ‘push_back(const char [6])’
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> names;
names.push_back("Lewis");
names.push_back("Mark");
names.push_back("Reece");
names.p... | The issue is that you are using a vector<int> rather than a vector<string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<string> names;
names.push_back("Lewis");
names.push_back("Mark");
names.push_back("Reece");
names.push_back("Max");
for(int i = 0; i < names.s... |
70,500,480 | 70,501,413 | Asio: how to get async data back into synchronous method | I'm using asio for async io, but there are some times where I'd like to "escape" the async world and get my data back into the regular synchronous world.
For instance, consider that I have a std::deque<string> _data that is being used in my async process (in a single thread always running in the background), and were I... | If you want to synchronize two threads, then you have to use sychronize primitives (like std::atomic). Asio doesn't provide more advanced primitives, but the STL (and boost) is full of it. For your simple example, you might want to use std::future and std::promise to move the top item of the deque to another thread.
He... |
70,500,597 | 70,500,761 | converting hex string to an integer while preserving the format | Title might be aids I don't really know what this process is called. Anyway basically I am using JSON to config my tool. (which is wrote in C++). but I want to configure key binds for GetAsyncKeyState but JSON doesn't support hex which I need for the virtual key codes. A solution for this is to use a string then conver... | unsigned int i = std::stoul(str, nullptr, 16);
|
70,500,657 | 70,500,677 | Is it possible to change a const data value? | can someone explain to me why does this code doesnt change the value of a?
is it possible to change a const data value?
case 1:
const int a = 2;
*((int*)&a) = 3;
std::cout << a;
case 2:
const int a = 2;
const_cast<int&>(a) = 3;
std::cout << a;
| Changing a const value is undefined behavior.
I would advise you not to do it or write any program that does so.
|
70,501,201 | 70,506,860 | How to draw a little square with a pic on it with fltk | i wanna create a board with little squares , and put a picture on every square , how can I do it using fltk on c++ ?
| The recommended method to draw a box with an image in FLTK is to use an Fl_Box widget and assign an image to it which will be used as its label, like:
Fl_Box b(0, 0, 100, 100);
b.image(my_image);
Of course, my_image needs to be a valid image like Fl_Image, Fl_PNG_Image etc.
|
70,501,659 | 70,501,979 | Constructors static keyword use | I read so many definitions of keyword 'static' and I still find it very confusing. Output of this program should be :
1 2 1 2 3 4 1 1 2 3 4 8 7 6 5 1 2 6 5
I understand how global members are called,but when the program reaches the main and static D d; I get all confused. Thank you in advance to anyone willing to expl... | For your example, I'm getting
1 2
1 2 3 4
1
1 2 3 4
8 7 6 5
1 2 6 5
5 8 7 6 5 6 5
I broke the output down in groups that correspond to paragraphs that follow.
First, the global variable C c; is constructed. This first constructs its member variable of type D, which prints 1; then C's constructor prints 2. That's the f... |
70,502,206 | 70,502,334 | Checking for a match in each element of a 2d vector | I'm creating text based TicTacToe in C++ and need to create a function that checks for a win.
Right now, I have a vector of all the moves player X has made:
std::vector<int> x_vector = {1, 2, 3, 5, 7};
I also have a 2d vector of win conditions:
std::vector<std::vector> > wins = {{1, 2, 3}, {4, 5, 6}, {7, 8, 8}};
In t... | You can iterate through your list of known wins, checking each to see if it is a subset of the list of user's moves. The std::includes function will do this test – but note that the two 'lists' need to be sorted.
To avoid having to manually sort the list of user's moves after each input, you can use the std::set contai... |
70,502,500 | 70,565,778 | What's the difference between getLocalBounds and getGlobalBounds in sfml c++? | I was making a collision detection for my objects, and was just wondering why I should use GlobalBounds instead of LocalBounds? or does it not matter which function I use?
| In simple terms: global bounds = local bounds + transformations and since you most of the time want to deal with the transformed position, scale or rotation, the global bounds become more useful than the local ones.
Of course there are always use cases, where local bounds can be useful.
|
70,502,661 | 70,503,168 | Fill Matrix in Spiral Form from center | I recently finished making an algorithm for a project I'm working on.
Briefly, a part of my project needs to fill a matrix, the requirements of how to do it are these:
- Fill the matrix in form of spiral, from the center.
- The size of the matrix must be dynamic, so the spiral can be large or small.
- Every two times a... |
Notice that the numbers along the diagonal (1, 9, 25, 49) are the squares of the odd numbers. That's an important clue, since it suggests that the 1 in the center of the matrix should be treated as the end of a spiral.
From the end of each spiral, the x,y coordinates should be adjusted up and to the right by 1. Then t... |
70,502,897 | 70,503,042 | any reason not to use 'protected' in this situation (cpp, c++, oop) | #include <iostream>
using namespace std;
class R {
protected:
int a;
public:
int read(void) {
return a;
}
};
class RW : public R {
public:
void write(int _a) {
a = _a;
}
};
int main(void) {
int a;
R *r = (R *)&a;
RW *rw = (RW *)&a;
rw->write(1);
cout << dec <... |
any reason not to use the 'protected' here?
protected member variables are sometimes discouraged in favor of protected member functions that accesses private member variables - and you don't need duplicate as if you make it private in R. You could add a protected member function to write to it instead.
class R {
publ... |
70,502,973 | 70,503,028 | Extra output when writing to file using std::cout | I am trying to read data from a file in.txt, and after some computations, I am writing the output to out.txt
Why is there an extra 7 at the end of out.txt?
Contents of Solution class.
class Solution
{
public:
int findComplement(int num)
{
int powerof2 = 2, temp = num;
/*
get number of b... | The reason there is an extra 7 is that your loop executes one too many times. You need to check std::cin after you've tried to read the input.
As is, you simply repeat the last test case.
|
70,503,103 | 70,503,278 | How to choose MPI vendor/distribution with CMake? | I have a program that I would like to compile with CMake + make but using two different MPI distributions, OpenMPI and MPICH.
In Ubuntu, I have both installed; these are all the compiler wrappers I have installed:
mpic++ mpicxx mpif77.mpich mpijavac
mpicc mpicxx.mpich mpif7... | Setting -DMPI_ROOT= or -DMPI_HOME= didn't work for me. It still uses the default in my system (OpenMPI).
What worked was to set -DMPI_EXECUTABLE_SUFFIX=.mpich, option which I found near the end of the documentation: https://cmake.org/cmake/help/latest/module/FindMPI.html.
|
70,503,267 | 70,503,383 | Is there a way to use bools with strings? I want to search for a word in a string, and if it's there, output the meaning | I am very new to coding and this is my first language, C++. I have an assignment that is really confusing.
The assignment wants me to search the user input of one line for slang words. Ex: TMI or BFF. However, I don't know how to use conditional expressions to do this, and I have tried if-else statements but they end u... | This code:
else if ((textSlang = userInput.find("IDK" ))) {
cout << "IDK: I don't know" << endl;
}
assigns textSlang to 0 IFF userInput begins with IDK. In all other cases it assigns some value other than 0.
And all int values other that 0 evaluate to true.
You want:
else if ((textSlang = userInput.find("IDK" )) != st... |
70,503,372 | 70,503,917 | No member named "XXX" in a simple CRTP case | Here I have a simple CRTP case:
#include <cstddef>
#include <utility>
template <typename Impl>
class base
{
constexpr static size_t impl_num = Impl::num;
};
template <typename Impl>
class deriv : public base<deriv<Impl>>
{
friend class base<deriv<Impl>>;
constexpr static size_t num = Impl::num_in;
};
cl... | The fundamental difference is the moment when you're trying to access the internals of the Impl class. Impl in base<Impl> is an incomplete type, and there are certain restrictions on what you can do with it.
In particular, you can't access num data member inside base, that's why the line
constexpr static std::make_inde... |
70,503,521 | 70,503,604 | Linking to lib on Linux without headers | Hello I'm trying to link to a library without headers. I wrote prototype exactly as defined in library, but ld cannot link it.
readelf -Ws Release/libcef.so | grep KeyStringToDomKey
386822: 00000000066d73d0 328 FUNC LOCAL HIDDEN 17 _ZN2ui16KeycodeConverter17KeyStringToDomKeyERKNSt3__112basic_stringIcNS1_11cha... |
386822: 00000000066d73d0 328 FUNC LOCAL HIDDEN 17 _ZN2u...
HIDDEN is the key here: this symbol is not visible outside of the shared library (neither to static linker /usr/bin/ld, nor to the dynamic loader).
|
70,503,703 | 70,503,760 | C++11 : Using local static variables in multithreaded program caused coredump | In C++11, I create 100 threads, every thread call Test::PushFunc, add local static variable index, insert to a local set variable localMap.
In theory, index is stored in Initialized Data Segment Memory and was added by every thread in program running time.
Following line
assert(it == localMap.end());
is reasonable bec... |
But in practice, program is coredump in assert randomly. Can U tell me why ?
Because you have a data race -- multiple threads are trying to read and write the same variable without any synchronization.
The index is a global variable. You need to guard access to it with a mutex.
Udate:
But localMap is not a global va... |
70,503,725 | 70,504,139 | std::erase_if delete an extra elements on std::vector? | I use std::erase_if to erase half the elements from containers using a captured counter as follows. C++20 compiled with gcc10
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
int main()
{
{
std::vector<int> container(10);
std::cout << container.size() << std::endl;
... | remove_if takes a Predicate. And the standard library requires that a Predicate type:
Given a glvalue u of type (possibly const) T that designates the same object as *first, pred(u) shall be a valid expression that is equal to pred(*first).
Your predicate changes its internal state. As such, calling it twice with the... |
70,504,125 | 70,504,313 | pybind11 py::class_.def_property_readonly_static incompatible function arguments for () -> str | I'm trying to bind C++ class static non-arguments method to python class static constant field use pybind11.
Here's my sample code config.cpp:
namespace py = pybind11;
struct Env {
static std::string env() {
return std::getenv("MY_ENV");
}
};
PYBIND11_MODULE(config, m) {
m.doc() = "my config module written... | Here's the answer about how to bind C++ class static non-arguments method to python class static constant attribute/variable with def_property_readonly_static API: https://pybind11.readthedocs.io/en/stable/advanced/classes.html#static-properties
The key is to use C++11 lambda, so update PYBIND11_MODULE part in config.c... |
70,505,162 | 70,505,238 | Why would one want to put a unary plus (+) operator in front of a C++ lambda? | I found out that in C++ we can use + in lambda function +[]{}
Example from the article:
#include <iostream>
#include <type_traits>
int main()
{
auto funcPtr = +[] {};
static_assert(std::is_same<decltype(funcPtr), void (*)()>::value);
}
The main idea of + sign in lambda
You can force the compiler to generate l... | It's not a feature of lambda and more is a feature of implicit type conversion.
What happens there is stemming from the fact that a captureless lambda can be implicitly converted to a pointer to function with same signature as lambda's operator(). +[]{} is an expression where unary + is a no-op , so the only legal res... |
70,505,765 | 70,509,655 | std::allocator deallocate don't use size argument | I'm learn about std::allocator. I try to allocate but use deallocate incorrectly I saw that it didn't use size argument, I confuse about the method could you please explain for me ? Thanks.
testcase1 "test" : I didn't deallocate, valgrind detected (correct)
testcase2 "test_deallocate" : I deallocate with size(0) less ... | Valgrind only intercepts the lower level allocation functions (malloc, new etc.). So it all depends on what the implementation of allocate and deallocate do.
Currently Valgrind doesn't do much checking of sized delete (or aligned new for that matter, see why does std::allocator::deallocate require a size? and https://b... |
70,505,843 | 70,546,672 | Android Studio NDK app performance difference between RUN and BUILD | I am trying to create a sudoku app with C++, SDL2 and Android Studio NDK.
In theory it is already working well unless I build and install the app manually.
While I get around 50-60 FPS when I run the app with the RUN-Button in Android Studio, there is a major performance drop when I install the app via BUILD -> GENERAT... | The difference between RUN and BUILD is in my Run-configuration.
Under Installation Options -> Deploy I chose "APK from app bundle". After researching and trying for hours I changed it to "Default APK", which caused the same performance problems as building and manual install as described in my question above.
While I ... |
70,506,148 | 70,506,620 | Multi Monitor Selecting | I want to use multi monitors. Like when application started , I will see all monitors and click one of them ,then application will start the monitor that I selected. How can I do this?
| Call EnumDisplayDevices to enumerate display adapters and monitors. Call ChangeDisplaySettings to move and/or turn monitors on/off.
Call MonitorFromPoint and GetMonitorInfo to find the work area for application windows.
|
70,506,156 | 70,517,564 | Embedded Linux, Qt4 QPrinter: PDF file content is bold and ugly | I am creating a PDF file using QPrinter in Qt4.8,
QPrinter printer(QPrinter::HighResolution);
QTextDocument document;
document.setHtml(html);
printer.setOrientation(QPrinter::Landscape);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);
printer.setOutputFileName(fName);
// printer.setFu... | It seems the problem is not about QPrinter at all. When refactoring I changed html contents of QTextDocument and unsupported CSS was causing the problem. I changed this:
body {
font-family: "Helvetica, Arial, sans-serif"; // quotes are not supported
font-style: normal;
font-size: 12px;
}
table.bordered , .... |
70,506,485 | 70,515,900 | In Qt6 cin/getline does not read any input for me | I am just starting with QT6 (and with QT in general).
I have tried to do simpe cin/cout operations and it's already troublesome.
Somehow cin does not read a line, nor does getline.
Here is my code:
#include <QCoreApplication>
#include <iostream>
#include <string>
using namespace std;
void do_something()
{
string ... | The solution was, as written in the comments:
Run the program in the Terminal, not in the QT Creator's Output Termina.
In the output Terminal you cannot type any input.
Flush the buffer because the text lies in the buffer until a endl or a flush occurs.
|
70,506,714 | 70,506,752 | C++ pointer member initialization | I know this is really basic, but I don't know the answer given my very limited C++ usage.
I was told whenever a class contains a pointer as a member, I should allocate memory for it. (and then use 'delete' inside the destructor to free the space)
class Person{
public:
string* ptr_name;
Person(string& name){... | After calling this constructor
Person(string name){
ptr_name = &name;
}
the pointer ptr_name will be invalid because the local variable name will be destroyed.
Thus dereferencing such a pointer will result in undefined behavior.
|
70,506,761 | 70,516,169 | Why don't methods defined in classes in C++ need forward declarations when referring to methods that only show up later in the class? | Why is this a compilation error:
void f() {
g();
}
void g() {
}
but not this:
class X {
void a() {
b();
}
void b() {
}
};
I was under the assumption the compiler would (at least, generally) read code from top-down, left-to-right, and that was the reason that in the 1st piece of... | C dates from 1972; C++ dates from 1985. C++ inherited the forward declaration requirement and the design of header files from C, and kept that behavior for compatibility, but was able to improve things for classes, with C didn't have.
|
70,506,780 | 70,508,058 | Member by member assignment of different classes based on the same template | Say that one has two classes which are different, but are somewhat "equivalent" in their purpose, so they have the same members, and one can be assigned by the other:
struct Pure
{
QString name;
int age = 18;
};
struct Observable
{
QProperty<QString> name;
QProperty<int> age {18};
void operator=(co... | You can't use std::is_same<QProperty<class X>, T>, because this is trying to pass T as the second argument to is_same, but it's a template and is_same is expecting a type.
You can make a is_same-like trait that takes template classes instead:
template<template<typename...> class A, template<typename...> class B>
struct... |
70,506,857 | 70,507,316 | Why is this optimized away by modern compilers for C++11 and higher | I'm lost.. I wanted to play around with the compiler explorer to experiment with multithreaded C code, and started with a simple piece of code. The code is compiled with -O3.
static int hang = 0;
void set_hang(int x) {
hang = x;
}
void wait() {
while (hang != 0) {
// wait...
}
}
To my surprise, t... | It's because of following rule:
[intro.progress]
The implementation may assume that any thread will eventually do one of the following:
terminate,
make a call to a library I/O function,
perform an access through a volatile glvalue, or
perform a synchronization operation or an atomic operation.
The compiler was able... |
70,507,626 | 70,507,744 | Overloading operator in different ways depending on template argument | I have a class
template<int n> MyClass<n>
for which I am trying to define the operator &. I want to be able to perform MyClass&MyClass, but also MyClass&MyClass<1> (or MyClass<1>&MyClass would work for me as well) with a different functionality obviously.
template <size_t n>
struct MyClass
{
//...a lot of stuff
... | SFINAE only works with templates. You can make the 1st operator& template as:
template <size_t n>
struct MyClass
{
//...a lot of stuff
template <size_t x>
std::enable_if_t<x == n, MyClass<x>> // ensure only MyClass<n> could be used as right operand
operator&(const MyClass<x> &other) const;
// over... |
70,507,682 | 70,508,191 | Wrong input shape error in torchscript and C++ interface | I am trying to interface libtorch and OpenCV to predict the classes using the Yolov5 model. The weight I am using is yolov5s.pt. The source code is
cv::Mat image = file->input_image(); // read image and resize into 640x640
auto tensor = torch::from_blob(image.data, {image.rows,image.cols,3}, torch::kFloat);
tensor = t... | The solution was pretty simple. I am feeling too embarrassing, but you shouldn't.
Here is the solution
// forgot to add these both lines
// the yolov5 is expects [BATCH, CHANNEL, WIDTH, HEIGHT]
tensor = tensor.permute({2,0,1});
tensor = tensor = tensor.unsqueeze(0);
std::cout << tensor.sizes() << std::endl;
|
70,508,180 | 70,508,229 | what is the "written out" equivalent of a ternary assignment? | I have a struct that is non-default-constructibe.
I want to assign different values to an object of that struct depending on a condition.
Since the struct is non-default-constructibe, it is not possible to declare an unitialized object of it.
However, it is possible to do that with a ternary:
struct foo {
foo(int a... | Adding a factory function can help you out here. Using
foo make_foo(bool test)
{
if (test)
return generateFoo1();
else
return generateFoo2();
}
lets you have code like
foo f = make_foo(test);
|
70,508,536 | 70,516,877 | Need to add multiple inlcude devpkey.h in my cmake project in msvc | Included that header files of my BundleController class are included multiple times devpkey.h header file. So MSVC give errors like below;
**Severity Code Description Project File Line Suppression State
Error C2374 'DEVPKEY_Device_Address': redefinition; multiple initialization (compiling source file Bund... | in such situation always need look code and try understand source of error. DEVPKEY_Device_Address (and another symbols in question) defined with DEFINE_DEVPROPKEY macro. based on - are INITGUID is defined - DEFINE_DEVPROPKEY expanded to declaration or definition. if not defined INITGUID, before include devpkey.h ( usu... |
70,508,626 | 70,508,942 | C++ can't use std::array, due to cli::array keyword Visual Studio | I want to declare a std::array, but the array part gets recognized as cli::array keyword (see Why is "array" marked as a reserved word in Visual-C++?), which means that the std:: doesnt affect it. How can a stop Visual Studio from automatically using namespace cli, or specify that I want to use std::array?
The blue ar... | std::array accepts two template arguments. One is the type of the elements and the other accepts the number of elements.
If you mean to use a dynamic array, then use std::vector.
|
70,508,730 | 70,511,136 | How to parse a string of a set of chess moves and store each move individually C++ | So I am reading a .txt file that has many sets of chess moves. I am able to read data from the file and insert the line into a string.
An example single chess move can look like this:
1. e4 e5
I have written the following function to parse a single chess move:
void parseSingleChessMove(string move)
{
this->moveN... | @rturrado showcased how you could do this with regex, however I would hesitate to do it like that, since std::regex is heavy, and requires a lot of knowledge regarding regex to use it effectively. Instead, I think it's easier to accomplish it with istream and operator>>.
void parse_moves(std::istream& input)
{
int ... |
70,508,815 | 70,508,966 | Implicit call of Class constructor from Initialisation of another class | The following code-snippet seemingly works:
#include <iostream>
class Filling{
public:
const int num;
Filling(int num_)
: num(num_)
{ }
};
class Nougat{
public:
Nougat(const Filling& filling)
: reference(filling)
{ }
const Filling& get_filling() const{ return reference; }
private:
const Filling& refe... | Wrapper's constructor expects a reference to Nougat, but you are giving it a Filling. As with all function calls in C++, in such a situation implicit conversion sequences for all arguments are considered.
An implicit conversion sequence could be for example a cast from a derived class reference to a base class referenc... |
70,508,837 | 70,508,875 | I want to know the error in my code. This is to print sum of all even numbers till 1 to N | #include<iostream>
using namespace std;
int main(){
int i = 1;
int sum;
int N;
cout << "Enter a number N: ";
cin >> N;
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
else
{
i = i + 1;
}
}
cout << sum;
}
This is ... | For starters the variable sum is not initialized.
Secondly you need to increase the variable i also when it is an even number. So the loop should look at least like
while(i<=N)
{
if(i%2 == 0)
{
sum = sum + i;
}
i = i + 1;
}
In general it is always better to declare variables in minimum scopes w... |
70,509,028 | 70,509,256 | writting a binary in c++ | So i have this program that supposedly reads any file (e.g images, txt) and get its data and creates a new file with that same data. The problem is that i want the data in an array and not in a vector and when i copy that same data to char array, whenever i try to write those bits into a file it doesnt write the file p... | Try this:
(It basically uses a char*, but it's an array here. You probably can't have an array in the stack in this case)
#include <iostream>
#include <fstream>
int main() {
std::ifstream input("hello.txt", std::ios::binary);
char* buffer;
size_t len; // if u don't want to delete the buffer
if (input)... |
70,509,085 | 70,509,191 | Print of vowels in a string | I attempted to create a program that let's the user input a string of text and then create a subprogram that will print out all the vowels in that string. The problem with my program is that it only prints out the text once again.
So my terminal will look like:
Enter text: Feye
Feye
Instead of what I intend it to do:
... | Here is a simple solution:
#include <iostream>
#include <string>
#include <string_view>
#include <array>
#include <iterator>
#include <algorithm>
static constexpr std::array<char, 12> vowels { 'A', 'E', 'I', 'O', 'U', 'Y',
'a', 'e', 'i', 'o', 'u', 'y' };
bool is_vowel( ... |
70,509,208 | 70,509,470 | std::future in simple words? | I saw the uses of std::future in the program written in C++. So, I quickly went to lookup what is is: std::future and got a quite complicated answer for me.
Can someone put it in simple words for a 6 years old kid? I have an understanding level of a 6 years old kid...
Just a small definition with a minimal use case wil... | A std::future<T> is a handle to a result of work which is [potentially] not, yet, computed. You can imagine it as the receipt you get when you ask for work and the receipt is used to get the result back. For example, you may bring a bike to bike store for repair. You get a receipt to get back your bike. While the work ... |
70,509,529 | 70,509,563 | Use of class template node requires template arguments C++ | I have two classes defined in C++ seen below.
#include <vector>
#include <tuple>
#include <map>
template <class T> class node {
public:
int NodeID; //ID used to identify node when inserting/deleting/finding.
T data; //generic data encapsulated in each node.
std::vector<node*> children; //child nodes, ... | Solution 1
You can solve this by specifying a type in std::vector<node*> Nodes; as shown below:
std::vector<node<int>*> Nodes; //note i have added int you can add any type
Solution 2
Another solution would be to make class DAG a class template as shown below:
template<typename T>
class DAG {//Class for the graph
... |
70,509,642 | 70,524,080 | Dealing with in/out string parameters in Swig Python | Maybe someone know, how to rewrite getVersion to get in Python version and legacyVersion as a result of function instead of passing them as in/out parameters
class DeviceInterface {
public:
virtual uint32_t getVersion(uint8_t* version, uint8_t* legacyVersion ) = 0;
};
For now I create additional functio... | You can define your own typemaps to handle the output parameters. In this case, the typemaps treat all uint32_t* parameters as 200-byte output buffers. This is a minimal example without error checking.
%module test
%include <stdint.i>
// Require no input parameter. Just allocate a fixed-sized buffer.
%typemap(in,n... |
70,510,716 | 70,511,014 | Why we cannot create an array with a constant in c | Why the below piece is a valid C++ code but an - invalid C code?
int main(){
unsigned int const size_of_list = 20;
const char* list_of_words[size_of_list] = {"Some", "Array"};
for (unsigned int writing_index = 0; writing_index < size_of_list; writing_index ++)
;
return 0;
}
| In C:
20 is a constant.
unsigned int const size_of_list is not a constant.
Title: "Why we cannot create an array with a constant in c" does not apply to this code.
const char* list_of_words[size_of_list] = {"Some", "Array"}; // Bad
An issue here (and the error message) is why a VLA cannot be initialized. That is answ... |
70,511,046 | 70,511,442 | Parsing a string in c++ with a specfic format | I have this string post "ola tudo bem como esta" alghero.jpg and i want to break it into 3 pieces post, ola tudo bem como esta (i dont want the "") and alghero.jpg i tried it in c because im new and not really good at programming in c++ but its not working. Is there a more efficient way of doing this in c++?
Program:
i... | In C++14 and later, you can use std::quoted to read quoted strings from any std::istream, such as std::istringstream, eg:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
int main()
{
std::string token1, token2, token3;
std::string str = "post \"ola tudo bem como esta\" alghero.jpg";... |
70,511,082 | 70,515,855 | Why is it possible to pass a void(*)(int x, int y) to attachInterrupt that expects void(*)()? | I've been inattentive and for some reason created a function that takes two arguments, and I passed it to attachInterrupt like so:
int state = 42;
void simplified_state_handler(){
state++;
}
void interrupt_func(int x, int y) {
simplified_state_handler();
}
attachInterrupt(digitalPinToInterrupt(10), interrupt_... | The compiler settings of the AVR boards allow it.
It is only a warning: invalid conversion from 'void (*)(int, int)' to 'void (*)()' [-fpermissive].
On other Arduino platforms (SAMD, STM32, esp8266) it is an error.
The compiler settings in AVR platform were benevolent from the start and they can't change them suddenly.... |
70,511,444 | 70,511,645 | Is it possible to have a constructor with 1 input parameter of undeclared type? | Here is what I an trying to do:
Class with two objects (string myStr and int myInt)
Constructor takes in 1 parameter (data type not fixed).
If parameter is string: myStr = parameter; myInt = parameter.length();
If parameter is int: myInt = parameter; myStr = "0000...0"
(string of length "parameter", set by for loop... |
Is it possible to have a constructor with 1 input parameter of undeclared type?
Technically, you can have variadic parameters which allows unspecified number of arguments of unspecified types. But I recommend against using it.
The types of all other parameters must be declared.
If parameter is string: myStr = param... |
70,512,077 | 70,512,136 | multiple concepts for template class | I have the class below, but it only works with floating points. How to add integers too? That is multiple requires statements? or is there something that can include all numerical types?
Or there is a better way?
#ifndef COMPLEX_H
#define COMPLEX_H
#include <concepts>
#include <iostream>
template <class T>
requires s... | You can || your concepts such as
requires std::floating_point<T> || std::integral<T>
you can also create a concept this way
template <typename T>
concept arithmetic = std::integral<T> || std::floating_point<T>;
then you can use this concept with your class
template <class T>
requires arithmetic<T>
class Complex
{
... |
70,512,367 | 70,608,511 | How to translate a program into a language with QtLinguist in C++? | I wrote code on QtCreator to translate the GUI of my application into English and Spanish. This application was written in French. The .ts translation files have been generated. And I translated strings to English on QtLinguist (but not Spanish), and I ticked the fields with a green arrow to show that I was sure of the... | What probably happens is that QTranslator::load fails; since you didn't specify an absolute path, nor did you pass a directory as second argument, it will only try to find the file in your current working directory.
To make this more robust, you should a) specify the directory as second argument, and b) check the retur... |
70,512,466 | 70,513,480 | Getting undefined symbols for architecture arm64 error | I am building on an M1 Pro Mac (CLion) and am getting the following error while compiling:
FAILED: tree
: && /Library/Developer/CommandLineTools/usr/bin/c++ -g -arch arm64 -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX12.0.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/tree.dir/mai... | It looks like you are having problems with templates. In templated classes you have to either place the implementation of the methods all in the header file or make explicit template instantiations of the concrete classes in the cpp body that defines it.
It's easier to see with an example. In the following case I'm add... |
70,513,188 | 70,513,333 | JsonCpp: Serializing JSON causes loss of data in byte string | I have a simple use case where I wish to serialize and transmit vectors of integers between 0 and 256. I surmised that the most space-efficient way of doing so would be to serialize the vector as a serialized string, where the nth character has the ASCII code equivalent to the nth element of the corresponding vector. T... | Jsoncpp Class Value
This class is a discriminated union wrapper that can represents a:
...
UTF-8 string
...
{ 230 } is invalid UTF-8 string. Thus further expectations from Json::writeString(builder, val) for a correct result are illegal.
|
70,513,208 | 70,523,303 | STM32 - Dynamic Memory Allocation Implementation, how to correctly implement the _sbrk function? | I'm working on a bare-metal programming project written in C++ on a STM32F401RE board, and I need to implement malloc() and free() functions.
I know that dynamic memory allocation on embedded systems is not a good idea, but I need it.
Up to know I understood that in order to use malloc and free functions of the C stand... | Assuming that you are using Newlib (the usual C library used with GCC on stand-alone systems), then the target specific porting layer ("syscalls") for the C library is defined at https://sourceware.org/newlib/libc.html#Syscalls.
A minimal implementation suitable for standalone (no OS) environments is given there as an ... |
70,513,252 | 70,513,306 | Is there a way to iterate over the second element of a std::map? | I want to create a std::vector<char> with something like: v(map.begin(), map.end()); rather than iterating over all elements of the map and resizing v over and over.
#include<iostream>
#include<map>
#include<vector>
int main() {
std::map<int, char> map{{1,'a'},{2,'b'},{3,'c'}, {4,'d'}};
std::vector<ch... | In C++20, you could create a view over the values by using std::views::values:
#include <map>
#include <vector>
#include <ranges>
int main() {
std::map<int, char> map{{1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'}};
auto view = std::views::values(map);
std::vector<char> v(view.begin(), view.end());
}
Demo
A m... |
70,513,264 | 70,513,342 | How is printf() an expression? | I was trying to learn value categories because of an error that I got and stared watching this video by Copper Spice.
They go on to define an expression and as an example provide printf() at this point in the video (screenshot below).
How is printf() an expression? I always thought that function calls aren't really an... |
How is printf() an expression?
It's a function call expression.
I always that that function calls aren't really an expression
Function calls are expressions.
They are more like statements
Function calls are not statements. Consider for example ret = printf();. Here, the function call is a subexpression of the ass... |
70,513,509 | 70,513,536 | default member value initialization is ignored in GCC | I came up with an unexpected behaviour (to my own limited knowledge) in the code below, where it does not respect the default member initialized values. I have a contractor for a single argument assignment that supposes to build the class from an assignment operator. I forgot to use the correct argument name and I ende... | Complex(T real) : re{re} { // should be re{real}, but why re{re} is not 0?
If you provide an initializer for a member explicitly in the constructor, then this initializer replaces the default member initializer. The default member initializer is in such a case not used at all.
To be clear: The default member initializ... |
70,513,923 | 70,515,115 | assertion fails: __is_complete_or_unbounded | While compiling HHVM, the code fails due to:
/usr/include/c++/10/type_traits:918:52: error: non-constant condition for static assertion
918 | static_assert(std::__is_complete_or_unbounded(__type_identity<_Tp>{}),
What does __is_complete_or_unbounded actually do/check?
The issue occurs while constructing an obj... | In C++, an array cannot have zero size.
From Array declarators documentation:
If the expression is a constant expression, it shall have a value greater than zero.
|
70,514,422 | 70,526,080 | ADL warning: ambiguous conversion with boost operators and SFINAE | I'm trying to understand an ambiguous conversion warning during ADL for the following piece of code:
#include <boost/operators.hpp>
#include <boost/polygon/polygon.hpp>
class Scalar
: private boost::multiplicative< Scalar, double > {
public:
explicit Scalar( double val ) : mVal( val ) {}
Scalar &operator... | Your free operator* in the global namespace is too open. It actively assumes that Point is not constructible from Scalar, quod non:
no problem
vs using Boost Polygon's Point
You should restrict it more:
template <
typename P, typename S,
typename IsPoint = typename boost::polygon::is_point_concept<
ty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.