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 |
|---|---|---|---|---|
68,812,330 | 68,812,356 | Is there a way to pass user data for a setter without using an extra variable in C++? | I'm still new to C++ and so far I used to pass static values to setter methods. Now I'm trying to pass user data to the methods, but so far I can only do this using an extra variable as follows.
Class:
class Square
{
private:
double length;
public:
void setLength(double l);
double getlength();
double c... | You can either set the value using a variable or you can send a value, but the thing is that if you want to do it directly, it will break the law of Encapsulation. We can the class attributes private to make sure of Encapsulation. So for that, the thing you did is perfect β.
|
68,813,119 | 68,813,147 | How to call a template method of template argument? | Code:
#include <iostream>
struct S {
template<typename T>
void method() const;
};
template<typename T>
void S::method() const {
std::cout << "Hello World\n";
}
template<typename Obj>
void func(const Obj& obj) {
obj.method<int>();
}
int main() {
S s;
func(s);
}
When I try to compile this cod... | You have to add template:
template<typename Obj>
void func(const Obj& obj) {
obj.template method<int>();
}
|
68,813,991 | 68,825,580 | Linker issue when usiing nana library on Ubuntu 20.04 | I have been using nana library for a while for my application on Windows and it works great. Now I am trying to do a Linux build but I can not seem to link nana to my application correctly.
I have tried this but it also did not seem to work
I have created a small example to demonstrate the issue. Here is my main.cpp
#i... | Here's a build that actually works:
cmake_minimum_required(VERSION 3.21)
project(NanaTest VERSION 0.1.0)
include(FetchContent)
FetchContent_Declare(
nana
GIT_REPOSITORY https://github.com/cnjinhao/nana.git
GIT_TAG v1.7.4
GIT_SHALLOW TRUE
)
FetchContent_MakeAvailable(nana)
add_executable(NanaTest ma... |
68,814,264 | 68,814,292 | How to declare an array of functions? | Suppose I want to declare an array of functions, and try the following
int (*funcs)(int, int)[10];
But turns out that the following declaration stands for an function returning an array, which does not compile.
How can I declare an array of functions properly?
| Strictly speaking you may not declare an array of functions. You may declare an array of function pointers.
It seems you mean
int (*funcs[10])(int, int);
Another way is to introduce a using declaration (or a typedef declaration) like for example
using FP = int( * )( int, int );
FP funcs[10];
or
using FUNC = int ( in... |
68,814,286 | 68,817,852 | How to remove some functions in a template specification for void type in C++? | I have a class TriggerEvent:
template <typename ReturnType, typename... ArgumentTypes>
class TriggerEvent<ReturnType(ArgumentTypes...)>
{
public:
using EventCallback = std::function<ReturnType(ArgumentTypes...)>;
using InvokeCallback = std::function<bool(const ReturnType&)>;
void Subscribe(EventCallback&& callb... | You can use a helper template to generate the proper invoke callback type:
bool(T)
bool() when T == void
Like so:
template <typename ReturnType>
struct invoke_callback_ref {
using type = bool(const ReturnType&);
};
template <>
struct invoke_callback_ref<void> {
using type = bool();
};
template <typename ReturnT... |
68,814,590 | 68,815,028 | Is there a way to return custom struct from a function in C++? | I wanted to know if it were possible to somehow return a custom struct from a function.
Actual use case: I have a dictionary in the form of a string, separated by some separator. Eg: a FIX message: "8=FIX.4.4,8=MKT...", while parsing this message, I want to have these key-value pairs extracted, ideally in a form of a s... | As said in comment, you can store your data in a map of variants:
#include <iostream>
#include <map>
#include <variant>
using std::cout, std::endl;
using var_t = std::variant<int, std::string, float, double>;
int main()
{
std::map<int, var_t> myMap {
{ 10, "hello world" },
{ 1, 5 },
{ 2... |
68,814,713 | 68,822,436 | MFC SDI changed menu using SetMenu but how to change accelerators? | I have a SDI application. I want to change the menu based on certain conditions in run-time.
I use this code block to change the menu and it does it's job.
menu = GetMenu();
SetMenu(NULL);
menu->DestroyMenu();
menu->LoadMenu(IDR_MAINFRAM_2));
SetMenu(menu);
My only problem is that the accelerators for the new menu doe... | This is straight forward. Assuming you do your manipulation from the CFrameWndEx-derived class, just call:
LoadAccelTable(MAKEINTRESOURCE(IDR_MAINFRAM_2));
MFC will process that accelerator table for you
|
68,814,812 | 68,814,813 | What is the difference between LNK2001 and LNK2019 errors in Visual Studio? | In Visual Studio there are two different error numbers for the infamous unresolved symbol error in C++: LNK2001 and LNK2019. Looking at their documentation they give extensive lists of the usual and some more exotic possible causes and the general explanation at the top is identical.
So, why are there two different err... | Having a closer look I've seen that LNK2019 extends LNK2001 with referenced in function '<function>'.
So, I assume that Visual C++ throws LNK2019 when it can determine a function using the symbol in question and else LNK2001, while otherwise the cause of the error is the same.
In my case I've received LNK2001 for an un... |
68,814,831 | 68,817,696 | Dllmain function is not being called | I searched here but none of these questions helped me so yeah I'll explain:
My Dllmain function is not being called when it attaches to a process (rundll32.exe) in visual studio project settings I changed it to attach to rundll32.exe it was supposed to show a messagebox on attach but it just doesn't do it.
My code:
// ... | If you use rundll32.exe as the loader program, you must call it using an entry point, like this:
In this case, DllMain has been called, but you'll get a messagebox error like :
Error in D:\blah\blahblah.dll
Missing entry: x
That's normal, it's because you don't have exported any externally callable function from your... |
68,815,240 | 68,815,511 | Template argument as function unnamed argument | This question continues Non-static data members class deduction
Here are the unnamed argument functions, that I'm using to return std::string representation of the data type
struct Boo {};
struct Foo {};
std::string class2str(const double) { return "Floating"; };
std::string class2str(const int) { return "Fixed Point... | (As I started writing the answer there was no answer to the question, but as I was about to post it I saw @Jarod42's answer which already show the tag dispatch approach. Posting this answer nonetheless as it uses a slightly different approach of full specializations of a deleted primary template, instead of non-templat... |
68,817,270 | 68,818,222 | Is it possible to create an interface without using dynamic dispatch? | Background
I'm writing the firmware for an embedded project with a couple of 'choices'. For example, the device uses a humidity sensor, but it supports multiple different humidity sensors.
To implement this nicely, I have written an (abstract) base class as an interface to represent the sensors:
class HumiditySensor {
... | You have only one class, so there is no polymorphism by definition. You don't need inheritance, interfaces, CRTP, or any such hacks.
class SHTHumiditySensor /* no ': public HumiditySensor' needed */ {
private:
SHTSensor &sht;
public:
explicit SHTHumiditySensor(SHTSensor *sht);
void readSample() /* no virtua... |
68,818,234 | 68,832,963 | Importing header files and linking .a file in CMake | Trying to put Skia in my CMake project. How do I tell CMake to link my executable against libskia.a and use the header files inside ext/skia so that I can include them like so?
#include <skia/subdirectory/headerfile.h>
My project structure is currently the following:
.
βββ CMakeLists.txt
βββ CMakeLists.txt.user
βββ ex... | In your primary CMakeLists.txt file you would simply add the following:
target_link_libraries(project skia)
If CMake cannot find the library, you can either do:
target_link_libraries(project /full/path/to/libskia.a)
or:
link_directories(/path/to/libraries)
target_link_libraries(project skia)
|
68,818,421 | 68,818,627 | Query in implementing queue in linked list in c++ | I have tried to implement queue using linked list. This is the code i wrote. When i try to use the disp() method i get a infinite loop running. I am not able to find the error in the logic. I fail to understand how the line while(temp!=NULL) and incrementing the temp never ends.
#include<iostream>
using namespace std;... | Your dequeue is not properly dequeueing the first element:
node *temp =front;
if(temp!=NULL){
int x =temp->x;
temp=temp->next;
delete temp;
return x;
}
temp = temp->next makes temp point to the second node and in the next line you delete that seco... |
68,818,880 | 68,819,001 | How to write a function with an arbitrary number of parameter packs | I was trying to implement some generic functions for my protocol working over UDP sockets for game engines (for learning purposes), when I have stumpled upon a need to have a function that must accept arbitrary number of tuples, every one of which might have their own number of different parameters.
Example of usage:
i... | Using this type trait to check if a type is a specialization of a template
template <class T, template <class...> class Template>
struct is_specialization : std::false_type {};
template <template <class...> class Template, class... Args>
struct is_specialization<Template<Args...>, Template> : std::true_type {};
You c... |
68,819,067 | 68,819,556 | Is there a way to print integers normally that are assigned to a pointer array? | I am creating a program that involves pointers and arrays and I have stumbled upon a problem.
Basically, I created three integers that would get its value from the user's input and later declared them all in an array in order to change all of their values in one single loop.
Then I declared a pointer which uses the arr... | If you want to change values of salary1, salary2, salary3, you should declare salary[3] for int*, not int!
int salary[3] = { salary1, salary2, salary3 };
to
int* salary[3] = { &salary1, &salary2, &salary3 };
then your pointer also should be double-pointer like:
int** pntr = salary;
finally you should dereference (pntr ... |
68,820,113 | 68,820,397 | get nan error for the result of the normalization function in c++ | i would like to use the glm::normalize() in C++ to normalize a glm::vec3 vector, but the result of the normalization is nan, can you please help me to resolve it? Thank you!
this is my code below:
glm::vec3 a(4.58463e-41,-9.83211e-09,-2.4355e+26);
glm::vec3 n = glm::normalize(a);
cout<<n.x<<n.y<<n.z<<endl;
the result ... | If you need (I doubt you do) to normalize such crazy long vectors, you should make sure their length is reasonable to start with. glm is limited to float (at least for this API).
double x = 4.58463e-41;
double y = -9.83211e-09;
double z = -2.4355e+26;
// reduce to reasonable range while keeping the normalized value th... |
68,820,500 | 68,820,619 | take 4*4 matrix from user to test if it includes 2*2 sub-matrix have the same value | i just need the user to enter 4*4 matrix of character, the out put will be yes or no according to if there is a 2 * 2 sub-matrix have the same input.
the code is always print false.
the code is:
#include <iostream>
using namespace std;
int main()
{
//input
char color[4][4];
for (int i = 0; i < 4; i++) {
... | This condition is wrong:
if (color[i][j] == color[i][j + 1] == color[i + 1][j] == color[i + 1][j + 1]
For simplicity, consider
if (a == b == c)
which is parsed as
if ( (a == b) == c)
The result of a==b is compared to c. The result of a==b is either true or false which can be converted to 1 or 0, respectively.
You w... |
68,821,113 | 68,821,310 | Combining ranges adaptors and std::source_location got strange results | Consider the following useless code:
#include <ranges>
#include <source_location>
#include <iostream>
int main() {
auto lines = std::views::iota(0, 5)
| std::views::transform(
[](int, const std::source_location& location = std::source_location::current())
{ return locati... | gcc is correct, the program is completely valid.
And GCC outputs strange line number 61 no matter which row the std::source_location::current() is in:
That's because the default function argument, current(), is evaluated at the point of the function call, which has nothing to do with where the function is declared.
A... |
68,822,047 | 68,822,085 | How to construct a tuple with four elements from two pairs with matching data types in C++? | I have a function f(), that returns a std::pair<A, B> with some types A and B. And I have another function g(), that calls f() twice and returns a std::tuple<A, B, A, B>. Is there a way to construct the return tuple directly from both calls to f()? So I would like to shortcut the last three lines of my current code:
st... | Yes, there is std::tuple_cat. Even though cppreference says that...
The behavior is undefined if any type in [arguments] is not a specialization of std::tuple. However, an implementation may choose to support types (such as std::array and std::pair) that follow the tuple-like protocol.
I've tested it and all major st... |
68,822,650 | 68,825,004 | Boost Spirit (x3) failing to consume last token when parsing character escapes | Using boost spirit x3 to parse escaped ascii strings I came across this answer but am getting an expectation exception. I have changed the expectation operator in the original to the sequence operator to disable the exception in the code below. Running the code it parses the input and assigns the correct value to the a... | Your input isn't terminated with a quote character. Writing it as a raw string literal helps:
std::string const qinput = R"("Hel\"lo Wor\"ld)";
Should be
std::string const qinput = R"("Hel\"lo Wor\"ld")";
Now, the rest is common container handling: in Spirit, when a rule fails (also when it just backtracks a bran... |
68,822,791 | 68,827,832 | Unpacking 8 to 16-bit using SIMD: AVX2 version mixes up the order | I am trying to use SSE2 to unpack text with zeros, and extend that to AVX2. Here's what I mean:
Suppose you have some text like this: abcd
I'm trying to use SSE2 to unpack abcd into a\0b\0c\0d. The \0's are zeros. This of course being applied to 16 characters instead of 4.
I was able to do that using this code (ignore ... | As I can see the right answer already has been received from @PeterCordes. Nevertheless I want to supplement it with small helper function:
template <int part> inline __m256i Cvt8uTo16u(__m256i a)
{
return _mm256_cvtepu8_epi16(_mm256_extractf128_si256(a, part));
}
|
68,822,989 | 68,823,033 | Use struct with forward declaratio | I need to use a struct before it was actually declared, how is that possible ? Thank you.
I need to use C1 before it was declared, but I get incomplete type error.
struct C1;
struct Cap
{
C1 l1;
};
struct C1 : Cap
{
};
| You can't use C1 in the Cap struct by value as to calculate the size of a Cap object would require knowing the size of a C1.
You could use it by reference (C1&) or pointer (C1*) as the size of a pointer is a known size.
|
68,823,581 | 68,827,471 | using directive in header file | I have a class that I need to convert to a template class. For this, I am moving the implementation from class.cpp to class-in.h that will then be included at the end of class.h.
The implementation has a few using ... directives as well as a gflag DEFINE_bool. I need to use these in the class-inl.h file but I am told t... | My recommendation is to not put usings into header files if they are only used for implementation. They unnecessarily leak symbols and implementation details. If you define using my_shortcut_for_long_type=...., someone is bound to start using it and code breaks when you decide to change it.
It won't kill you to write s... |
68,823,655 | 68,823,784 | CMake skips standard precompiled headers | I'm new to C++, really trying to get familiar with CMake, but there's always something wrong.
I'm using CLion with Cygwin and G++11 package installed
My CMakeLists.txt file:
cmake_minimum_required(VERSION 3.20)
project(testing)
set(CMAKE_CXX_STANDARD 20)
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
end... | Here are a few things I have tried when debugging similar problems:
If in doubt, delete and re-create your build directories. CMake caches certain variables and can sometimes get into a weird state. A fresh directory will remove any uncertainty.
CMake should print out what compiler it is using - Check that and make ... |
68,823,918 | 68,829,436 | Warning: range-based for loop is a C++11 extension | While trying to compile a simple range based for loop on MacOS Big Sur, I got this warning:
warning: range-based for loop is a C++11 extension [-Wc++11-extensions]
I tried using clang++ and g++ but both gave the same warning. Is there a way to always compile with C++11 without having to use -std=c++11 and without usin... | To provide this question with a proper answer, based on the discussion in the comments:
Compilers such as GCC and Clang set the default in their source code and it cannot be changed by, e.g., modifying a config file. The only way to change the default would be to change it in the source code and to compile the compiler... |
68,824,798 | 68,825,098 | Typetrait to get value type of contiguous-memory containers | I need a typetrait that would return value type for the following "contiguous-memory" types (to which operator[] can be applied):
std::vector<T, Args...>, std::array<T, N>, T[], T[N], and T* (with possibly CV qualifiers like T* const). The trait should return T for all above types.
Is there a more concise implementatio... |
I need a typetrait that would return value type for the following "contiguous-memory" types (to which operator[] can be applied):
To "extract" the required type, it seems to me that you can simply use the operator[] itself, removing references, volatiles and consts. See the following helper struct
template <typename ... |
68,824,925 | 68,824,967 | Is extern "C" turning C code to C++ code, or just allowing the compiler to compile C code as C++ code? | I have a small issue.
I thought that using using extern "C" will turn the C code into C++ code directly.
#ifdef __cplusplus
extern "C" {
#endif
ENUM_J1939_STATUS_CODES CAN_Send_Message(uint32_t ID, uint8_t data[], uint8_t delay);
ENUM_J1939_STATUS_CODES CAN_Send_Request(uint32_t ID, uint8_t PGN[], uint8_t delay);
bool... | You use extern "C" { ... } in C++ code, around declarations of external functions which are C functions, not C++ functions.
extern "C" { ... } does not somehow "turn C code into C++ code".
It does not turn C++ code into C code, either.
You use extern "C" { ... } when you have some other function(s) to call, and those o... |
68,825,164 | 68,825,247 | How to create template with | The following code does not compile. Is there a different syntax to achieve that?
template <typename T>
struct A {};
template <typename T>
struct B {};
template <typename S, typename T>
struct C : S<T> {}; // unknown template name 'S'
int main() {
A<int> a;
B<int> b;
C<A,int> c; // Use of class template 'A' r... | The C struct template needs to use a "template template parameter"
template <typename T>
struct A {};
template <typename T>
struct B {};
template <template<typename> typename S, typename T>
struct C : S<T> {};
int main() {
A<int> a;
B<int> b;
C<A, int> c; // Use of class template 'A' requires template ... |
68,825,571 | 68,826,050 | C++ vectors not initializing even when I included the necessary headers | Basically what the question says: I'm unable to initialize a vector of any kind in C++;
Here is my code:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
//The error occurs under the word "lines" in the following line
vector<string> lines{"Hello", "ther... | To compile your code using C++11, change your tasks.json file to this:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: clang++ build active file",
"command": "/usr/bin/clang++",
"args": [
"-std=c++11",
"-g",
"${file}",
"-o",
... |
68,825,619 | 68,825,763 | How do I get this Linked List Stack implementation to run in C++? | I am trying to implement a Stack using a Linked List in C++. When I run my code, nothing is outputted to the console, but it compiles without errors. The problem seems to come from my pointer for the top node. I initially made the top node without a pointer, but that created problems of its own when I tried to initiali... | There are multiple, fundamental errors in the shown code related to how pointers and objects work in C++. It's not just one issue or error, all of these issues must be fixed before it works correctly.
Node* prev;
This is a pointer member of the Node class. Before using an object referenced by a pointer, the pointer mu... |
68,826,159 | 68,832,887 | how to return a response from a curl multi handle c++ libcurl | php has multi_get_content(), but i do not see any clear way to retrieve the response from a multi transfer when complete. I can only retrieve the CURLcode from it using the CURLMsg* variable (msg->data.result).
| Use the CURLOPT_WRITEFUNCTION option to setup a callback that receives all incoming data and stores it appropriately. An example of such callback that stores the entire response in memory is getinmemory.c (While that example uses the easy interface, the callback works the exact same way for the multi interface.)
|
68,826,162 | 68,826,934 | gcc and clang differs in behavior when calling variadic member function template in a variadic class template | The following code
#include <iostream>
template <class... Ts>
struct A
{
template <Ts ...Args>
static void f() {
(std::cout << ... << Args) << std::endl;
}
};
int main() {
A<int, int, int, int>::f<0, 1, 2, 3>();
}
with -std=c++17, compiles with clang 12.0.1 and prints 0123, but fails to compi... | This is clearly a GCC bug. There are several bug reports, for example, 77731, 88580 and 91247. It will be fixed in GCC 12.
|
68,826,689 | 68,845,488 | Find a path between 2 points in a maze with minimum turns | The problem:
Given a 2D matrix consist of 0 and 1, you can only go in location with 1. Start at point (x, y), we can move to 4 adjacent points: up, down, left, right; which are: (x+1, y), (x-1, y), (x, y+1), (x, y-1).
Find a path from point (x, y) to point (s, t) so that it has the least number of turns.
My question:
I... | I have found a way to solve this problem, storing directions and using BFS() to reduce the time complexity:
struct Node{
short row, col;
char dir;
Node(int _row = 0, int _col = 0, int _dir = 0){
row = _row; col = _col; dir = _dir;
}
};
void BFS(){
memset(turns, 0x3f, sizeof turns);
deq... |
68,827,119 | 68,827,177 | How to choose class's operator== overloading over the template operator==? | I have overloaded the operator== for several types, using both template and in-line class method. But when come to the reference of an object as the lhs. The template operator== overloading will be used. Why not the operator== overloaded in the class definition?
#include <iostream>
template <typename T0, typename T1>
... |
Is it possible to force the compiler using the overloading defined
inside the class?
Yes, simply make the operator== overload a const qualified function, so that it will act on the const object of Obj.
bool operator==(const Obj& rhs) const /* noexcept */
{
std::cout << "Obj == \n";
return a == rhs.a; // meani... |
68,827,267 | 68,827,449 | In mouse hooking, the wheel delta is always 0 | #include <iostream>
#include <windows.h>
LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam){
if(wParam == WM_MOUSEWHEEL){
std::cout << "wheel: " << GET_WHEEL_DELTA_WPARAM(wParam) << std::endl;
}else{
MOUSEHOOKSTRUCT* mouselparam = (MOUSEHOOKSTRUCT*)lParam;
std::cout << "etc: " << wPara... | GET_WHEEL_DELTA_WPARAM() only works with the wParam of a real WM_MOUSEWHEEL window message, not the wParam of a WH_MOUSE_LL hook.
In the hook, the wParam is just the message identifier by itself, nothing more. ALL of the mouse details are stored in a MSLLHOOKSTRUCT struct pointed by the lParam. Which you attempted to ... |
68,827,601 | 68,831,497 | How to access nested QStandardItemModel's items from QML? | Background
I have a tree-like QStandardItemModel, whose items I would like to access from QML.
Here is how the model is defined on the C++ side:
backend.h
class Backend : public QObject
{
Q_OBJECT
Q_PROPERTY(QStandardItemModel *model READ model CONSTANT)
public:
explicit Backend(QObject *parent = nullptr);
... | The problem is in these two lines: rootIndex: modelIndex(index).
index is the index of the 'parent' model, but modelIndex(...) is the method of the current model.
I've tried it with this (slightly modified) piece of code and it worked:
Repeater {
model: DelegateModel {
id: model1
model: backend.mo... |
68,828,035 | 68,828,293 | Which one works faster? | Do these 2 have any differences?
if (condition)
{
std::cout << "Condition is true";
}
else
{
std::cout << "Condition is false";
}
OR
if (condition)
{
std::cout << "Condition is true";
return 0;
}
std::cout << "Condition is false";
I know that is not good to use the second one because maybe you have so... | I modified the original question a bit as follows,
void f1() {
int a = 0;
if (a > 0) {
a = 1;
} else {
a = 2;
}
}
void f2() {
int a = 0;
if (a > 0) {
a = 1;
return;
}
a = 2;
}
Here are the compiled assembly. f1() and f2() are nearly identical.
f1():
... |
68,828,772 | 68,828,910 | Safe and maintainable way to convert int to enum class | I am looking for a safe and maintainable way to convert an int value to enum class. I know i can convert inegral values to enum class by simply using static_cast, but i want to make sure the value to be converted really has a representation in the enum class either before or after converting.
Everything that comes to m... | You can create both the enum and the switch statement with a macro, which allows you to safely add new values:
// In header file
#define ENUM_VALUES(x) \
x(A) \
x(B) \
x(C)
#define CREATE_ENUM(name) \
name,
enum class Entries { ENUM_VALUES(CREATE_ENUM) }
// In source file
#define CREATE_SWITCH(name) \... |
68,828,838 | 68,829,065 | Is it valid to create closure (lambda) objects using `std::bit_cast` in C++20? | A colleague showed me a C++20 program where a closure object is virtually created using std::bit_cast from the value that it captures:
#include <bit>
#include <iostream>
class A {
int v;
public:
A(int u) : v(u) {}
auto getter() const {
if ( v > 0 ) throw 0;
return [this](){ return v; };
... |
But is the program well-formed according to the standard ...
The program has undefined behaviour conditional on leeway given to implementors. Particularly conditional on whether the closure type of the lambda
[this](){ return v; };
is trivially copyable from; as per [expr.prim.lambda.closure]/2:
The closure type... |
68,829,012 | 69,955,794 | Heap buffer overflow in Search a 2D Matrix on LeetCode | I am coding a solution for LeetCode problem 74. Search a 2D Matrix:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous ro... | This is the best optimal solution
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(!matrix.size()){
return false;
}
int n = matrix.length;
int m = matrix[0].length;
int a=0;
int b = (n*m)-1;
... |
68,829,535 | 68,830,648 | Dump stack and heap memory to file, then load it back into RAM? | As the question states. I am certain that it is possible, but I can't find information on the subject.
I'm doing this as an experiment right now, the idea is basically to do the following scenario:
boot up linux (just because I don't like windows)
do some random stuff
dump stack and heap memory to 1 or 2 files
do some... |
EDIT: I thought searching for sysctl hibernate sources would help, but I can't even seem to find those
It'll need to be done in the kernel, since there's a load of kernel & driver state, and it needs access to all running processes.
You can start from power/hibernate.c.
If you just skip the call to swsusp_arch_suspen... |
68,829,565 | 68,829,664 | Template conversion operator issue | I have done a bit of browsing and this was the most relevant link that I could find, however it does not answer my question
Question: Why does the template substitution fail and the following does not compile?
template <typename T>
struct A
{
A() {};
A(T value) : val(value){}
operator T() { return this->val;... | std::operator+(std::basic_string) is a set of operator templates, template argument deduction needs to be performed on the 2nd operand test. But implicit conversion (from A<std::string> to std::string) won't be considered in template argument deduction.
Type deduction does not consider implicit conversions (other than... |
68,829,718 | 68,845,783 | C++ QT best way to pass a message higher in class structure | I am currently implementing a program that realizes TCP communication between PC program and external devices in QT. The problem I have is more general, but I will use this one as an example.
My class hierarchy looks like this:
Program
/ \
Server_A <--> Server_B <--- External system
... | Finally, I came up with a solution. It was necessary to implement ExternalCommand class, which instances were created in Server_B.
In the minimal solution, it has: 1. Field QString Message, 2. Method QString getMessage(), 3. Method void finish(QString), 4. Signal void sendToExternal(QString)
When I read the message sen... |
68,830,544 | 68,832,927 | is it possible to specify templated class in concepts? | say I have a function that converts string to numeric type as below
template<class T>
T to_t(const std::string& str) {
return boost::lexical_cast<T>(str);
}
and I want to make the function being able to convert numeric str to std::chrono::duration, so I can write code like to_t<std::chrono::seconds>("1234") to_t<s... | Your concept can be defined as:
template <class Dur>
concept stl_duration = std::same_as<
Dur, std::chrono::duration<typename Dur::rep, typename Dur::period>
>;
Or more generally, use Barry's Specializes:
template <typename T, template <typename...> class Z>
inline constexpr bool is_specialization_of = false;
templ... |
68,831,096 | 68,831,217 | Why can't std::stringstream be default constructed when it's static inline? | The following compiles fine (on g++ 8.3.0-6 and --std=c++17) with the std::stringstream being a non-static class member:
#include <iostream>
#include <sstream>
class Foo {
public:
std::stringstream ss;
};
int main() {
Foo f;
f.ss << "bar\n";
std::cout << f.ss.str();
}
But the following doesn'... | This is almost certainly a compiler bug. It is a little strange that the compiler knows about the constructor overload in one case but not the other, though it might have something to do with the constructor being explicit.
This does compile with 8.3:
#include <iostream>
#include <sstream>
class Foo {
public:
... |
68,831,220 | 68,842,273 | PfRingDevice for lo interface | I'm using PF_RING and PCAP++ to capture and analyze net traffic.
Sometimes usefull to use lo interface (loopback): for tests and regression analyze.
By the way, there is constant silence in the loopback until you break it by your command.
PF_RING may give me loopback traffic.
#include <dnet.h>
#include <string>
#includ... | It seems that PF_RING doesn't support lo, please see this GitHub issue: https://github.com/ntop/PF_RING/issues/221
I tested it also and lo isn't recognized by PF_RING.
However, as suggested in the issue, you can set up a dummy interface which PF_RING can see:
# ip link add dummy0 type dummy
# ip link set dev dummy0 up
... |
68,831,340 | 68,831,414 | How can I validate the data in this format UEEW123456 | example:
string id;
cout << "Enter the ID: ";
cin >> id;
The format must be like this UEEW123456, which contain 4 characters in front and 6 integers at back. How can I validate and make sure the input follow this format and prompt user to enter again if he/she did not follow this format.
| You can use regular expressions for this.
#include <cassert>
#include <string>
#include <regex>
bool is_valid(const std::string& input)
{
static std::regex expression{ "[A-Z]{4}[0-9]{6}" };
std::cmatch match;
return std::regex_match(input.c_str(), match, expression);
}
int main()
{
assert(is_valid("UE... |
68,831,419 | 68,831,744 | Adding missing arguments to function pointer in another function | I have some functions which I would like to call using function pointer. They have different arguments and data types.
void processVec2(
float a,
float b,
array<vector2> vec2_array,
int i,
int j)
{
/// some code here
}
void processVec3(
float a,
float b,
float c,
float d, ... | You need to change loopFunction to take the additional arguments you want to pass through, expand the parameter pack in the function pointer type and pass the arguments when you call the function pointer:
template<typename T, typename ... Args>
void loopFunction(
int iter,
array<T> array,
void (*func... |
68,831,600 | 68,831,666 | Error: "No matching function for call to Date::Date()" | I tried to implement the constructor for the Person class (see code at the end of the post). Codeblocks gives this error for line 37 (i.e. const Date &date)):
error: no matching function for call to 'Date::Date()'
Why is the constructor for Date being called? How do I fix the error?
class Date
{
public:
D... | It is called because members are initialized before the constructor body is entered - in your Person constructor, you are assigning to the members, not initializing them.
Since you're not explicitly initializing the members, they are default-initialized first.
Use the initializer list for initialization:
Person::Person... |
68,831,758 | 68,831,977 | Does c++ have an equivalent to Typescripts' intersection type? | I came back to c++ after some time with Typescript and learnt that in Typescript we could do something like this:
let ojbect: InterfaceA & InterfaceB = new InterfaceAandBImplementation();
It's called an Intersection Type. I wanted to do the same in C++, using pure virtual classes as interfaces, but I can't seem to get... | In typescript, type C = A & B is basically a way to cheat your way to get interface C extends A, B {}.
What this does is simply merge the members from left to right. If that is what you desire then class C : A, B {} is probably the closest.
Otherwise, for type requirements in functions you will need concepts (or a SFIN... |
68,832,576 | 68,832,785 | Confusion about incrementing iterator | int main(){
multiset<string> graph;
graph.insert("a");
graph.insert("b");
multiset<string>::iterator it = graph.begin();
cout << *(it + 1) // Wrong
cout << *++it; // True
return 0;
}
why does the compiler complain when executing *(it + 1), but *(++it) can be... | RandomAccessIterators allow you to add arbitrary offsets like it + n, but multiset has only BidirectionalIterators. For more on iterator categories see here: https://en.cppreference.com/w/cpp/iterator#Iterator_categories.
In principle you are correct, that it+1 and ++it both increment the iterator by one. And if an ite... |
68,832,787 | 68,837,360 | How to calculate maximum/minimum over n-channels in Halide using domains? | I am currently trying out Halide, playing around with calculating the maximum/minimum over all channels of an image. I would like to achieve this for a arbitrary images, where the amount of channels is only known at runtime.
I successfully got the following solution:
#include "Halide.h"
#include "halide_image_io.h"
usi... | Here's a way using the maximum and minimum helpers:
#include <Halide.h>
#include <halide_image_io.h>
using namespace Halide;
using namespace Halide::Tools;
int main() {
Buffer<uint8_t> input = load_image("rgb.png");
Var x, y;
RDom r_chan(0, input.dim(2).extent());
Func min_img;
Func max_img;
min_img(x, ... |
68,833,372 | 68,833,650 | Do I need to care about endianness when creating c++ program? | I know that i should care about this when reading data from binary files and with networking but what with a source code? Does it matter for endianness if I assign value, for example int = 42? Will it compile on big endian machine with big endian ordering and then not work properly on little endian machine? Or compiler... | Despite its reputation as a low-level language, when writing C++ code, you are not actually writing code for a concrete computer.
Instead, C++ code targets something called the C++ Abstract Machine, and it's the compiler's job to convert the behavior your program would cause on that Abstract Machine into a something (t... |
68,833,380 | 68,833,472 | Including a class object inside another class c++ | I am having trouble calling a method on an object created inside another classes private scope.
The error is down the bottom as well. It seems like it is not recognising the Motor variables inside my car class.
Do I need to create them as pointers? Or is there something else I am missing here?
This is to be used in an ... | In methods definition like in
Car::Car(int forR, int revR, int
forL, int revL)
{
rMotor.init(int forR, int revR);
lMotor.init(int forL, int revL);
};
you are calling init, not defining it. So it is wrong specifying the type of the parameters (int) and it results in a set of compilation errors.
Just call the m... |
68,833,424 | 68,833,898 | Declaring array of objects without specified size as class field | The field has to be immutable so I can't use the vector. Is there a way to do it like in the title?
I want to do something like this:
typedef list<pair<int,string>> list_pair;
class tree{
private:
list_pair arr[]{
public:
tree(int size){
arr[size];
}
}
|
Is there a way to do it like in the title?
No.
A non-static member array must have a known size, there is no way around that in C++.
The field has to be immutable so I can't use the vector.
Your example array of non-const isn't immutable either.
Furthermore, I don't see a reason why that should matter. It's a priva... |
68,833,568 | 68,833,747 | Where is the fold expression ()? | Reference fluentCPP article
The below code explanation says that this structure inherits from several lambdas, can be constructed from those lambdas, and folds over the using expression.
template<typename... Lambdas>
struct overloaded : public Lambdas...
{
explicit overloaded(Lambdas... lambdas) : Lambdas(lambdas).... | This isn't a fold expression. You cannot have any expression statements in class scope. And as you point out, there are no parentheses that are part of the fold expression syntax.
This is a declaration with a parameter pack expansion. Pack expansions can be used in many more context than just fold expressions.
what wi... |
68,833,874 | 68,838,616 | Obj-c(++) calling api with reference to a pointer | Quite new to Objective-C/Objective-C++, I am writing a wrapper around a C++ library.
One of the functions takes a reference to a pointer and a reference to an int to create a buffer and return its size, in this manner :
int GetData(char*& pcBuffer, int& iBufferSize);
It is really not clear to me as to how to interface... | The C++ function likely allocates the string buffer and returns it in the first argument, while returning the size of the allocated buffer in the second argument.
You don't need to mimic the same interface on the Objective-C side, as you can use the returned buffer to instantiate a NSString. What's left is to cope with... |
68,834,963 | 68,835,031 | Why we call memory created using "new" keyword "dynamic memory" since it is also a fixed memory | Array created this way int a[5] contains 5 integer memory blocks and memory can't be changed at runtime.
Array created this way int *ptr=new int[5] also contains 5 integer blocks and in this case too memory cant be increased and decreased at runtime, so, from which perspective it is called dynamic memory.
| The colloquial term "dynamic memory" comes from the language defined term "dynamic storage duration". See Storage duration :
dynamic storage duration. The storage for the object is allocated and deallocated per request by using dynamic memory allocation functions. See new-expression for details on initialization of ob... |
68,835,413 | 68,835,512 | What is time complexity for this function? | Consider this function:
void func()
{
int n;
std::cin >> n;
int var = 0;
for (int i = n; i > 0; i--)
for (int j = 1; j < n; j *= 2)
for (int k = 0; k < j; k++)
var++;
}
I think that the time complexity is O(n^2 * log n)
but when n is 2^m, I have a hard time thinking... | n isn't a constant, it's dynamic, so that's the variable in your analysis. If it was constant, your complexity would be O(1) regardless of its value because all constants are discarded in complexity analysis.
Similarly, "n is 2^m" is sort of nonsensical because m isn't a variable in the code, so I'm not sure how to ana... |
68,835,548 | 68,838,864 | python ctypes array data getting corrupted | I have the following files:
test.h:
extern "C" {
void* createTest();
void getStrings(void* test_ptr, char*** strings, size_t* length);
}
test.cpp:
#include <vector>
#include "test.h"
class Test {
public:
Test() {
strings.push_back("test1");
strings.push_back("test2");
strings.push_back("... | In getStrings the auto type deduction fails somehow. Changing it to:
void getStrings(void* test_ptr, char*** strings, size_t* length) {
auto inst = reinterpret_cast<Test *>(test_ptr);
std::vector<char*>& strs = inst->getStrings();
*strings = strs.data();
*length = strs.size();
}
seems to fix the issue.... |
68,836,156 | 68,836,235 | Variable alias in struct that can be used by static member function | Is it possible to alias a variable in a struct/class the same way you would alias a type or a namespace? Ideally, the following syntax would work
extern int x;
struct A
{
using x_alias = x;
static void foo(int* dst)
{
*dst = x_alias;
}
};
One solution is to use
#define x_alias x
but I would rather have ... | If you can use C++17, then you can use a static member variable and declare it as inline like
struct A
{
static inline const int& x_alias = x;
static void foo(int* dst)
{
*dst = x_alias;
}
};
And now you don't have to worry about suppling an out of line definition or any linker issues as the compiler/link... |
68,836,905 | 68,837,334 | Read from json file value in a vector | a want to read in a vector of a struct element from a json.
JSON:
A: [
{ "list" :[
"a" : 2,
"b" : 4,
"c" : 9
]
}
my vector is : std::vector< structE > vec;
structE{ "a", "b", "c" }
if (A[i].isMember("list")) // &&
{
auto const list= A[i]["list"];
... |
I have this error: matching function for call to 'std::vector ::push_back(const Json::Value&)'
From your source code, it appears that you might be using JsonCpp to handle Json in your C++ code, when dealing with Json::Value objects, for basic types such as int and std::string, you can use Json::Value::asInt() and Jso... |
68,837,278 | 68,837,387 | Custom comparer for priority_queue object in a class | I have a class that's structured like the following skeleton code.
class custom
{
private:
struct info
{
// define some stuff
};
std::priority_queue<info, vector<info>, custom_comparer_t> pq;
}
I am wondering if there's a standard for how the custom_comparer_t in this case should be defined? Would it be b... | std::priority_queue template parameters according to cppreference:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
The Compare template parameter of std::priority_queue must meet the Compare concept requirements. And std... |
68,837,288 | 68,837,576 | In *modern* C++ how should I manage *unowned* pointers? | In modern C++ how should I manage unowned pointers?
I was thinking something like a weak_ptr for unique_ptr, but that doesn't seem to exist.
Example
For instance, if I have a class A that owns a pointer, I should use unique_ptr<X> instead of an old X* pointer, e.g.
class A
{
std::unique_ptr<X> _myX;
};
But then if... | Bjarne Stroustrup has weighed in on this matter.
Pointers are really good at pointing to "things" and T* is a really good notation for that... What pointers are not good at is representing ownership and directly
support safe iteration.
He makes two suggestions:
Consider T* to mean "non-owning pointer to T" in modern... |
68,838,099 | 68,838,372 | C++ standard and 128 bit integer | What prevents C++ standard from having a 128/256 bit integer?
From other stackoverflow questions, recommendation to achieve this are Boost or compiler extension __int128 or std::bitset<>
So it is obvious that programmers are using/needing this.
Why is there a reluctance in adopting it?
| The reason is expense and lack of need. If the standard required a 128-bit integer type, every compiler would have to implement it. On hardware that doesn't support such an integer type natively, implementations would have to provide a way of generating code to emulate it. There simply aren't enough folks who need such... |
68,838,364 | 68,838,549 | Initializing N std::unique_ptr with custom deleter in a template function | I need to map peripheral memory addresses to access the hardware in linux. To make things a bit more generic (aka complicated...) I created a following function:
template<typename Tp>
static Tp* getPeripheralPtr(unsigned address)
{
static constexpr auto deleter = [](Tp* ptr){ munmap(ptr, sizeof(Tp); };
static s... | With this:
ptr{{((void)indices, ptr_type(nullptr, deleter))...}}
You need a type within an initializer_list constructor. And obviously, you couldn't use just a raw C-array. If you remove one braces level you could use it with raw C-array.
|
68,838,489 | 68,838,560 | Can someone help me understand how labels and goto functions work? | I am totally new to C++ programming so this code may actually have many errors in it, I'm not sure. But the problem I'm having is that I have a label (START:) at the beginning of my code that I reference in a goto later on. The goto function itself seems to have no problems, but where I first use the START label I am g... | You can only goto a label within the same function. You cannot use it to jump between functions as you seem to be trying to do.
In fact, goto in general is a bad way to design programs. As a beginner you should probably just forget that it exists. There are certain special cases where some people feel it is better t... |
68,838,500 | 68,838,689 | Making conditions for a random name generator | I'm working on making a random name generator, and I'm trying to add conditions like, "if the previous letter is a 'c', there is a percentage chance that the next letter will be an 'h'." For testing purposes, I made the chance 100% to see if the code worked, but I still get instances where some c's are not followed by ... | In this block:
if (chance < 51)
randomName += vowels[rand() % 5];
randomName += consonants[rand() % 21];
if chance was less than 51 - the vowel was appended. If the next letter was randomly chosen to be c - it won't be caught by the
if (randomName[i-1] == 'c')
check because i was not properly incremented and poin... |
68,839,163 | 68,850,457 | Is it impossible to pass a run-time integer as a template argument? | I have a base class and a class template, and I want to be able to instantiate it as follows:
class Base
{
};
template<int i>
class Foo
{
};
namespace SomeEnum
{
enum
{
First,
Second,
Third,
...
Last
};
}
void bar()
{
std::unique_ptr<Base> ptr{ nullptr };
int fooType = rand() % SomeEnum... | A simple solution would be this:
namespace detail {
template<size_t I>
std::unique_ptr<Base> makeForIndex() {
return std::make_unique<Foo<I>>();
}
template<size_t... Is>
auto makeFoo(size_t nIdx, std::index_sequence<Is...>) {
using FuncType = std::unique_ptr<Base>(*)();
cons... |
68,839,670 | 68,839,787 | Is there a way to call method with base class pointer that uses the data in derived class? | (sorry for my bad english)
I have a base class with vector of pointers on Drawable objects in it and method draw() that uses data from this vector.
class GameObject
{
protected:
std::vector<Drawable*> drawable;
...
void GameObject::draw() { for (const auto& object : drawable) window.draw(*object); }
In the derive... | The problem is in the code added by your edit -- it looks like my crystal ball is working today.
You're creating a temporary Player and moving it into the player member variable. That ends up with a vector holding the address of the shape inside the temporary Player, which is immediately destroyed, leaving a dangling ... |
68,839,790 | 68,839,827 | Call pure virtual function from child constructor/destructor | class A{
virtual void setEnable(bool enable) = 0;
};
class B : A{
B() {
setEnable(true);
}
~B() {
setEnable(false);
}
bool enable_ = false;
void setEnable(bool enable) override {
enable_ = enable;
}
};
Am I correct in understanding that the B :: setEnable function will be ... |
Am I correct in understanding that the B::setEnable function will be added to the vtable only after the constructor exits and this is undefined behavior?
No. Inside the body of the A constructor, the A object is fully initialized, but the B object is not. The problem with calling a virtual function from a constructor... |
68,840,239 | 68,840,288 | noexcept operator used on function object always yields true | I ran into this by accident, while playing around with the noexcept operator when trying to implement my own version of std::visit for educational purposes. This is the code with only the relevant parts:
#include <iostream>
template<typename... Ts>
struct visitor : Ts... { using Ts::operator()...; };
template<typename... | In noexcept(vis1) the expression you're checking is vis1. The evaluation of this expression can't possibly throw an exception, because it doesn't do anything. So this returns true regardless of the exception specification on any of the functions in the overload set defined by vis1.
However, if you write noexcept(vis1(4... |
68,840,861 | 68,840,973 | Struct Node in tree class is not being recognized when I compile | I get this error from the compiler (I get like 5 of these errors):
./Tree.h:14:2: error: unknown type name 'Node'
Node *getParent(Node *child);
Here is my Tree.h class:
#ifndef TREE_H_
#define TREE_H_
class Tree {
public:
Tree(int arr []);
Node *getParent(Node *child);
Node *getRightChild(Nod... | Another way to get this code to compile is to forward declare Node:
class Tree {
private: // add this
struct Node; // and this
public:
Tree(int arr []);
Node *getParent(Node *child);
Node *getRightChild(Node *parent);
Node *getLeftChild(Node *parent);
private:
s... |
68,841,065 | 68,841,093 | Difference between compare order of std::sort and priority_queue (C++) | I am wondering why priority_queue and vector work the totally different way. Here is the sample:
priority_queue<int, vector<int>, less<int> > pq;
pq.push(1);
pq.push(2);
pq.push(3);
// if we print the elem in pq by pop(), we get 3, 2, 1
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(2);
std::sort(v.begin(),... | std::less is the default compartor for priority_queue, and std::vector is the default Container, so your code can be simplified as:
priority_queue<int> pq;
According to the doc, it's expected to get the largest value via pop
A priority queue is a container adaptor that provides constant time
lookup of the largest (by... |
68,841,146 | 68,845,502 | class with deleted destructor considered trivially copyable? | This compiles both with gcc and clang
#include <type_traits>
struct A {
~A() = delete;
};
static_assert(std::is_trivially_copyable_v<A>);
int main() { }
Is a class with deleted destructor trivially copyable?
| A trivially copyable class may not have a deleted constructor
Given the title and the future readers of this thread: the standard is entirely clear on that A defined as
struct A {
~A() = delete;
};
is not a trivially copyable class, as per [class.prop]/1, particularly /1.3
A trivially copyable class is a class:... |
68,841,164 | 68,867,031 | How to get pixel data from VideoMediaFrame.Direct3DSurface? | I creating Unity app for Micorsoft HoloLens 2.
The app captures and shares camera video frames using Windows.Media.Capture.MediaCapture and Microsoft.MixedReality.WebRTC.
I got a VideoMediaFrame.Direct3DSurface(Windows.Graphics.DirectX.Direct3D11.IDirect3DSurface) formatted by "NV12" on MediaFrameReader.FrameArrived ev... | You can't define a C++/WinRT object pointer at the dll frontier, as at binary level, it's not a COM object (so C# is passing a COM object that's mapped to a C++/WinRT object, which is bad). What you can do instead is something like this:
void __stdcall Direct3DSurfaceAccess(
IUnknown* surface, // pass a raw COM obj... |
68,841,580 | 68,842,056 | When parsing a space delimitated string, is there any advantage using getline over stringstream::operator>>? | int main()
{
std::string s = "my name is joe";
std::stringstream ss{s};
std::string temp;
while(std::getline(ss, temp, ' '))
{
cout << temp.size() << " " << temp << endl;
}
//----------------------------//
ss = std::stringstream{s};
while(ss >> temp)
{
cout << t... | std::getline() and operator>> are intended for different purposes. It is not a matter of which one is more advantageous than the other. Use the one that is better suited for the task at hand.
operator>> is for formatted input. It reads in and parses many different data types, including strings. If there is no error st... |
68,841,864 | 68,964,782 | Is it allowed to call std::current_exception() in lambda which is called in a catch clauseοΌ | What I mean is something like this:
//std::once_flag eptrFlag;
//std::exception_ptr eptr;
//...
try
{
// may throw exceptions
}
catch (...)
{
std::call_once(eptrFlag,
[&]()
{
//...
eptr = std::current_exception();
});
}
Is this undefined behavior, or is it safe?
I've read cpprefer... | Firstly, calling std::current_exception never causes undefined behaviour.
As for what is during exception handling, actually in the language standard exception handling also includes handling an uncaught exception (for instance, 18.1(7) of C++17 standard); for std::current_exception the actual condition is βduring hand... |
68,842,189 | 68,842,338 | C++ Primer 5th Edition (Stanley) - Question on exercise 7-39 | Working through some exercises in C++ Primer 5th Ed (Stanley) and on exercise 7-39.
Class for exercise 7-39.
class Sales_data {
public:
// defines the default constructor as well as one that takes a string argument
Sales_data(std::string s = ""): bookNo(s) {}
// remaining constructors unchanged
Sales_data(std::strin... | If you make two default constructors, you effectively have no usable default constructor. If you try to default construct a Sales_data when you have more than one default constructor, there will be ambiguity and the program will fail to compile.
So, this is pointless
Sales_data(std::string s = "") : bookNo(s) {}
Sales_... |
68,843,675 | 68,843,857 | How to run line of codes asynchronously in c++ | I want to run some bunch of codes asynchronously in c++. This is for an gtk GUI application. I want to get the length from a encoder to an variable while running the other parts of the code. This lines of code should be always running. When i want the length, i should be able to get the current length from the variable... | I haven't understood what exactly you want to do. But I think you can read more about the std::async.
#include <iostream>
#include <future>
void asyncFunction ()
{
std::cout << "I am inside async function\n";
}
int main()
{
std::future<void> fn = std::async(std::launch::async, asyncFunction);
// here some... |
68,843,847 | 68,844,009 | cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'LPCSTR {aka const char*}' | #include <iostream>
#include <string>
#include <sstream>
#include <windows.h>
#include <vector>
using namespace std;
int main() {
string PNGFilePath, WEBPFilePath;
int number, c;
char title[256];
cout << "Enter a Number: ";
cin >> number;
cout << endl;
cout << "Title: ";
cin.getline(... | Do you use Visual Studio?
If your project's Character Set is Use Unicode Character Set in the Project's Property window, MoveFile means that MoveFileW.
It's parameter type is LPCTSTR, that is const wchar_t *, not the const char *.
Your error is not in converting from string to const char *, just in parameter type error... |
68,844,096 | 68,844,470 | If I develop an app FROM Microsoft in C++ Targeting Linux, are Miscrosft library good? | The situation is this:
I do not have access to a machine running on Linux, just a little embedded platform where I cannot install any IDE (which is in LINUX and is my target), so I got to develop the app from my Microsoft PC.
The question is: should I use Microsoft libraries? Because I am developing in a Microsoft envi... | Applications targeting Windows do not work out-of-the-box in a Linux system (see some discussion here https://superuser.com/a/209736).
You could, however, use a Linux guest from the Windows host, through a virtual machine or even docker.
Also, your "little chip target on which you cannot install an IDE" sounds like an ... |
68,844,459 | 68,844,506 | ISO C++ forbids declaration of 'getr' with no type [-fpermissive] | #include<iostream>
using namespace std;
class circle
{
public:
int r;
getr()
{
cout<<"enter radius";
cin>>r;
}
area()
{
cout<<"area is "<<(3.14*r*r);
}
}
int main()
{
circle one;
one.getr();
one.area();
return 0;
}
Im getting the following errors:
... | You need to state the return types in your member function definitions:
void getr() { ... }
^^^^
|
68,844,593 | 68,845,194 | How to create unique_ptr with static deleter | I would like to have a member function unique-ptr with a static deleter function where the function is known at compiletime and no function pointer is required at allocation. I do not know if it is possible but this test confuses me:
#include <memory>
#include <string>
#include <iostream>
struct Apa {
std::string ... |
using deleter = decltype((Apa*) {});
This is an unnecessarily convoluted way of writing:
using deleter = Apa*;
The type Apa* doesn't satisfy the requirement that std::unique_ptr imposes on its deleter because Apa* isn't a FunctionObject. The example program is ill-formed (at least if you try to create an instance o... |
68,844,718 | 68,844,967 | Make a class template std::is_swappable | I'm trying to make a class template swappable. I don't understand why the static assertion fails:
#include <type_traits>
template <class T>
struct A {};
template <class T, class U>
constexpr void
swap (A <T>&, A <U>&) {}
static_assert (std::is_swappable_v <A <int>>);
int main (){}
It passes with
template <class T>... | std::is_swappable (and std::is_swappable_with) considers std::swap too.
... are both well-formed in unevaluated context after using std::swap;
Then for the 1st case, the calling of swap is ambiguous between user-defined swap and std::swap. For the 2nd one, user-defined swap wins in overload resolution then std::is_sw... |
68,844,815 | 68,844,913 | std::stoi() error -- "terminate called after throwing an instance of 'std::invalid_argument'" | I'm currently on chapter 4 exercise 17 on Programming Principles and Practice Using C++, and the exercise is to find the mode, min and max of string input. I have left out the function to calculate the mode as it is not relevant.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<int... | Basically the '|' can't be converted to an integer value and so stoi is throwing this error. If you are just using | as an identifier that input has ended, this should work
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<int> sequence {};
std::string input {};
std::cout <<... |
68,845,590 | 68,845,713 | How to get the vendor OUI and Device name from MAC Address in C/C++ | I am developing a network scanner in C++ with the help of libtins library, I can be able to get MAC addresses and IP but I want to go further to know the vendor(eg: Intel Corporate) and Device Name (eg: DESKTOP-TO5P0BD) in C++
codes to get Mac and IP
// Retrieve the ARP layer info
const ARP& arp = pdu.rfind_pdu<ARP>()... | In order to get the vendor from the MAC address, you can have a look at this MAC OUI vendor database mantained by Wireshark. It's a text file with a simple format.
In order to get the "device name", you can do a NetBIOS name lookup. This StackOverflow question may help you.
|
68,845,729 | 68,845,837 | Discrepancy with is_swappable_with_v | This is a follow up of this question. A slightly modified version of the code, using std::swappable_with_v rather than std::swappable_v yields inconsistent results:
#include <type_traits>
template <class T>
struct A {};
template <class T, class U>
constexpr void
swap (A<T>&, A<U>&) {}
int main (){
static_assert... | Gcc and clang are correct. From the behavior of std::is_swappable_with,
If the expressions swap(std::declval<T>(), std::declval<U>()) and swap(std::declval<U>(), std::declval<T>()) are both well-formed in unevaluated context after using std::swap;
std::declval<T>() yields rvalue expression when T is a non-lvalue-refe... |
68,845,817 | 68,851,278 | What is the format of the data compressed using zlib and how to uncompress them from command line or other apps? | I am using qCompress() to compress the data in a file. Now the requirement is that, this file should be un-compressible manually, either via command line or via some standard compression tool.
Since qCompress() uses zlib library, what should be the extension of that file (i.e. .zip, .gz, .bz etc)?
Also what kind of sta... | The documentation is scant, but from what I can tell, qCompress() writes a four-byte length followed by a zlib stream. There is no file format, extension, nor command line tool for that format. You would have to write your own.
It would be quite straightforward. Just discard the first four bytes, and feed the rest to z... |
68,846,008 | 68,879,333 | Infinite printing of stack in linked list form | #include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
struct node{
int data=0;
node *next=NULL;
};
class linked_stack{
node *top; //top is the head here
int size;
public:
linked_stack(){
size=0;
node *top=NULL;
}
vo... | when I ran my original code in debugger it showed an error box "Program received signal SIGSEGV, Segmentation fault." But along with this there was an output window where "2 36 45" was printed .
BUT code is working fine on "online GDB C++ compiler" but showing the error in "DevC++" compiler(maybe it could be the compil... |
68,846,225 | 68,846,505 | Why C++ double giving wrong answer for Just 17 DIGITS? | Recently while practicing I found this problem, Please run this code in your local machine.
#include <bits/stdc++.h>
using namespace std;
double power(double a, double b) {
double ans = 1;
for(int i = 1; i <= b; i++){
ans *= a;
}
return ans;
}
int main()
{
double anaconda = 0;
for(int i... | The C++ double type is typically stored (in memory) in 64-bit "double-precision floating-point" format.
While this allows you to represent and calculate on both very large, and very small, numbers (relative to other common c++ datatypes) it only does this with a certain precision.
This means that you can only rely on 1... |
68,846,362 | 68,846,787 | C++ Auto deduction of template type argument | As part of my messaging library, I use a construct like this to send a message (struct)
tMsgVolumeChanged oMsg;
[...]
oMsg.vSend<tMsgVolumeChanged>();
with the vSend() method defined in the base class (from which tMsgVolumeChanged and all other messages is derived) as
struct tMsgBase
{
tMsgBase() {}
virt... | If you want to use tMsgBase polymorphically, you will have to have some overhead in the derived classes.
struct tMsgBase
{
tMsgBase() {}
virtual ~tMsgBase() {}
virtual void send() = 0;
protected:
template <class T> void vSend(T * self) {
poGetMessageDispatcher()->boDispatch<T>( *self );
}
}
... |
68,846,410 | 68,846,603 | How to use the Compare template parameter of std::map for value comparison? | With this code:
namespace nonstd {
template <class Key,
class T,
class Compare = std::greater<T>,
class Allocator = std::allocator<std::pair<Key const, T>>
>
using map = std::map<Key, T, Compare, Allocator>;
}
int main() {
nonstd::map<char, std::size_t> const values = {
{'... |
Is there any way to use the Compare template parameter for value comparison?
No there isnt. A std::maps elements are sorted with respect to the keys only.
If you want a container of std::pair<char,size_t> sorted with respect to the size_ts you could use a std::set< std::pair<char,size_t>> with a custom comparator tha... |
68,846,816 | 68,846,885 | String doesn't want to store a 2700 character word | I'm trying to make a program that prints all the numbers from 100-999. After that you get to choose how many numbers you want to find. Then you type the number's position and it will be outputed.
There is one problem. The string, named str, stops storing at the number 954.
Here's the code:
#include <iostream>
#include ... | C++ streams are buffered. When you use << to write to a file it is not immediately written to the file.
Try to close or flush the ofstream before you read from it:
myFile.close(); // or...
myFile.flush();
For more details I refer you to flush() and close().
PS: Actually it is rather rare that you need to close a ... |
68,847,036 | 68,848,275 | Addition on pointers and operator precedence | int myMatrix[2][3] = { { 11, 12, 13 }, { 21, 22, 23 } };
for (int i = 0; i < 6; i++)
{ std::cout << *(*myMatrix + i) << std::endl; }
This is an example from one of my lectures.
The output is "11 12 13 21 22 23"
I don't understand why this is working.
*(*myMatrix + i) = *(11 + i) The * operator should have higher ... | You have a 2D array of two rows and three columns
In other words, you have a pointer array of size 2. Let's suppose we call this array as array1.
Now, each index of this array1 further points to an integer array of size three. This means that it contains two addresses which are of the following two arrays.
Let's say th... |
68,847,369 | 68,847,517 | Is std::string::begin() iterator invalid after += operator? | While debugging my code, I've noticed a change in stored iterator, pointed to begin(), after every 4 or 5 call to += operator on a string (what it points to, isn't even in the string itself!). Here's what my code looks like:
for (auto ch=word.begin(); ch!=word.end(); ++ch) {
// on a condition, the following loop star... | When you extend cointainers like vector or string sometimes they may to reallocate their memory to new location - so it change address. They need continuous memory, beacuse aren't list with pointer to next element.
Iterator move through continous memory addresses. Next element is address+1.
So, at begining, your first ... |
68,847,604 | 68,847,721 | Using sort() on specific Member of Struct after a sort() | My Code is sorting a vector<Struct> accordingly to the Points the Player gained in the Game. This works fine. Now I wanted to add that if similar points, it sorts by time. So that the Person with the highest Points, but lowest time is on Top. My Problem lays in sorting the vector<Struct> without destroying the sort I d... | You can use lambda as custom comparator and do both points and time comparision in one function.
std::sort(Test.begin(), Test.end(), [](const Highscore &P1, const Highscore &P2) {
if (P1.Points == P2.Points)
{
return P1.Time < P2.Time;
}
return P1.Points > P2.Points;
}
|
68,848,364 | 68,848,454 | Singleton CRTP with meyers singleton | i am tring to implement a Singleton template that using meyers singleton inside:
#include <bits/stdc++.h>
template <typename T>
class Singleton {
public:
static T& instance() {
static T _instance;
return _instance;
}
protected:
Singleton() = default;
~Singleton() = default;
Singleton... | You are using private inheritance with class Foo : Singleton<Foo> which means to the outside world, Foo is not a Singleton<Foo> and it doesn't have a instance function. You can add
using Singleton<Foo>::instance;
To the public section of Foo. That will import the instance function into the public space of Foo and a... |
68,849,076 | 68,850,339 | I would like to parse a boost::beast::flat_buffer with msgpack data using nlohmann:json | So I am using boost::beast as a WebSocket server.
I would like to receive a binary message and parse it using nlohmann::json.
However I get an error message:
none of the 3 overloads can convert parameter "nlohmann::detail::input_adapter"
Here is some code:
boost::beast::flat_buffer buffer;
ws.read(buffe... | You can use the iterators-based overload:
Live On Compiler Explorer
#include <boost/asio/buffers_iterator.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <nlohmann/json.hpp>
int main() {
using nlohmann::json;
using boost::asio::ip::tcp;
boost::asio::io_context io;
boost::b... |
68,849,844 | 68,851,193 | Is it undefined behaviour to access two objects of type T declared next to each other using T[]? | I recently watched a CppCon talk by Miro Kenjp on "Non-conforming C++: the Secrets the Committee Is Hiding From You".
At 28:30 (https://youtu.be/IAdLwUXRUvg?t=1710) He states that accessing doubles next to each other was UB and I don't quite understand why. Can someone explain why is this the case?
And if this is the c... | I want to start with a quote from the presentation:
You are not programming against the CPU, you are programming against the abstract machine
You say:
He states that accessing doubles next to each other was UB
But your quote is incomplete. He specifies this very crucial fact:
... unless the objects are part of an ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.