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 |
|---|---|---|---|---|
69,456,325 | 69,456,691 | i am looking for the right answer for this question, is this correct? |
Write a function void switchEnds(int *array, int size); that is passed
the address of the beginning of an array and the size of the array.
The function swaps the values in the first and last entries of the
array.
#include <iostream>
using namespace std;
void switchEnd(int *array, int size){
int temp=array[0];
... | There are multiple ways to do this. Your way is the straight forward way. But the question reminds me of some questions of c++ courses, where you should understand pointers.
If this is the case, then an answer like this might be better:
void switchEnd(int *start, int size){
int *end = start + size - 1;
int tem... |
69,456,736 | 69,461,671 | Read zst compressed pcap with libpcap | I would like to decode zst and gz pcap with libpcap but I am not able to find any example doing so. Of course I don't want to have a temporary decompressed pcap file.
Could you guys point me to the right methods ?
Thanks
| Libpcap doesn't currently support reading compressed files.
If you don't want to have a temporary decompressed pcap file, the only way to do so would be to have your program create a pipe, run another program that reads the compressed file and writes the decompressed file data to the standard output with its standard o... |
69,456,917 | 69,457,380 | Should I always define a constexpr static data member outside of the class? | Why a constexpr static data member needs to be defined outside of the class on C++11, C++14 but it doesn't need that requirement on c++ 17, 20 and above?
struct Array{
int static constexpr sz_ = 5;
int ar_[sz_]{};
};
//int constexpr Array::sz_; // needed on `C++11`, `C++14` but not needed for C++17, C++20
voi... |
Should I always define a constexpr static data member outside of the class?
Always?! Only a Sith deals in absolutes.
C++17 made static constexpr variables implicitly inline (in the linkage sense, they always needed an in-class initializer). The out-of-class definition remains an optional but deprecated feature.
D.1 ... |
69,457,205 | 69,457,235 | How to pass object array to a function? | class department
{
void max() ***HOW TO PASS ARRAY OF OBJECT HERE , WHAT PARAMETERS SHOULD I PASS***
{
}
};
class B : public department {
};
int main()
{
B a[10];
// a.max(a,n); ***HOW TO CALL THIS max FUNCTION***
return 0;
}
I want to pass the array of object a[10] to the max function... | You implemented max() as a non-static method of department, so you need a department object to call it on, like each B object in your array, eg:
for(int i = 0; i < 10; ++i)
{
a[i].max();
}
If this is not what you want, then max() needs to be taken out of department, or at least made to be static instead. Either w... |
69,457,893 | 69,457,996 | Problem receiving an array as pointer parameter | Hi I have a trouble trying to manage a the following array.
I have initialized this pointer int* coordenadasFicha = new int[2]; and I want to asign the two int asking the user for the numbers.
The trouble appears when I call pedirCoordenadasFicha(coordenadasFicha); Clion recomends me cast coordenadasFicha to int** but ... | An int* (a pointer-to-int) and an int*[] (an array of pointer-to-int) are two different things. And actually, in a function parameter, int* coordenadasFicha[2] is actually passed as int** (pointer to pointer-to-int), because an array decays into a pointer to its 1st element.
In your case, you are creating coordenadasF... |
69,458,100 | 69,469,262 | Boost log working on W10 but not in ubuntu - segmentation fault | After testing the Boost.log on W10 with Visual Studio 2019, I am trying to have the same application (writes a simple log file) running in ubuntu using the Windows Subsystem for Linux.
So, I created a new project with the same source files, configured it to build on WSL using GCC, and indicated to the Linker the boost ... | In the VS project, despite correctly indicating the linker (Configuration Properties => Linker => Input => Additional dependencies) to look for boost libraries on WSL, I was also including (Configuration Properties => C/C++ => General => Additional Include directories) the path to the boost headers that are on my Windo... |
69,458,205 | 69,458,238 | Execvp not executing ping command with arguments | I am using the exevcp system call in order to execute "ping www.google.com". However, when I execute the code below:
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
using namespace std;
int main(int argc, char *argv[]){
vector<char*> pingArgs... | vector<char*> pingArgs;
pingArgs.push_back("www.google.com");
pingArgs.push_back(NULL);
The first parameter to a program, it's argv[0], is the name of the program itself.
Here, you're merely informing the ping program that it's name is www.google.com, and it has no additional parameters.
vector<char*> pingArgs;
p... |
69,458,260 | 69,471,588 | CMakelist include subfolders | I can't figure out how to import my source files, which are in a different directory. The structure of my project looks like this:
root
- src
- core
App.h
App.cpp
CMakelist.txt
CMakelist.txt
main.cpp
CMakelist.txt
My main CMakelist under root looks like this:
cmake_minimum_required(VERSION 3.17... | If you do not want to use a separate library for core, you can use the following structure in src/CMakeLists.txt:
# core sources
set(core_srcs core/App.cpp core/App.h)
# aux sources
set(aux_srcs aux/stuff.cpp aux/stuff.h)
add_executable(edu main.cpp ${core_srcs} ${aux_srcs})
This lets you organize your CMakeLists.tx... |
69,458,664 | 69,470,606 | uWebsocket sending messages via WebSocket outside of the .message Behavior context | I have to open with the obligatory, I'm pretty trash at c++, fresh out of college.
I setup uWebsocket as a server, it's currently just echoing responses back to the client.
I am trying to setup a queue on a separate thread that can respond to the client at times OTHER than when I recieve a message.
I'm killing myself o... | From the uWebsocket docs, the type of ws is: WebSocket<SSL, true, int> *
Thus, you can try to use the following. Note: You probably need to forward-declare outerFunction as well.
void outerFunction(uWS::WebSocket<SSL, true, int> *ws);
void RelaySocket(){
struct SocketData{
//Empty because we don't need any... |
69,458,957 | 69,458,995 | Parametrized custom stream manipulators - why overload "operator<<"? | I am trying to implement a parametrized stream manipulator for a certain set of data. I do it the simple way as recommended:
class print_my_data
{
private:
. . .
public:
print_my_data(. . .) { . . . }
ostream& operator()(std::ostream& out)
{
return out << . . . << endl;
}
};
ostream& oper... | The overload you're looking for is only defined for function pointers.
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
Your print_my_data class is a callable object (a functor, in C++ terms). But it is not a function pointer. On the other hand, endl is a ... |
69,459,016 | 69,460,933 | How can I calculate the complexity of a program like this | So I have been studying the complexity of algorithms, but this one I can't uderstand.
If I use a global variable to check how many times the function is called it will calculate the number 11 then saying that the complexity is O(2*N), but when looking at the problem I thought the complexity would be O(N).
#include <cst... | Big O notation works like this:
O(c * f(x)) = O(f(x)), c!=0
In other words, you can always multiply the function inside the parenthesis by an arbitrary non-zero real constant.
So O(2N) = O(N)
Another property of big O notation is that you can omit lower order terms:
O(x^2 + x) = O(x^2)
O(a^x + p(x)) = O(a^x) where a... |
69,459,984 | 69,461,975 | c++11 way of returning an array of unknown number of elements | I would like to implement this function (or a similar one, see the requirements below) in C++11:
template<typename... ARGS>
constexpr std::array<const typename std::common_type<ARGS...>::type, sizeof...(ARGS)> asConstArray(ARGS&&... args)
{
return {std::forward<ARGS>(args)...};
}
struct DataBinding {
static co... | Trailing return type should do the job:
struct DataBinding {
static constexpr auto getRawBindings()
-> decltype(
asConstArray(
DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object
DEF_BINDING(float, areaProp, areaParam) //BindingInfo constexpr object
... |
69,460,287 | 69,697,203 | std::fstream file not getting created while making a custom Csv file manager class | I'm a beginner to C++. I made a simple program which collects information of cars and stores it into classes. This was just for the purpose of learning more about classes. I wanted to store the data of cars to a csv file. But it is very complicated so I tried to make a class called CSVFile to manage csv files. But I ca... | The file opened successfully when I opened it with std::fstream::app append mode.
|
69,460,318 | 69,460,341 | What is Foo(int* ptr): ptr_{ptr}{}? | I saw this code in the book "C++ High Performance" by Bjorn Andrist and Viktor Sehr.
The code example is actually used to show the point that "Compiles despite function being declared const!", and I am aware of this. However, I have not seen int* ptr_{}; and Foo(int* ptr):ptr_{ptr}{} before this point. What are these t... | Foo(int* ptr) : ptr_{ptr}{}
Declares and defines a constructor for the class Foo,
which takes in input a int * (pointer to int),
and initializes the member variable ptr_ via the member initializer list;
it does nothing more, so the body is emtpy, {}.
int* ptr_{};
uses one possible syntax of value initialization to... |
69,460,680 | 69,461,413 | i was not declear in thiscscope cpp,but another i is working Q:ARRAY OF OBJECT | ` SHOWING i IS NOT DECLEARED IN THIS SCOPE
question: of ARRAY OF OBJECT.
#include<iostream>
using namespace std;
class employee{
char name[30];
float age;
public:
void getdata();
void putdata();
};
void employee::getdata()
{
cout<<"Enter name"<<endl;
cin>>name;
cout<<"Enter the age "<<endl;
cin>>age;
... | #include<iostream>
using namespace std;
class employee{
char name[30];
float age;
public:
void getdata();
void putdata();
};
void employee::getdata()
{
cout<<"Enter name"<<endl;
cin>>name;
cout<<"Enter the age "<<endl;
cin>>age;
}
void employee :: putdata()
{
cout<<"Name "<<name<<endl;
cout<<"a... |
69,460,697 | 69,862,803 | Program 'test.exe' failed to run: Access is denied vs code C error | this is the error message
Program 'test.exe' failed to run: Access is deniedAt line:1 char:91
+ ... cuments\arpit\" ; if ($?) { gcc test.c -o test } ; if ($?) { .\test }
+ ~~~~~~.
At line:1 char:91
+ ... cuments\arpit\" ; if ($?) { gcc test.c -o test } ; ... | I had the same error just a few minutes ago, but I found the solution. It is because your Antivirus program 'erases?' the exe files so they can't run. If you are using Avast, you should turn off hardened mode (stopped working after I turned it on). This is the video where I found the solution. It works for me just fine... |
69,461,396 | 69,461,531 | How to make a function that accepts another one with argument tuple | I need a function My_func that works like this
auto f = [](const std::tuple<string, double>& t) { return std::get<0>(t); };
assert(My_func(f)("Hello", 8.5) == f({"Hello", 8.5}));
Now i have
template <class F>
constexpr auto My_func(F&& f) {
return [f](auto&& args...) { return std::forward<F>(f)(args); };
}
Bu... | template <class F>
constexpr auto My_func(F&& f)
{
return [f = std::forward<F>(f)](auto&&... args) {
return f(std::make_tuple(std::forward<decltype(args)>(args)...));
};
}
|
69,461,415 | 69,461,683 | Function default argument value depending on argument name in C++ | If one defines a new variable in C++, then the name of the variable can be used in the initialization expression, for example:
int x = sizeof(x);
And what about default value of a function argument? Is it allowed there to reference the argument by its name? For example:
void f(int y = sizeof(y)) {}
This function is a... | According to the C++17 standard (11.3.6 Default arguments)
9 A default argument is evaluated each time the function is called
with no argument for the corresponding parameter. A parameter shall
not appear as a potentially-evaluated expression in a default
argument. Parameters of a function declared before a default
ar... |
69,461,735 | 69,462,436 | Is it possible to store a type in C++? | Is there any easy way to keep the type of variable?
For example storing in general container std::map<key, std::any> myMap; will cast values types to std::any, and init types will be forgotten. If only somehow to store type as a std::string, and then compare it with typeid(someType).name(). But it seems realy inconveni... | If you just need to check if the current type of the stored value in an std::any is a certain type, you could use std::any::type():
#include <any>
#include <cassert>
#include <typeinfo>
int main()
{
std::any foo;
assert(foo.type() == typeid(void));
foo = 1;
assert(foo.type() == typeid(int));
foo = ... |
69,462,332 | 69,462,566 | Receive variadic sized raw arrays of the same type in a C++ template function | I would like to implement the following logic, I'm not sure if it is possible:
#include <stddef.h>
#include <array>
template<size_t SIZE>
constexpr std::array<const char*, 1> fun(const char (&name)[SIZE])
{
return {name};
}
template<size_t SIZE_1, size_t SIZE_2>
constexpr std::array<const char*, 2> fun(const char... | Knowing where to put the ... is much simpler with a type alias
template<std::size_t N>
using chars = const char (&)[N];
template<std::size_t... SIZES>
constexpr std::array<const char*, sizeof...(SIZES)> fun(chars<SIZES>... names)
{
return { names... };
}
See it on coliru
|
69,462,409 | 69,478,510 | int8 parameter input for imgSessionSaveBufferEx() | I am trying to execute the imgSessionSaveBufferEx function:
I would like to save an image into PNG format, what should I input as the parameter for Int8* file_name?
imgSessionSaveBufferEx(sessionID, NULL, ______);
| The sequence of attempts are below:
imgSessionSaveBufferEx(sessionID, NULL, "test.png");
imgSessionSaveBufferEx(sessionID, NULL, reinterpret_cast<Int8*>("test.png"));
// this is the answer, provided by Botje
imgSessionSaveBufferEx(sessionID, NULL, reinterpret_cast<Int8*>(const_cast<char *>("test.png")));
|
69,463,047 | 69,463,162 | how to print template typename in c++? | I am writing a wrapper for boost numeric_cast with the wrapper function something like:
#include <boost/numeric/conversion/cast.hpp>
#include <stdexcept>
template <typename Source, typename Target>
Target numeric_cast(Source src)
{
try
{
// calling boost numeric_cast here
}
catch(boost::numeric... | You can use typeid(T).name() to get the raw string of the template parameter:
#include <boost/numeric/conversion/cast.hpp>
#include <stdexcept>
#include <typeinfo>
template <typename Source, typename Target>
Target numeric_cast(Source src)
{
try
{
// calling boost numeric_cast here
}
catch(boos... |
69,463,504 | 69,463,748 | C++ Array function pointer with class | Below is my class code :
enum style{BASIC, WEATHER_ONLY};
enum area{AREA0, AREA1, AREA2, AREA3, AREA4, AREA5, NULL_AREA};
enum display{NTP_TIME, TWO_DAY_WEATHER, TREE_DAY_WEATHER, WEEK_WEATHER, TEMPERATURE_AND_HUMIDITY};
typedef struct areaFormat
{
unsigned int x0;
unsigned int y0;
unsigned int width;
... | Syntax to call a member function when you have a pointer to member function is:
(obj.*memberFuncPtr)(args);
so you should:
DisplayTemplate dt;
auto ptr = dt.displayStyle[BASIC][AREA0].function;
auto af = dt.displayStyle[BASIC][AREA0].areaParameter;
(dt.*ptr)(af);
If auto is not clear, you can add alias type for memb... |
69,463,774 | 69,464,031 | Adding number to pointer value | I am trying to add a number to a pointer value with the following expression:
&AddressHelper::getInstance().GetBaseAddress() + 0x39EA0;
The value for the &AddressHelper::getInstance().GetBaseAddress() is always 0x00007ff851cd3c68 {140700810412032}
should I not get 0x00007ff851cd3c68 + 0x39EA0 = 7FF81350DB08 as a res... | With pointer arithmetic, type is taken into account,
so with:
int buffer[42];
char* start_c = reinterpret_cast<char*>(buffer);
int *start_i = buffer;
we have
start_i + 1 == &buffer[1]
reinterpret_cast<char*>(start_i + 1) == start_c + sizeof(int).
and (when sizeof(int) != 1) reinterpret_cast<char*>(start_i + 1) != sta... |
69,464,490 | 69,464,716 | How to make a function that accepts another one with variable arguments | I need a function My_func that works like this
auto f = [](string s, double c) { return c; };
assert(My_func(f)(std::make_tuple("Hello", 8.5)) == f("Hello", 8.5'));
Now i have
template <class T>
auto My_func(T&& f) {
return [f = std::forward<T>(f)](auto&& value) {
};
}
What should i add?
| I believe you are looking for std::apply
#include <cassert>
#include <string>
#include <tuple>
template <class F>
constexpr auto My_func(F&& f) {
return [f = std::forward<F>(f)](auto&& tuple) mutable {
return std::apply(std::forward<decltype(f)>(f),
std::forward<decltype(tuple)>(t... |
69,464,493 | 70,393,053 | Capture YUV frames from OpenCV capture device | I need to extract YUV frames directly from a web camera using OpenCV from C++ on the Windows platform. In other words: a setup in OpenCV that makes the capture device's read() method return a YUV Mat. I'm looking for a working example or documentation on how to do this.
The specific YUV subformat isn't that important f... | Seems that OpenCV under windows is made with Direct Show which cannot grab YUV variants directly. So the solution is not to use OpenCV but Windows Media Foundation. OpenCV under other OS'es may be able to grab YUV.
|
69,464,759 | 69,464,998 | Compiler changes the type variable type from uin16_t to int when it's marked as constexpr | I've encountered a weird problem trying to flip all bits of my number.
#include <cstdint>
constexpr uint16_t DefaultValueForPortStatus { 0xFFFF };
void f(uint16_t x)
{
}
int main()
{
f(~(DefaultValueForPortStatus));
}
When I'm compiling this program (GCC trunk) I'm getting an error:
warning: unsigned conversion... | This is caused by IMHO a quite unfortunate C++ rule about integer promotion. It basically states that all types smaller than int are always promoted to int if int can represent all values of the original type. Only if not, unsigned int is chosen. std::uint16_t on standard 32/64-bit architectures falls into the first ca... |
69,464,843 | 69,470,253 | Is it possible to get mac addresses when scanning networks? ESP32 | I need to get the RSSI of the networks and they MAC addresss to a IPS (indoor position system) program. I was able to get ssid, signal strength and security using the sample code, but not mac addresses. I tryed to use this, but itsn't working:
void loop() {
int n = WiFi.scanNetworks();
if(n == 0){
Serial.print... | @Tarmo's answer is correct, but the Arduino core does provide a simpler interface to getting the AP's access point without having to directly call ESP-IDF functions.
Use the BSSID method to get the MAC address of the base station's wifi radio.
You can call either the BSSID() method to get a pointer to the six byte MAC ... |
69,464,943 | 69,466,360 | How to check a value for null when using boost json ptree | I 'm getting a json response from a server of the following format :
{"value": 98.3}
However there are cases that the response can be :
{"value": null}
I have written a C++ program that uses boost json in order to parse this and get the value as float
#include <iostream>
#include <string>
#include <boost/property_t... | Using the boost/property_tree/json_parser.hpp you can only check the string version like you said:
So I always check if the value is not equal with the literal "null" because according to this
Boost Json with null elements outputting nulls is not supported.
However, since boost version 1.75.0, you can also use boost/... |
69,465,479 | 69,465,612 | Unreal Engine 5 crashing after using SetupAttachment function | I've created new poject and added new c++ class, but after using SetupAttachment UE has an error. I've tryed to fix it and found a probem. For now i don't know, in what problem, i actualy know the place. UE5 window after building
Code:
Header:
// Fill out your copyright notice in the Description page of Project Setting... | It’s your mistake. You’re never initializing SpringArm, and even if it were set in your actor instance (or through a blueprint or subclass), it wouldn’t be available during the constructor (and would still crash when constructing the CDO).
|
69,465,711 | 69,465,789 | Using a template function as a template param in another function | I was wondering, how I can do the following in C++?
template <typename T>
T doSomething(T x, T y) {
T result = /*do something*/;
return result;
}
template <typename T , typename V>
T doMore(**input doSomething as template**, V v){
T result = doSomething<V>(v,0);
return result;
}
I am basically trying to us... | You cannot pass (the set of) function template as argument (you can pass specific instantiation though).
You might pass functor to solve your issue:
template <typename T>
T doSomething(T x, T y) {
T result = /*do something*/;
return result;
}
template <typename F, typename V>
T doMore(F f, V v){
T result = f(v... |
69,466,142 | 69,467,453 | make an array where the number that i insert gets deleted and is replaced by a 0 at end of array using pointers | I'm making it in a 3x4 matrix form
Also I'm not sure how to use a pointer since the number that I want to change and replace is an arr[3][4] and not the usual arr[5]
using namespace std;
#include <iomanip>
int main(){
int i;
int j;
int *change;
int number; // not sure how to use the pointer to referenc... | The operation that you want to do is natural for single dimensional ranges, and not for multi dimensional ones. There are standard algorithms to achieve your goal with a single dimensional range.
With range views, it's fairly simply to get a single dimensional view of the elements:
// flat view of the array
auto flat_a... |
69,466,282 | 69,466,504 | Initializing C++ class attribute from another class | Currently, I am trying to implement what I have learned so far: OOP class in C++. Here I have two different classes: VehicleInfo and Vehicle. Here down below is my written code:
#include <iostream>
#include <string>
#include <fstream>
#include <math.h>
#define M_PI 3.1416
using namespace std;
class VehicleInfo{
p... | In your Vehicle constructor, the compiler first has to default-construct all the member variables. Only after that will the code in the constructor run and Vehicle::vehicle = vehicle; will get called.
So your vehicle member variable will first get default-constructed and then assigned a value.
But your VehicleInfo does... |
69,467,219 | 69,467,562 | "The associated constraints are not satisfied" with custom requires clause | In one of my projects, I'm getting the error "the associated constraints are not satisfied" for one of my C++20 concepts. It appears to me that my code is correct, so I must misunderstand something about the language.
I have rewritten the code to remove all of the obviously extraneous details.
Here are the include stat... | template<typename... Args>
requires requires (BLikeType t, Args... args) {
{t.Bfunc(c_->Cfunc(args...))};
}
std::array<double, sizeof...(Args)> Afunc(Args... args) {
return c_->Cfunc(args...);
}
The requires-clause is not a complete-class context, so it can't see later-declared class members like c_. You can m... |
69,467,232 | 69,606,086 | how to get per test coverage for google tests c++ with gcov | I would like to get per test coverage for every test case in my c++ program.
What I get is that GoogleTest allows some actions to be performed before and after every test
#pragma once
#include <gtest/gtest.h>
#include <gcov.h>
class CodeCoverageListener : public ::testing::TestEventListener
{
public:
virtual void O... | The gcov.h header is internal to GCC, so it is not installed in any include path. If you want to call the gcov functions yourself (which I don't recommend), then you would have to declare them yourself.
extern void __gcov_reset (void);
extern void __gcov_dump (void);
Linking with libgcov should work, with the caveat t... |
69,467,271 | 69,475,731 | CopyFile() function causes exception while debugging but not while running from terminal | I have a Visual Studio 2019 project, containing only one .cpp file, named as copyFile.cpp
#undef UNICODE
#include <iostream>
#include <Windows.h>
int main()
{
std::cout << "Hello World!\n";
DWORD ret = CopyFile("xyz.txt", "xyzCopy.txt", FALSE);
printf("\n\t ret: %d, getlasterror(): %d", ret, GetLastError... | I could not find the root cause, however, @SimonMourier posted a link in his comments, which suggest a workaround that works.
Additional information: Toggling the debug option "Automatically close
the console when debugging stops" on, stops the exception being
thrown.
|
69,467,461 | 69,468,279 | Double template argument for a template function | What would be a valid definition of this function to be called in main as the following?
foo<float, double>(sqrtfunction< float>, floatList);
I was wondering if it’s done with template classes, but isn't possible to do this without calling it as a member of a class?
foo is a function which calls sqrtfunction which app... | I think user 463035818's answer resolved your problem.
But if you want to write a template function, you can write something like this:
#include <cmath>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <functional>
template <typename T>
T my_sqrt(T value)
{
return std::s... |
69,467,769 | 69,468,161 | Compiler version in C++ vs pre-compiled C libraries | I have a code that uses std=c++20.
I want to use a C library that was build with old gcc version.
Should I recompile the C library using the same compiler ?
If no, how could you judge that the 2 ABIs are compatible?
| There should be no problem using the library as it is. Don't forget to add extern "C" around the function prototypes.
More info: Using C Libraries for C++ Programs
|
69,467,772 | 69,468,150 | Move (or copy) capture variadic template arguments into lambda | I am attempting to figure out how to move (or just copy if a move is not available) variadic parameters into a lambda within a templated function.
I am testing this with a move-only class (see below) because this would be the "worst-case" that needs to work with my template.
class MoveOnlyTest {
public:
MoveOnlyTes... |
To be clear, I don't want to perfectly capture the arguments as in c++
lambdas how to capture variadic parameter pack from the upper scope I
want to move them if possible
Just using the same form:
auto lambda = [fn, ...args = std::move(args)]() mutable {
(*fn)(std::move(args)...);
};
In C++17, you could do:
auto l... |
69,468,027 | 69,468,484 | What is the best alternative to C's nested array designators in C++ for initializing a 2D array? | I am currently trying to convert my small regular expression engine from C to C++.
To discard syntactically incorrect regexes in a compact way, I use a 2D array to define what kinds of tokens are allowed after one another:
#define NUMBER_OF_TOKEN_KINDS 15
typedef enum {
Literal,
Alternator,
...
} TokenKind;... | You might create a constexpr function to initialize your std::array (instead of C-array):
constexpr
std::array<std::array<bool, NUMBER_OF_TOKEN_KINDS>, NUMBER_OF_TOKEN_KINDS>
make_grammar_allowed()
{
std::array<std::array<bool, NUMBER_OF_TOKEN_KINDS>, NUMBER_OF_TOKEN_KINDS> res {};
res[Literal][Alternator] = t... |
69,468,326 | 69,468,374 | Reading lines of txt file into array prints only the last element | First of all, I didn't code in C++ for more then 8 years, but there is a hobby project I would like to work on where I ran into this issue.
I checked a similar question: Only printing last line of txt file when reading into struct array in C
but in my case I don't have a semicolon at the end of the while cycle.
Anyway,... | line.data() returns a pointer to the sequence of characters. It is always the same pointer. Every time you read a new line, the contents of line are overwritten. To fix this, you will need to copy the contents of line.
Change:
char *nicknames[2000];
to
char nicknames[2000][256];
and
nicknames[nicknameCount++] = line.... |
69,468,530 | 69,517,461 | why is the overload resolution wrong here? | suppose we have this as our setup:
#include <iostream>
class Base {
private:
int a;
public:
Base(int a)
: a(a) {
}
virtual void print() = 0;
};
class Child : public Base {
public:
using Base::Base;
void print() override {
//some code
}
};
class Wrapper {
private:
vo... | Ok. after sometime thinking about it, I figured it out. It's simply because there is an implicit cast happening where we try to call the constructor of second version, we change the type of Child* to Base* and because of that it's not anymore an LValue and becomes an RValue, therefore it can't bind to Base*& and if we ... |
69,468,579 | 69,470,901 | Save data from `recvfrom()` to a structure to avoid extra bytes? | I get the packages by upd and create the structure PSG. Then I save it to a vector and sort.At the end, I write all the byte data to a file. The problem is that the last packet is less than 1424 bytes. and because of this, extra bytes are written to the end of the file. How could I correctly save data from recvfrom() t... | You're getting the size of the packet read in bytesrecv, but then you're ignoring it and not using it. Store it somewher and use it. You could add it to your PSG object:
#pragma pack(push, 1)
struct PSG
{
uint64_t id;
uint64_t size;
uint32_t type;
uint32_t count;
uint8_... |
69,468,615 | 69,469,271 | I am getting an error of redefinition while using extern header file | I am getting an error of redefinition while using extern, but I was also told, that extern variable should be used like this, why I am getting this error and how should I use extern in this case so it will work? (I can use this variable even if I don't specify it in Tab.cpp, but I am getting error of finding one or mor... | There are definitions and declarations. A declaration tells the compiler that something exists. A definition is a declaration that has all the information needed to describe that thing.
For global variables like maxid, The extern says that it will have external linkage; that is, be known to the linker and be seen bet... |
69,468,783 | 69,468,831 | Adding derived class object to vector<unique_ptr> of base class | So in my code I'm trying to add unique_ptr to objects from derived class to vector of base class. I get this error:
E0304 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=std::unique_ptr<Organism, std::default_delete<Organism>>, _Alloc=std::allocator<std::unique_ptr<Organism, std::... | Similar to how the default member visibility of class is private, inheritance is also private unless otherwise specified. You need to inherit from Organism publicly so that std::unique_ptr is able to see and perform the conversions you expect.
class Sheep : public Organism {
public:
Sheep( coordinates organism_pos,... |
69,468,895 | 69,469,410 | Reverse order of varidic template arguments while constructing a map key | I am using a variadic template to construct a key for a map, calculating a number to a base:
template<typename T>
uint64_t key(int base, T n)
{
return uint64_t(n) % base;
}
template<typename T, typename... Args>
uint64_t key(int base, T n, Args... rest)
{
return key(base, rest...) * base + (uint64_t(n) % base)... | Since C++17 I would use fold expression (op,...) to do that:
template<class B, class ... Args>
auto key(B base, Args ... args) {
std::common_type_t<Args...> res{};
( (res *= base, res += args % base), ... );
return res;
}
Demo
|
69,469,112 | 69,469,226 | Template struct in C++ with different data members | Is there a way to change what data members are contained in a templated struct based on the parameters? For instance:
template<int Asize> struct intxA
{
#if (Asize <= 8)
int8 num = 0;
#elif (Asize <= 16)
int16 x = 1;
#endif
};
In implementation:
intxA<3> struct8;
intxA<11> struct16;
I have tried the code abov... | Yes, you can do it with partial specialization.
template<int Asize, typename = void> struct intxA
{
};
template <int Asize>
struct intxA<Asize, std::enable_if_t<Asize <= 8>>
{
int8 num = 0;
};
template <int Asize>
struct intxA<Asize, std::enable_if_t<(Asize > 8 && Asize <= 16)>>
{
int16 x = 1;
};
|
69,469,207 | 69,469,611 | Access Violation with uninitialized variable being passed to method call that initializes it | I need some theoretical explanation of the following memory access violation BEFORE even entering the method:
String testMethod (AnsiString param1);
AnsiString A1 = testMethod(A1);
I am trying to understand the theory behind the problem.
A1 is getting initialized by the return value of testMethod() while at the same t... | AnsiString A1 = testMethod(A1);
When you reach this point:
AnsiString A1
the name A1 exists and is known to the compiler. Thus, you can use it farther to the right. However, you are calling testMethod with a raw memory block that has not been constructed yet. That's going to blow up when it hits the copy constructo... |
69,469,311 | 69,469,932 | C++ Managing pointers to functions inside another class | I'm trying to write a program that calls for a function stored inside a class whose implementation is defined by another object instance.
Let me clarify this better: I would like to create an object A and call for its functions (like an abstract object), but the body of this functions should be defined by either an ins... | Polymorphism exists for just this type of situation, eg:
class A {
public:
virtual ~A() = default;
virtual void someFunction() = 0;
};
class B : public A {
public:
void someFunction() override {
std::cout << "some function" << std::endl;
}
};
class C : public A /* or B*/ {
public:
void som... |
69,469,481 | 69,476,872 | how to translate key shortcut | I cannot force QKeySequence::toString() to return translated shortcut representation despite the fact that it documentation suggests it should work. The docs say: "The strings, "Ctrl", "Shift", etc. are translated using QObject::tr() in the "QShortcut" context." but I am not completely sure what it means by shortcut co... | The QShortcut::toString has a SequenceFormat parameter, defaulted to ProtableText. The documentation of the format states, that portable format is intended for e.g. writing to a file.
The native format is intended for displaying to the user, and only this format performs translations.
Try:
qDebug() << action->shortcut(... |
69,470,058 | 69,470,331 | How to read QWORD (64-bit) from the registry in C++? | How do I read a REG_QWORD from the registry? Most specifically the HardwareInformation.qwMemorySize .
I found that with it divided by 1024 then once again divided by 1024 you can get the Video memory in megabytes. How can I read the QWORD first? I can only find how to read DWORDs.
| You read a QWORD the exact same way you read a DWORD, using RegQueryValueEx(), just with a 64-bit integer variable instead of a 32-bit integer variable, eg:
HKEY hKey;
if (RegOpenKeyEx(..., KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
QWORD value = 0; // or UINT64, ULONGLONG, ULONG64, ULARGE_INTEGER, etc...
DWOR... |
69,470,252 | 69,474,948 | Examine how the variables are allocated in the heap memory (for debugging runtime errors) | For example, the following code causes munmap_chunk(): invalid pointer
#include <vector>
int main(int argc, char* argv[]) {
std::vector<int> foo(10, 0);
std::vector<int> bar(10, 1);
for(int i = 0; i < 20; i++) {
foo[i] = 42;
}
bar.clear(); // causes munmap_chunk(): invalid pointer
}
In this simple exampl... |
Is there way to show how variables are allocated in the heap?
Yes: you can examine locations that vector will use in a debugger. For example (using your program) and GDB:
(gdb) start
Temporary breakpoint 1 at 0x1185: file t.cc, line 3.
Starting program: /tmp/a.out
Temporary breakpoint 1, main (argc=1, argv=0x7ffffff... |
69,471,180 | 69,471,591 | cpp common method to create QObject::connection | i want to write ConnectMathod(...) in such way that it accept QObject* and receiver slot. and establish connection
class A : public QObject {
public :
A();
~A();
signals :
void sigA(int);
slots :
void slotA(bool);
}
class B : public QObject {
public :
B();
~B();
signals :
void sigB(bool);
slots :
void slotB(int);
}
/... | Make ConnectMethod as a function template which takes as second argument template parameter which will be any callable object, for example a closure generated from lambda expression:
class C : public QObject {
Q_OBJECT
public:
C() {}
~C() {}
signals:
void signalC(bool);
public:
template<class Callable>
... |
69,471,424 | 69,471,541 | How C++ alias works? | How does alias internally work in C++?
Does it allocate its own memory like pointers?
Otherwise how does the compiler treat it?
Is it like C++ Macro preprocessor computing?
int x=5;
int &y=x; //Assembly of this???
| Those are called references.
The standard doesn't describe how they (or anything else) work on the assembly level.
In practice, they are implemented as pointers, unless the compiler optimizes them away (which is easier for references compared to pointers, because they can't be reassigned).
They are unrelated to macros,... |
69,471,669 | 69,471,832 | How to get the weekday number from std::chrono::year_month_day in C++ | In C++ 20, the following code will output the number (0-6) for the weekday of the input date:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
year_month_day dmy;
cin >> parse("%d %m %Y", dmy);
cout << format("%w", weekday{dmy}) << '\n';
}
How ca... | You can use std::chrono::weekday::c_encoding to retrieve the stored value.
|
69,471,738 | 69,473,051 | Reference counting - internal references problem | I have implemented my own smart pointers, and everything worked fine, untill I realized a fatal flaw with my implementation. The problem was the fact that an object can have a smart pointer that potentially holds a reference to itself. the problem would be easy to avoid if this was a one layer problem - what could easl... | There is no easy way to handle this issue. It is a fundamental problem with reference counting.
To build intuition as to why this is the case, note that the difficulty of detecting cycles of smart pointers is similar to the difficulty of dealing with the cycles. To detect cycles you need to be able to traverse the poin... |
69,471,899 | 69,477,033 | CGAL::Polyhedron_3 makes unwanted duplicated vertices using make_tetrahedron(), how to solve it? | I was trying to create a volume mesh using the CGAL::Polyhedron_3 data structure when, doing some tests, I noticed that the make_tetrahedron function duplicates the vertices already present in the polyhedron.
Example: Two tetrahedra that share a common face
this is the code I tried:
#include <CGAL/Simple_cartesian.h>
#... | You cannot store non-manifold features in a polyhedron, you need something like a linear cell complex. See here
|
69,471,964 | 69,472,193 | Trouble establishing pipe communication between python and cpp | The first attached piece of code is the python code I was using (in "test.py"). The second one is the c++ code (in "test.cpp" which I compiled to "test.out"). I am using ubuntu (18.04) wsl to run these programs.
I firstly established the pipes that will allow intercommunication between the two processes. Using fork I c... | You have some problems in your C++ program (like undefined behavior because you read your string literal out of bounds in write(w_sub, "message back", MSGSIZE);) but the first problem is that your file descriptors aren't inherited by the started program - so they are all bad file descriptors in the C++ program. Always ... |
69,472,895 | 69,473,227 | Double becomes pointer when returned? | I'm new to Cpp and I'm just trying to construct a very basic 'Circle' class. Below is my code
#include <iostream>
#include <cmath>
#include <typeinfo>
class Circle {
private:
const double pi = 3.14159265358979323846;
double radius;
double area;
double perimeter;
public:
void se... | The actual issue you're having is the attempt to return a C-array from a function. That's not a thing that can be done. If you want, the smallest possible change would be to change your function to look like this:
#include <array>
// [...]
std::array<double, 3> get_attr() {
std::array<double, 3> circle_attr{r... |
69,473,641 | 69,474,175 | Multithreading is slowing down OpenGl loop | I'm currently programing a minecraft like map generator using OpenGL in C++. I have a AMD Rayzen 5 3600 6-Core.
So, when I tried to add multithreading in my main loop to call my chunks generation, it was slowing down the rendering. I'm not using multithreading for rendering.
I'm on Windows using MinGw to compile code a... | Threads and processes are basically the same thing under Linux, both are created by calling clone() internally. So you can see that a thread is not something cheap to create and you are doing it several times inside each loop!
Don't beat yourself for that, the first generations of web servers (Apache) were like that to... |
69,473,896 | 69,474,526 | How do I format an bluetooth address as a btaddr? | I have a bluetooth address (7C9EBD4CBFB2) that I need to connect to using winsock. This is my code, which returns error as -1, and won't connect to my device.
#include <winsock2.h>
#include <ws2bth.h>
#pragma comment(lib, "Ws2_32.lib")
#include <Windows.h>
#include <iostream>
using namespace std;
SOCKADDR_BTH sockAddr;... | You are not calling WSAStartup() before socket(). You would have realized this sooner if you had been doing better error checking. See Handling Winsock Errors.
socket() would have returned INVALID_SOCKET (-1), and then WSAGetLastError() would have returned WSANOTINITIALISED (10093).
Successful WSAStartup not yet perfo... |
69,474,540 | 69,474,559 | Is it possible to make a C++ function for a data type that is accessible using a dot operator? | I want to make a function associated to a data type say int that can be accessed using the dot operator such that:
int x = 9;
std::string s = x.ToString();
I know how to do so with std::string and the likes but not the int data type. Is that possible?
| No, this is not possible. An int is a primitive type whereas a std::string is a class type that contains methods.
However, you could create your own struct/class in order to implement this functionality. The struct Int type has a constructor which takes in an integer and uses an initializer list :a(value) to assign the... |
69,474,794 | 69,475,049 | Prime factors with stack implementation in C++ | Greetings stack overflow, recently run into a problem where my code isn't doing exactly what I intend it to do. My intentions are for the user to input a number and then the program will check for its prime factors, when it finds a prime factor I want it to push the number into a stack. I've tried putting cout statemen... | You've made a very simple error. In passing your stack by value to primeFactors the stack is copied and the copy worked on. When primeFactors finishes, that copy is discarded, and your original empty stack is left.
Taking advantage of C++ templates:
#include <iostream>
#include <cmath>
template <typename T, unsigned i... |
69,475,015 | 69,486,620 | ncursesw causing weird behaviour | On WSL2, I'm using the first example code given in this tutorial website: https://tldp.org/HOWTO/NCURSES-Programming-HOWTO/panels.html.
Code:
#include <panel.h>
int main()
{ WINDOW *my_wins[3];
PANEL *my_panels[3];
int lines = 10, cols = 40, y = 2, x = 4, i;
initscr();
cbreak();
noecho();
/... | The example shows two problems:
mixing -lpanel with -lncursesw (won't work because the size of the types holding character plus attributes differs).
You should use -lpanelw.
there's no call to setlocale to make line-drawing work portably.
|
69,475,135 | 69,475,253 | Access a vector or an array from another file in C++ | I'm trying to access the elements of an array/vector from another file (pattern.cpp here). According to this discussion (http://cplusplus.com/forum/beginner/183828/) I should do
//pattern.cpp
namespace myprogram {
void Pattern::FromReal()
{
extern std::vector<double> real_data;
for (auto it=real_data.begin(); i... | Here is the working example. Just create(if not already) a realdata.h file which have the extern for the real_data vector. Then you can just include this header in pattern.cpp and wherever you want this real_data vector like in main.cpp .
main.cpp
#include <iostream>
#include "pattern.h"
#include "realdata.h"
extern s... |
69,475,322 | 69,483,295 | Cumulative sum with array in C++ | #include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <sstream>
using namespace std;
int iData, tData;
void randgen(int max, int min){
srand((unsigned) time(0));
}
int main()
{
cout << "Masukkan jumlah data: ";
cin >> iData;
int jData[iData]... | This:
int iData;
cin >> iData;
int jData[iData];
is using variable-length arrays, which are not standard C++. Rather use std::vector instead:
int iData;
cin >> iData;
std::vector<int> jData(iData);
The tData local variable is uninitialized:
int tData;
...
tData += jData[i];
It should be initialized to 0.
The condi... |
69,475,384 | 69,475,888 | Finding the intersection of two binary search trees | I am building and returning a new binary search tree constructed of the intersection of two other binary search trees. I have available to me a find function which I am using to check if any values of the first tree are found in the second tree and if they are I insert them into a new tree. My issue is that the new tre... | You are overwriting res every time you call intersectWith() by calling 'new BinSearchTree()'.
To fix this, create res outside of interSectWith() and then pass it in as a third parameter. (You could then also consider making intersectWith() return void, as a return value is no longer needed.)
|
69,475,538 | 69,476,078 | How to detect selection of shapes in OpenCASCADE? | I am using OPENCASCADE 3D library together with Qt. I have set up 3D display, and displayed several items of TopoDS_Shape in a window, using calls to AIS_InteractiveContext::Display method. Now I'd like to have some event processing when user picks a shape on 3D display.
I have checked documentation to AIS_InteractiveC... | No, you should react on mouse clicks or key strokes to check whether the user wants to select something.
There is an Open CASCADE Qt sample called "Tutorial", you might want to check it. In the file ".../samples/qt/Common/src/View.cxx" you can find a sample implementation.
|
69,475,710 | 69,476,000 | Simple Encryption program array | Building a simple program that multiplies the ASCII value of chars in a string by 3 to encrypt and then divide by 3 to decrypt. So far I got the encryption part down but whenever I enter what the encryption gave and try to decrypt it doesn't work. I think it has something to do with the buffer stream but I could be wro... | This is a working implementation, although I agree with the other answer that you should use encrypt and decrypt functions. I found quite a few other bugs with your code working through it. You should enable all warnings with -Wall -Werror and fix them:
#include <iostream>
#include <vector>
#include <sstream>
int ma... |
69,476,112 | 69,476,525 | Abstract class init in the initialization list | I want to understand the following c++ concept. class_a is abstract class and as per abstract class concept we cannot create any instance of it.
i have used the initlization list and abstract class as well but never used following concept.
In the code ,the initlization list of class_b, class_a is initlized. I want to u... | It would be more clear with a slightly richer example. Because if the abstract base class has neither attributes nor methods it is harder to see how it can be initialized.
class NamedProcessor {
std::string name; // a private attribute
public:
NamedProcessor(const std::string &name) : name(name) {}
virtu... |
69,476,158 | 69,481,115 | I am getting segmentation fault while using Morris algorithm for inorder traversal of a binary tree | The question link was this: Inorder Traversal (GFG)
I referred the geeksforgeeks article that had the same code but in void function. I modified it to fit the question. Now I am getting segmentaion fault and I don't know why.
The GFG article: Inorder Tree Traversal without recursion and without stack!
vector<int> inOrd... | The following condition is wrong:
if(!root->left){
This will make the same check in each iteration. It should relate to the current node:
if(!current->left){
|
69,476,464 | 69,476,734 | How can I replicate compile time hex string interpretation at run time!? c++ | In my code the following line gives me data that performs the task its meant for:
const char *key = "\xf1`\xf8\a\\\x9cT\x82z\x18\x5\xb9\xbc\x80\xca\x15";
The problem is that it gets converted at compile time according to rules that I don't fully understand. How does "\x" work in a String?
What I'd like to do is to ge... | This is indeed provided by the compiler, but this part is not member of the standard library. That means that you are left with 3 ways:
dynamically write a C++ source file containing the string, and writing it on its standard output. Compile it and (providing popen is available) execute it from your main program and r... |
69,476,676 | 69,476,808 | arguments a constant in template function | I have a template function as below which has one of the arguments a constant
template<typename T>
T maxAmong( T x, const T y) {
return x ;
}
For explicit specialization I expected to have the below code. But this gives a compile error.
template<> char* maxAmong( char* x, const char* y) {
return x;
}
Where... | const char * is a pointer to a const char.
char * const is a constant pointer to a char.
Thus, your template specialization should look like this:
template<typename T>
T maxAmong( T x, const T y) {
return x ;
}
template<>
char* maxAmong( char* x, char* const y) {
return x;
}
This thread might be helpful as ... |
69,476,849 | 69,476,992 | Can you extract bitmask directly from bitfield in C++? | Considering following example:
#include <iostream>
using namespace std;
struct Test
{
uint8_t A:1;
uint8_t B:1;
uint8_t C:1;
uint8_t D:1;
};
int main()
{
Test test;
test.A = 1;
test.B = 0;
test.C = 1;
test.D = 0;
int bitmask = test.A | (test.B << 1) | (test.C << 2) | (tes... | Assuming you want to convert the entire struct, and there exists an integral type with the same size as the struct:
Test test;
test.A = 1;
test.B = 0;
test.C = 1;
test.D = 0;
cout << (int)std::bit_cast<char>(test) << '\n';
std::bit_cast is a C++20 feature.
char is used here because it has the same size as Test. I'm c... |
69,476,900 | 69,477,013 | In this Linked List why it is not allowing me to run again and create another node what is the error in my code? | I am trying to make employee database using Linked list data structure but once I enter the value the option to run again is not available and also display function is not executes code stops before that I have checked the code sevearl times but I am not able to spot the error.
#include<iostream>
using namespace std;
... | You got a typo in Link_List constructor. it should be:
head=NULL;
not
head==NULL;
It seems to work after replacement.
TIP: Although statically scanning code with your eyes makes you think better; A debugger is an essential tool you need to adopt.
|
69,477,385 | 69,477,865 | Can dangling pointer be equal to valid pointer during constant evaluation in C++? | During constant expression evaluation in C++17, shall the compiler consider any pointer addressing a valid object unequal to any pointer addressing an object after the end of its lifetime?
For example:
constexpr auto f(int * x = nullptr) {
int c = 0;
auto p = &c;
if ( x == p )
throw "unexpected";
... | The result of comparing a dangling pointer with any other pointer is implementation-defined:
When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values. […] Any other use of an invalid pointer v... |
69,477,518 | 69,486,588 | how to use and update panels in ncursesw | I'm currently coding in C++ in Ubuntu WSL2, using the <panel.h> header to create panels in ncursesw, as I need Unicode characters.
I've done a couple tests already, where the results are shown in the table below:
This is the code and result when creating a window with a WINDOW* and -lncursesw.
Code:
#include <panel.h>... | doupdate doesn't do a wrefresh (it's generally used after one more more windows is prepared using wnoutrefresh).
Without an explicit wrefresh, your program is getting the wrefresh done as a side-effect of getch — which refreshes stdscr, but that in turn has only the pending werase from initscr followed by the box call:... |
69,477,605 | 69,478,853 | Running 'grep' command using exec functions | I am trying to run grep command using execvp. I have to save the output into an output file like output.txt. The code, I have tried is given below:
#include<iostream>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
int main(){
pid_t pid = fork(... | The execvp() function calls directly the program and execute it with the provided arguments. The use of wildcards like * are provided by the shell terminal, so the grep is understanding the * as a file to be grep'ed.
If you want to call the grap using wildcards and the operator > you should use the function system() o... |
69,477,812 | 69,478,223 | Is there a way to read the function parameter as the exact name passed in c++? | For my program (C++), I need to read one of the function parameter as it is given while calling the function, for example:
void foo(int arg)
{
// I need to read the "arg" parameter here, not its value but the exact thing passed while calling the "foo" function
}
for example:
int bar = 10;
foo(bar); // I want to read "... | AS there is no build-in reflection in C++, in resulting code all ids will be gone. But you can emulate it by using stringize operator #, if you don't mind to use some wrappers. assert() macro in some implementations makes use of it.
#include <iostream>
void order(int arg1, int arg2, const char* str)
{
std::cout <<... |
69,478,685 | 69,478,993 | Declare a C++ std::list with elements that point to other elements in the list | I'm trying to use an std::list and an std::unordered_map to store a directed acyclic graph. Each list element stores a node key (unsigned) and its children. And the map stores, for each key, an iterator to the node in the list:
std::list<std::pair<unsigned, std::list<decltype(lst.begin())>>> lst;
std::unordered_map<uns... | Write classes. Within the definition of the class, it is an incomplete type, which means you can use pointers (or references) to it.
The children pointers can be non-owning, with the map owning all the nodes.
class Graph {
struct Node {
unsigned key;
std::vector<Node *> children;
};
std::un... |
69,478,707 | 69,478,883 | Default parameters and forward declaration | I have a class Property with a constructor in which I want default parameters, in a file property.h:
class Property {
Property(OtherClass* value = myApp->someValue) {...};
};
where myApp, of another type Application, is defined in another file that makes extensive use of this Property class. Since this other file #i... | The remarkable point is that the default argument of function parameters is resolved where the function is called (in opposition to where the function is defined). That gives the necessary space to solve OPs problem by yet another level of indirection:
Instead of accessing myApp->someValue, a helper function is introdu... |
69,478,965 | 69,509,782 | Compile C++ class with a header file to use it in python? | I have a my_class.h:
// my_class.h
namespace N
{
class my_class
{
public:
void hello_world();
};
}
with a my_class.cpp file.
// my_class.cpp
extern "C" {
#include "my_class.h"
}
#include <iostream>
using namespace N;
using namespace std;
void my_class::hello_world()
{
cout << "Hello... | Much to talk about, but I'll try to be brief:
extern "C" is going to make those symbols available in the C-syntax.
(You do want this)
C-syntax does not support classes or namespaces.
the python dynamic library loader is grabbing ALL the symbols - not
just your class. (It seems there is some confusion there with the na... |
69,479,041 | 69,483,541 | is there a z3 container that is equivalent to a map in C++? | I am working on a reverse engineering project where I am asked to perform backward slicing on assembly code. for a given assembly code register in a given assembly code function, I would like to detect all instructions inside the assembly function that perform an operation that updates that register. Long story short I... | An SMTLib array from bit-vectors to bit-vectors would work for this just fine. From an API perspective, there's no difference between a map and an array in SMT-solving: You address it using bit-vectors, just like what you wanted to do.
Your message suggests that you're worried you will not be able to "address" the arra... |
69,479,278 | 69,479,353 | Working of parameterized constructor in C++ when variables are initailized vs uninitialized | Below C++ code works.
#include<iostream>
using namespace std;
class Complex{
private:
int real, imag;
public:
Complex(int r=0, int i=0){
real = r; imag = i;
}
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3;
}
When the parameterized constructor's variables r and i are uninit... | The Complex constructor you show, with default arguments, can be called with two, one or zero arguments. If no arguments is used then the default values will be used.
But if you remove the default values, you no longer have a default constructor, a constructor that can be used without arguments.
It's really exactly th... |
69,479,670 | 69,480,706 | Android How to enable position independent flag -fpic for c++ code | I am using a c++ class in my application to store my constants/urls etc. For that I have configured ndk and CMakeLists.txt file. So I only have two files in my jni folder which is app-config-native-lib.cpp and CMakeLists.txt. Following is my CMakeLists.txt file
# For more information about using CMake with Android Stud... | The option -fPIC is the default on Android.
You can add other compiler options in CMakeLists.txt via:
set_source_files_properties(myfile.c PROPERTIES COMPILE_FLAGS " -mfpu=neon -fno-vectorize")
|
69,479,974 | 69,480,330 | Why a pointer to a class take less memory SRAM than a "classic" variable | i have a Arduino Micro with 3 time of flight LIDAR micro sensors welded to it. In my code i was creating 3 Global variable like this:
Adafruit_VL53L0X lox0 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox1 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox2 = Adafruit_VL53L0X();
And it took like ~80% of the memory
Now i am creating... | You use the same amount of memory either way. (Actually, the second way uses a tiny bit more, because the pointers need to be stored as well.)
It's just that with the first way, the memory is already allocated statically from the start and part of the data size of your program, so your compiler can tell you about it, w... |
69,480,128 | 69,493,071 | clang-tidy bugprone-unused-return-value: how to check all functions? | I have clang-tidy checking for unused return values with bugprone-unused-return-value check. Unfortunately it only checks return values from list of functions specified with CheckedFunctions parameter. I would like to check usage of return value from all functions, but am not able to figure out what to write to Checked... | Unfortunately bugprone-unused-return-value check is not built to check all functions.
You can either specify CheckedFunctions or if you omit the specification then a default list of functions will be used. There is no possibility of using wildcards or regular expressions here.
See the documentation. I also checked the ... |
69,480,604 | 69,482,653 | C++ SDL2 can't load any file | I'm using SLD2 in order to make a game, All was working perfectly since now.
I think there is a problem the loading file system.
for example, when i tried to load a bmp :
#include <iostream>
# include "SDL.h"
int main(int argc, char* argv[]) {
SDL_Init(SDL_INIT_VIDEO); // Initialize SDL2
SDL_Window* window = ... | There is nothing wrong with SDL2. The path you are entering is probably invalid because it says "couldn't load ( some random weird chars )", that means SDL couldn't find the file. You are using ../ to indicate that your background.bmp file is in the parent directory of the current working directory. If you are using an... |
69,480,630 | 69,483,669 | Boost concept check warnings | Given this code using boost 1.75 / gcc 11
#include <boost/bimap.hpp>
#include <string>
#include <iostream>
int main()
{
typedef boost::bimap<std::string, int> bimap;
bimap animals;
animals.insert({"cat", 4});
animals.insert({"shark", 0});
animals.insert({"spider", 8});
std::cout << animals.left.count("ca... | As the messages suggest, you can suppress the -Wnonnull diagnostics:
g++ -std=c++17 -Wno-nonnull ...
https://godbolt.org/z/YEafWTqex
|
69,480,783 | 69,485,658 | Qt 6.2: QMediaPlayer & QByteArray | Good day.
Has anyone tried QMediaPlayer in Qt 6.2 already?
I'm trying this code, but Media Status always remains as "NoMedia" and no any sound :).
Full test project: https://github.com/avttrue/MediaPlayerTest
#include "mainwindow.h"
#include <QDebug>
#include <QBuffer>
#include <QFile>
#include <QAudioOutput>
#includ... | As the docs points out:
void QMediaPlayer::setSourceDevice(QIODevice *device, const QUrl
&sourceUrl = QUrl())
Sets the current source device.
The media data will be read from device. The sourceUrl can be provided
to resolve additional information about the media, mime type etc. The
device must be open and readable.
Fo... |
69,481,286 | 69,481,509 | how to store count of values that are repeated in an array into map in c++? | I was trying to store count of words repeated in an array of string...
int countWords(string list[], int n)
{
map <string, int> mp;
for(auto val = list.begin(); val!=list.end(); val++){
mp[*val]++;
}
int res = 0;
for(auto val= mp.begin(); val!=mp.end(); val++){
if(val->second == 2) ... | The reason for the error is that list is an array, which does not have a begin method (or any other method).
This could be fixed by changing the function to take a std::vector instead of an array.
If you want to keep it as an array, the for loop should be changed to this, assuming n is the length of the array:
for(auto... |
69,481,294 | 69,481,362 | Use initializer list as default value for function/method parameter | I want to do something like
void A (int a[2] = {0,0}) {}
but I get
<source>(1): error C2440: 'default argument': cannot convert from 'initializer list' to 'int []'
<source>(1): note: The initializer contains too many elements
(MSVC v19 x64 latest, doesn't work with gcc x86-64 11.2 either)
Again, I cannot figure what ... | The reason this does not work is that this
void A (int a[2]) {}
is just short hand notation for
void A (int* a) {}
You cannot pass arrays by value to functions. They do decay to pointers to the first element. If you use a std::array<int,2> you can easily provide a default argument:
void foo(std::array<int,2> x = {2,2... |
69,481,611 | 69,482,410 | Using function to create a grading system | Question: I honestly have no idea how to answer test #1, it only needs one input and will output one when the question is asking the user will input ten (10) consecutive numeric grades that may or may not have a decimal.
#include <iostream>
#include <array>
#include <iomanip>
char getLetterGrade(double);
using namespac... |
"Using function to create a program that validate and evaluate 10 numeric grades to its respective letter grade"
Well as given, the assignment does not require you to compute the average of the grades.
On the other hand, from the code sample given by your teacher, you are expected to define your grade to letter conve... |
69,481,713 | 69,507,167 | how to link a c++ library to a c++ source code when it has a specific linker script to compile? | i have these files:-
/lib
kernel.hpp
kernel.cpp
main.cpp
when i use
gcc -m32 -c main.cpp -lstdc++ -o main.o -llib/kernel.hpp
it says
[function name]([type of argument 1], [type of argument 2]) is not declared in this scope
how to fix?
| I started writing a comment, but got to be too long, so we'll make it an answer instead. I don't think it in fact will answer your question, but it may point you in the right direction.
Let's clear up a misconception, c++ is not a superset of c; there are c constructs that c++ does not support. If your code is c++, you... |
69,482,003 | 69,482,191 | How to convert int to string in a ternary operation | When trying to do a ternary operation using an integer and string such as:
for (int num = 0; num < 100; num++) {
cout << (i % 10 == 0) ? "Divisible by 10" : num;
}
You end up with the following exception
E0042: operand types are incompatible ("const char*" and "int")
If you were to try to cast num to const... | If you insist on the conditional operator, you could write this:
for (int num = 0; num < 100; num++) {
(num%10==0) ? std::cout << "Divisible by 10" : std::cout << num;
}
If you want to stay with yours, you need to convert the values to some compatible types. There is no way around that. The conditional operator is... |
69,482,527 | 69,483,791 | Changing array value through a function | I want to design a program of n = 3 instances. Each instance is pointing to an 'instance' position of an array. Each instance is composed of two values: {error, control}. When calling a function "run_instance" these two values change to other ones.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#in... | There are a few problems:
n should be const or constexpr:
const int n = 3;
or
constexpr int n = 3;
arr should be an array of doubles:
double arr[n][2] { ... };
An array should be added in the parameter list in run_instance:
double run_instance(double** arr, int instance, double measured_error, int Kp, int Ki)
And f... |
69,482,846 | 70,251,547 | Template argument deduction Doesn't Work for Function Template <unresolved overloaded function type> | I am trying to understand how template argument deduction works in C++. And so writing out different examples. One such example which doesn't work and i can't understand why is given below:
#include<iostream>
template<int var, typename T>
void func (T x)
{
std::cout<<x<<std::endl;
}
template<typename T>
void SomeF... |
SomeFunc(func<5,int>);
You pass a pointer to the function func<5,int> and T becomes void(*)(int) which is fine. It also works inside SomeFunc when you use the function pointer a to call the function it is pointing at.
SomeFunc(func<5>);
Deduction is not possible. The compiler is not able to look forward to see th... |
69,482,892 | 69,483,004 | Please explain the use of for_each function in this c++ code | I was going through techiedelight article link
I didn't get the meaning of [&m](char &c) { m[c]++; } in std::for_each(s.begin(), s.end(), [&m](char &c) { m[c]++; });
#include <iostream>
#include <unordered_map>
#include <algorithm>
int main()
{
std::unordered_map<char, int> m;
std::string s("abcba");
s... | [&m](char &c) { m[c]++; }
this is a lambda. A lambda is an anonymously typed function object using shorthand.
It is shorthand for roughly:
struct anonymous_unique_secret_type_name {
std::unordered_map<char, int>& m;
void operator()(char& c)const {
m[c]++;
}
};
std::for_each(s.begin(), s.end(), anonymous_uniq... |
69,483,490 | 69,485,329 | Apply stateful lambda to integer sequence values | I am playing around with trying to implement the numeric literal operator template.
#include <string_view>
#include <cstdint>
#include <cmath>
#include <iostream>
#include <boost/mp11/integer_sequence.hpp>
#include <boost/mp11/algorithm.hpp>
using namespace boost::mp11;
template <char... Cs>
[[nodiscard]] constexpr au... |
So I would like to transfer ints, that are <0,1,2> into something like
<100,10,1>
First, you can convert std::index_sequence to std::array, then perform your operations on it as you normally do, and finally, convert std::array to std::index_sequence again.
In order for the stateful lambda to work at compile-time, we ... |
69,483,521 | 69,484,057 | template deduction and implicit constructors | Is there a way to make template deduction work with (implicit) conversion? Like the following example:
template<typename T> struct A {};
template<typename T> struct B
{
B(A<T>); // implicit A->B conversion
};
template<typename... Ts> void fun(B<Ts>...);
int main()
{
A<int> a;
fun(B(a)); // works
fun(... | Template argument deduction does not consider any potential type conversions - mainly because deduction happens before any such conversions can happen.
Basically, when the compiler sees fun(a), it first gathers a set of foo functions that are eligible to service that call. If a foo function template is found, the compi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.