question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
70,677,484
70,677,822
Why can't I std::apply for a member function
I'm trying to develop a wrapper to help people use pthread on calling any member function. template <typename> struct signature; template <typename C, typename R, typename... Args> struct signature<R (C::*)(Args...)> { using return_type = R; using pure_argument_type = std::tuple<C*, std::tuple<Args...>>...
The return type of std::get<1>(*param) is std::tuple<C*, std::tuple<Args...>>. Since the type of the second element of this tuple is also a tuple, you need to use std::apply to expand it again, something like this std::apply( [f = std::get<0>(*param)](auto* obj, auto&& args) { std::apply([&](auto&&... args) { ...
70,677,792
70,679,150
Read multiple text file in Arduino ide
I have folder contain n txt file(files have numeric values) I need to read these files and save the file contains in array. How can I read the contents of the first file1 in the array and then clear the array ,and then read the second file2 in the same array and so on? #include "SPIFFS.h" void setup() { Serial.begin(...
You could do something similar to this. Though you will need to check the proper behaviour of parseFloat() when it doesn't detect a float value, ie., what it actually returns. while(file) { int length = readFile(arr, file); file.close(); handleArray(arr, length); file = root.openNextFile(); } ... int ...
70,678,522
72,659,872
Numerical integration of a 2-dim complex function in C++?
I am trying to integrate this integral numerically (so without evaluating the primitive) in C++: It is simpler than what it seems, in fact I know which algorithm I can implement to solve it (I consider fYsin as func(th,phi) and integrate it with trapezoidal rule in 2-D). The only problem is that Y is complex and in pa...
I solved this problem by simply integrating real and imaginary part separately. The complete code can be found in this repository, within the complete algorithm definition to integrate the function of the first image I posted.
70,678,772
70,735,847
Using C++ protobuf formatted structure in leveldb. set/get operations
I'd like to make a POC of using leveldb in order to store key-value table of different data types in protobuf format. So far I was able to open the database file, and I also saw the get function with the following signature : virtual Status Get(const ReadOptions& options, const Slice& key, std::string* value)=0 I under...
You need to serialize the protobuf message into a binary string, i.e. SerilaizeToString, and use the Put method to write the binary string to LevelDB with a key. Then you can use the Get method to retrieve the binary value with the given key, and parse the binary string to a protobuf message, i.e. ParseFromString. F...
70,678,778
70,682,996
ldfcn.h gives 0 instead of true or false
i have dummy.cpp #include <iostream> #ifndef EXPORT_API #define EXPORT_API __attribute__ ((visibility("default"))) #endif extern "C"{ using namespace std; bool dum = true; int main(){}; }; and main.cpp #include <iostream> #include <dlfcn.h> #include <string> using namespace std; int main() { vo...
solved it with gcc -shared -o dummy.so -fPIC dummy.cpp to get a proper so file and if yours has a function like int foo(){} or something use std::invoke in your .sofile and then call it like bool* give = (bool *) dlsym(test, "dum"); auto answr = *give; where answr is the return val
70,678,788
70,679,026
Memory allocation in the C++ standard library
Recently, I became interested in tracking memory allocation and deallocation. When overloading the new and delete operators, I found that the C++ standard library sometimes calls the overloaded operators and sometimes allocates memory using other methods. (Probably std::allocator.) For instance, std::string seems not t...
The standard containers will use the allocator provided to them to allocate dynamic memory. By default, that is std::allocator. For most other dynamic memory uses in the standard library, the standard doesn't specify how the implementation should acquire memory, and the implementation has the freedom to do what they wa...
70,679,324
70,679,360
What does symbol # means in #define S(x) (cout<<#x<<endl)
#define S(x) (cout<<#x<<endl) Using # will print whatever string, int, float I place in S(x). For example: S(Door Class Default Constructor); will print Door Class Default Constructor I Wasn't able to find any documentation regarding it. Explain how is it able to do so.
It causes the expanded x to be wrapped in double quoates, " It's often called the stringize operator and you can find more information here.
70,679,724
70,680,415
Reference evaluation and constant expression
Consider the following snippet: struct test1 { static constexpr int get() { return 1; } }; struct test2 { constexpr int get() const { return 1; } }; template <class T> int get(T&& t) { if constexpr (t.get() == 1) { return 1; } return 2; } int main() { return g...
Pointers and references to unknowns in constant expressions being directly ill-formed will possibly be addressed in C++23 and, if so, as a Defect Report for earlier language versions. [...] when the function being accessed via the very same reference is static. Isn't the refence "evaluated" in this case? Is it a GCC ...
70,680,708
70,680,753
C++ Runtime Error 0xC0000005 Caused By Object Inside Struct
While working on a C++ project, a runtime error (0xC0000005) showed up. I managed to locate the problem and encapsulate it in the code below. #include <iostream> using namespace std; class TestC{ public: string test1[20]; string test2[10]; void initArrays(){ cout << "init start\n"; fo...
You're using malloc to allocate a structure that contains a class, TestC. This means the TestC constructor won't run and the test1 and test2 arrays won't be correctly initialized. Instead, use new: TestS *struct_instance = new TestS; You should never use malloc to allocate and type that is a C++ class, or contains a C...
70,680,967
70,685,553
Xcode offers -std=c++20 but command line clang does not
I have the Xcode command line tools installed and can use clang++ fine for versions up to C++17. In Xcode itself, I can select C++20 in the build settings: But when I try to compile using clang++ from the command line with this option: error: invalid value 'c++20' in '-std=c++20' note: use 'c++17' for 'ISO C++ 2017 wi...
Like you have noticed, Xcode and system uses different instance of Command Line Tools. Xcode uses the one that is embedded in Xcode, and the system will use a copy located in Library/Developer/, which is not automatically upgraded along with Xcode. Support of c++20 flag is only added for later versions of Apple Clang, ...
70,681,084
70,683,604
Consteval constructor and member function calls in constexpr functions
struct A { int i; consteval A() { i = 2; }; consteval void f() { i = 3; } }; constexpr bool g() { A a; a.f(); return true; } int main() { static_assert(g()); } https://godbolt.org/z/hafcab7Ga The program is rejected by all of GCC, Clang, MSVC and ICC and replacing constexpr on g by...
The rule is, from [expr.const]/13: An expression or conversion is in an immediate function context if it is potentially evaluated and its innermost non-block scope is a function parameter scope of an immediate function. An expression or conversion is an immediate invocation if it is a potentially-evaluated explicit or...
70,681,310
70,681,456
Error i get using get() and set() method in C++
I want to write a code that will accept input but store it as private in C++ but I keep getting a weird output after compiling it. Below is my code #include <iostream> #include <string> using namespace std; class MyClass{ private: int salary; public: string fname; string lname...
You should call cout<<"Salary amount: "; cin>>salaries; before myObj.setSalary(salaries); and also actually print the salary you get: cout << myObj.getSalary();
70,681,777
70,681,938
A code error about template and iterator of C++ made by a C++ new learner
As a C++ new learner, when I tried to learn about the template and iterator of C++, I wrote a function to check whether a number is amoung an array by using template and iterator of C++. The code is below: template<typename T> bool find(vector<T>::iterator &begin, vector<T>::iterator &end, T target){ for(;begin != en...
You should add typename before iterator type in function arguments. Also if you use the name find for your function and include std namespace in your code, there will be a clash. So you should use another name for the function or use scope resolution operator for std functions. Here I fixed it for you: template<typenam...
70,682,096
70,682,383
Is it safe to call std::visit on classes with virtual functions?
I'd like to create a hierarchy of visitors to handle instances of std::variant. I'd like to override some of the methods in subclasses for more specialized behavior. My code looks like this: #include <variant> #include <cstdint> #include <iostream> struct Event1 {}; struct Event2 {}; using Event = std::variant<Event1...
Yes, such code is required to do what you expect. When you pass a Visitor & to std::visit, it won't copy (and thus slice) it. All examples of std::variant I've seen use either simple classes with no inheritance or lambdas. That's because examples tend to be as simple as possible.
70,682,335
70,682,418
query the spdlog logger name
say we build our spdlog object as the following? logger = std::make_shared<spdlog::logger>("some name", sink_list.begin(), sink_list.end()); Is there a method such as logger->get_name() or anything else that would return "some name"
Is there a method such as logger->get_name() or anything else that would return "some name" There is. logger->name() (source)
70,682,756
70,684,047
schedule() affecting private thread variables in OpenMP #pragma omp parallel for
I've been following and modifying a tutorial for OpenMP in C/C++ to demonstrate/ understand how schedule() works in #pragma omp parallel for. This is my code: #include <unistd.h> #include <stdlib.h> #include <omp.h> #include <stdio.h> #define THREADS 4 #define N 100 int main ( ) { int i; int perThread=0; printf...
You should use firstprivate(perThread) instead of private(perThread). Using private clause your private variable is declared, but not initialized, so its value is undefined. In OpenMP specification you can read that the firstprivate clause declares one or more list items to be private to a task, and initializes each o...
70,683,050
70,683,168
How am I able to use a class as a function parameter in itself?
This is not allowed as test will be infinitely big (it contains itself recursively). struct test{ test t; }; However the following compiles fine: struct test{ int get(test t1);// or `int get(test t1){}` static test t2; }; How does it know how much space to allocate for t1 on the stack, at that point test isn't com...
Case 1 Here we consider the statement static test t2; From static documentation: The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared: struct S { static S s; // declaration, incomp...
70,683,307
70,683,476
Pass function template as argument to normal function to be specialised differently within the normal function
I would like to do something to the following effect: template <class A> A doThings(A input) { /* do something */ } void doTwoThings(ClassB inputB, ClassC inputC, template <class A> A(A) func) // This syntax is wrong but how to achieve this effect? { std::cout << func<ClassB>(inputB); std::cout << func<ClassC>(inp...
Not sure if it match your need, but you might do template <typename F> void doTwoThings(ClassB inputB, ClassC inputC, F func) { std::cout << func(inputB); std::cout << func(inputC); } doTwoThings(5, "testStr", [](const auto& input){ doThings(input); });
70,683,447
70,699,796
mlpack include file errors
Recently I am about to learn mlpack. Today I have successfully built the solution from mlpack source code, but when I newly create a project I get the following error in the header file. I would like to know what is wrong and how to fix it. errors In the screenshot, the algorithm.hpp is under the build folder and its a...
I finally found out that this problem seems to be related to the version of the source code. I should not use the latest version of the source code from https://github.com/mlpack/mlpack, but the source code corresponding to the latest stable version. After I replaced the include directory with the include directory cor...
70,684,028
70,684,245
How am I able to use an incomplete class as an argument in itself?
struct test{ void call(test t1){ // } }; I have asked a similar question and found a few other links such as: How am I able to use a class as a function parameter in itself? Incomplete types in member function definitions But none of them answer this question: The compiler needs to emit code to allocated space on...
The class struct test is not an incomplete type. From cppreference.com: Incomplete type the type void (possibly cv-qualified); incompletely-defined object types class type that has been declared (e.g. by forward declaration) but not defined; array of unknown bound; array of elements of incomplete type; enumeration t...
70,684,671
70,684,766
How do i read/write JSON with c++?
I would like to know how to read/write a JSON file using C++. I will be using this file to store player info & setting for a simple game I'm making. It's nothing fancy, just a console number guessing game, but I just use it to learn stuff. I have to know how to read & write specific parts of a JSON.
Using a library, it can be done quite easily: #include <nlohmann/json.hpp> #include <iostream> int main() { // read file auto json = nlohmann::json::parse("{\"value1\": \"string\"}"); // mutate the json json["value1"] = "new string"; // write to a stream, or the same file std::cout << json; /...
70,684,743
70,686,290
gdb printing <incomplete type> with incomplete enum class declaration
I've been dipping my toes in C++, and found a surprising behavior of gdb. I'm wondering if it is the expected behavior, or if I messed something up. enum class Foo; struct Bar { Foo a; int b; }; enum class Foo { A, B, C }; int main() { auto a = Foo::A; auto b = Bar{ Foo::A, 1 }; } built with gcc 7.5.0 (with t...
Using g++ (Debian 11.2.0-10) 11.2.0 and GDB-10.0: 7 auto b = Bar{ Foo::A, 1 }; (gdb) p a $1 = Foo::A (gdb) n 8 } (gdb) p b $2 = {a = Foo::A, b = 1} built with gcc 7.5.0 (with the -g option) and ran with gdb 8.1.1 These are pretty ancient. Is there something I can do I suggest trying latest released...
70,684,828
70,685,367
Return an array which is iniated in a one liner
I want to return an array of my custom structure object timeInDay with as few lines as possible, in order to return a day in my time schedule. struct timeInDay[] getRingTimesForWeekDay(int day) { switch (day) { case MONDAY: return { {7, 50} }; case TUESDAY: return { {7, 50} }; case WEDNESDAY: return ...
No line is required to return a c-array from a function, because you cannot return a c-array from a function. You could dynamically allocate it and return a pointer to first element and size, but you better stay away from that in favor of std::array: #include <array> struct timeInDay { unsigned short hour; unsigne...
70,685,138
70,696,741
Conan package manager - how to remove folders during conan install?
I have a local conanfile.py to consume a package, the package is already located on the local cache (~/.conan/). In the conanfile.py there is the imports() function in which I copy some files from the package into my build folder. I have two files with the same name in different directories and I copy them to the same ...
I ended us solving it in the package creation side. Renamed the files as I wanted and then just consumed them
70,685,472
70,685,528
Problem with function which create and return pointer to dynamic vector
I have to crate a function which gets a reference to int array as one of arguments. This function should creates a dynamic vector and returns its pointer. When I compile this code I got err: "No matching function for call to 'func'". I have no idea what's wrong. Immediately, I would like to ask if I removed the dynamic...
The first parameter of the function is a reference to a scalar object of the type int vector<int> *func(int &, int); You need to write vector<int> *func( const int *, int); Also in the for loop you have to write for(int i = 0; i < size; i++) newVec->push_back(arr[i]); In fact the for loop is redundant. Your function...
70,685,625
70,686,664
How to pass a function signature as input in order to initialize another function in C++?
my question is the following: supposing I have a program, written in C++, which takes a function and gives its integral. In this program I write the function manually, in the source code, and I change its signature every time I want to integrate another function. If now I want to initialize this function in input (for ...
You need this: https://github.com/ArashPartow/exprtk It is only slightly slower than compiling the expression in native code. There are also others, you can see most of them here: https://github.com/ArashPartow/math-parser-benchmark-project (Disclaimer: I am the author of the Node.js bindings: https://github.com/mmomtc...
70,685,777
70,710,121
How to get data out of readyReadSlot?
I am trying to get data out of slot with a signal readyRead(). But my method doesn't seem to work. I googled a lot but still I can't solve the problem. Here what I have: In my main function I call the method sendPOST() to get cookies. I got cookies from this method using inside of it SIGNAL finished(QNetworkReply *) an...
I found a problem solvation for me. void DataMartsModel::replyFinishedSlot_(QNetworkReply *reply) { static bool isRead = false; if(reply->error()) qDebug() << "Error: " << reply->errorString(); else { cookie = reply->manager()->cookieJar()->cookiesForUrl(webReportsUrl); QStri...
70,686,008
70,718,544
Shared library with statically linked dependencies
I just wanted to understand how shared libraries with statically linked libraries are expected to perform. I am writing a shared library (lshared.so) that is statically linked to another library (lstatic). Now, I have another executable helloworld which loads a dynamic version of library lstatic (lstatic.so) and lshare...
Will the static version of library (lstatic) loaded by lshared.so and the dynamic version (lstatic.so) conflict. Possibly. Will they share any global state. Possibly. The answers depend on how exactly lshared.so is built (which symbols it exports), and how the main helloworld binary is linked. The answers also tend...
70,686,429
70,686,520
Initializing a member of uncopyable and unmovable type
Given an uncopy/movable struct U, membes of that struct can not be assigned in the constructor (see C). They can only be initialized via a member initializer list (see S). struct U { U(int x); U(U &other) = delete; U(U &&other) = delete; }; struct S { S(int x) : u(x) {} U u; }; struct C { C(in...
You cannot initialize it in the constructors body. Members are initialized before the body of the constructor is executed. If x is computed when the constructor is called then you can still use the member initializer list. For example when you have a void f(int&) that needs to be called to retrive the parameter for u: ...
70,686,708
70,687,209
String to Hex without changing number, C++
While working on a project, I found myself wondering how to convert from string to hex. Not just converting from, let's say, the string "42" to hex 0x3432. I'm curious how you would go about converting the string "0x42" to hex 0x42. As in, assume the string given is a valid hex number (I know that's a big assumption, b...
As this is just a matter of different representations of the same value, its IO streams that offer such "conversion": #include <sstream> #include <iostream> int main() { std::stringstream ss{"0x42"}; int x = 0; ss >> std::hex >> x; std::cout << x << "\n"; std::cout << std::hex << x; } Output: 66 4...
70,686,762
70,687,060
How to understand the usage of #define directive in this code example?
I am looking into the #define directive recently. And I am confused by the #define usage in the following code example. Anyone could explain how it works? template <> __inline__ __device__ void warpReduce<ReduceType::kSum, 2>(float* val_list) { float val0_tmp, val1_tmp; #define WarpReduceSumOneStep(a, b) ...
Every preprocessor directive takes up exactly one line. That \ at the ends of some of the lines say "pretend that this isn't really the end of a line". So the definition of the macro WarpReduceSumOneStep includes the next four source lines. They're highlighted in blue on my system. The macro definition ends at the end ...
70,687,712
70,689,395
How to expand a non value paramter pack
I've been trying to expand a non value parameter pack recently in C++. Is this possible? And if it's not, why? I mean, as you can see, in the line with the comment //, given a parameter pack for the TypeMap class, how can I call addType<T>() with each type of the parameter pack? Thanks in advance! template <typename......
As @HolyBlackCat has already answered in the comments, you can expand it like this: TypeMap() { (addType<T>(), ...); } If T is std::string, int, float this would expand to: TypeMap() { (addType<std::string>(), addType<int>(), addType<float>()); } There are however a few more issues in this code-snippet: 1. a...
70,689,073
71,063,033
QT on Raspberry Pi 4
I have a Raspberry Pi 4 Model B Rev 1.4 and I am using Ubuntu 20.04 running in VirtualBox on a Windows 10 machine. I have been following the steps presented in this video https://www.youtube.com/watch?v=TmtN3Rmx9Rk&list=PLXAxzIhirYJGp1dMN0SxMRNCumubmpzWj&index=2&t=1686s. The goal is to run QT C++ applications on the Ra...
Had the same problem. the /lib you want to copy is a link, not a folder. It's linked to /usr/lib. So try it with rsync -avz --rsync-path="sudo rsync" pi@192.168.1.237:/usr/lib sysroot
70,689,563
70,690,538
Google test using C++11/14, how to fix the invalid POSIX Extended error
I am using gtest to do unit test and trying to use the function MatchesRegexto match the pattern a string contains multiple substrings using look around. e.g Verifying the statement The team members are Tom, Jerry and a Terminator contains all three keywords Tom, Jerry and Term std::string target = "The team members ar...
POSIX regular expressions in C++ are very limited. Fortunately, you may combine expectations logically. #include <iostream> #include <string> #include <gmock/gmock.h> using testing::AllOf; using testing::MatchesRegex; TEST(RegexTest, Simple_Regex_Matcher) { std::string target = "The team members are Tom, Jerry and ...
70,689,568
70,689,828
Is overloading int function with the same long long function has any point?
Here is a simple example: int function (int n) { //code } long long function (long long n) { //absolutely the same code but intended to work with bigger values } I was thinking about saving extra memory (if you use it with variables of small types) AND making it more universal (if you use it with variables ...
If you're writing code for reasonably-recent personal computers or web servers, having a separate int version is probably a premature optimization, given that most of these machines have 64-bit processors anyway, so calculations with 64-bit long long should be fast. OTOH, if you're writing for an 8/16/32-bit embedded s...
70,689,663
70,693,776
How to link multiple .cpp files in Code::Blocks for a single project?
While following the book C++ For Dummies, I have three files in my CodeBlocks project, main.cpp, Pen.h, and Pen.cpp. They look like this: main.cpp: #include <iostream> #include "Pen.h" //#include "Pen.cpp" using namespace std; int main() { Pen MyPen = Pen(); MyPen.test(); } Pen.h: #ifndef PEN_H_INCLUDED #def...
In the main.cpp include the header file: #include "Pen.h" The Pen.h file it's ok. You need to add the Pen.cpp file to the project tree. Go to Project -> Add files... and add Pen.cpp
70,689,687
70,689,712
Why do operation on <bit> return signed numbers?
Operations like template< class T > constexpr int popcount( T x ) noexcept; return a signed integer, but the number of set bits can never be negative? What was the motivation for choosing a signed rather than unsigned type?
From the paper: The counting operations return "int" quantities, consistent with the rule "use an int unless you need something else". This choice does not reflect, in the type, the fact that counts are always non-negative. gcc's intrinsic here (__builtin_popcount) also returns int.
70,689,689
70,690,647
Update Template Parameter/Recast Template With New Parameter
I'm creating a tree of templated typenames. I am using tuples for the trees structure. Every Node in the tree that is not a leaf will contain a tuple of typenames containing other Nodes and Leaves. The leaves will contain a size and an offset representing their position within the tuple (relative to root node and based...
Sorry if I don't quite get the exact logic how the code work, but you might try this: struct Node { ⋮ ⋮ template<uint16_t ... I, uint16_t ... J> static constexpr auto GetElements_helper(std::integer_sequence<uint16_t, I...>, std::integer_sequence<uint16_t, J...>) { constexpr std::array arr...
70,690,329
70,690,358
Declare static arrays in a struct right in C++
I tried to declare static array: #include <iostream> #include <string.h> using namespace std; struct tagData{ static string tags[]; }; int main(){ tagData::tags[3]; tagData::tags[0] = "default"; tagData::tags[1] = "player"; tagData::tags[2] = "enemy"; return 0; } But as the result an error occurred: *Pat...
struct tagData{ static string tags[]; }; This static class member must be defined in global scope, and not as a local variable in a function like main: string tagData::tags[3]; And now, once the formalities are taken care of, you can manually access its class members, in main or any other function: int main...
70,690,458
70,690,588
Is a pointer pointing to another array and deallocating memory at the end considered as memory leak in c++?
#include <iostream> using namespace std; int main() { int* pointer = new int[5]; pointer = new int [10]; delete[] pointer; return 0; } After allocating new memory for the pointer, what happens to the old memory with the length of 5? If it is a memory leak, should I use realloc() instead?
I want you to picture yourself in the following scenario You are standing next to an abyss with one arm tied behind your back. Thus, you have one hand available. That hand is your pointer var. At some point you request of me to throw you a ball. That ball is the memory being allocated via new. I toss you the ball, whi...
70,690,649
70,690,855
Bezier curve... adding normals (in 3D)
I have a bezier curve class. Each point on the curve is defined thus: struct bpoint { vector3D position; vector3D controlpoint_in; vector3d controlpoint_out; }; To retrieve a point on the curve's spline (the curve can have infinite points), I use this function: vector3d GetSplinePoint(float thePos) { f...
Ok, so, there are a few things to consider, mathematically speaking. First, your curve has a certain shape, so at each point of the curve there is one and only one plane perpendicular to the current direction of the curve. The normal has to be a part of this plane. So your curve is parametrized by thePos, which, to sim...
70,690,749
70,690,771
Why can't compare int and size_t in c++
The thing is that if I compare int and size_t in for loop it works fine. vector<int> v; for (int i = 0; i < v.size(); ++i) However, it doesn't work if I do this: vector<int> v; int max_num = max(3, v.size()); Line 13: Char 24: error: no matching function for call to 'max' /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../.....
In C++ when the types of a binary operator are different, there are various (complicated) rules that govern what actual type the binary operator uses: i < v.size() One of these is an int. The other one is a size_t. This is ok, there are rules that figure out which actual type is used for the comparison (the int value ...
70,690,912
70,690,989
binary comparison not defined when using map<any,any>
I was looking for a way to have a string[] as a map value, and I found this Stack Overflow question. I attempted to use the std::any type to solve my problem, and I got the error binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator Here is my code: #inc...
std::map by default requires that the key type be comparable with <. std::any does not define any operator< and can therefore not be used as key in the map by default. If you really want to use it in the map as a key, you need to implement your own comparator, see this question. However, the comparator needs to define ...
70,691,206
70,691,233
Access to field results in dereference of a null pointer in C
This question is related to C Programming Language: I get error: Access to field 'x' results in a dereference of null pointer #include <stdlib.h> #include <stdio.h> typedef struct A { int *x; int *y; } A; void allocateStruct(int sizeN, A *aType); void printInfo(A *aType); int main() { A *gen...
You haven't allocated a memory to the structure and yet you are accessing it's member in void allocateStruct(int sizeN, A* aType) { aType->x = (int*)malloc(sizeN * sizeof(int)); aType->y = (int*)malloc(sizeN * sizeof(int)); } allocate memory to the structure itself first atype = malloc(sizeof(A)) You n...
70,691,337
70,691,427
Create a class run at main() get undefined reference to... error
arrayADT.h #include <iostream> using namespace std; template <class T> class arrayADT { private: T *A; static int size; static int length; public: arrayADT(){ size=10; A= new T[size]; length=0; } ...
I found two different problems: The destructor method must have a scope with {} even if it is empty. I removed the static keyword as each object will have size and length property. #include <iostream> #include <stdio.h> #include <string> using namespace std; template<class T> class arrayADT { private: ...
70,691,372
70,692,382
Using predicates in custom implemented data structures
I have a cusom implemented Heap for priority queue application class Heap { SomeCutsomClass elements[100]; .... .... }; Now I need to support two different comparison operation between the keys of the heap and I want to implement it using c++ predicates struct less1 { bool operator()(const SomeCutsomClass&...
Here is an example containing both an example of std::less use and custom predicates as functions (lambdas). #include <cassert> #include <array> #include <iostream> #include <functional> // Make heap a class template // this allows you to specialize easily for any class // I added the STL like third template paramete...
70,691,413
70,694,322
C++ derived-class members after downcasting
I recently learned about upcasting and downcasting in C++. However I came up with a few questions during reading about downcasting. Say I have two classes class Base { public: virtual void foo() {} }; class Derived : public Base { public: Derived(int i) { mem = i; } int mem; }; My question...
It depends; if you cast a Derived object to Base, the result is a new object created by omitting the fields that are not in the Base. However, if you cast a pointer to Derived (i.e. Derived*), the result is a pointer which points to the same object but whose type is Base*. It depends; if you cast a Base object, you g...
70,691,644
70,691,679
How can I repeat a number cycle using mod operator?
I have to loop through 1 <= i <= 20 and every time I mod any i, I want to get a value between 1,2,3. Sorry I have not found any useful resources online. That's why I posted it here. Thanks in advance.
In C++ the % sign acts as the remainder operator. If you do i % 3; The possible values are 0, 1, and 2. Using that as a starting point, we can shift by 1: (i % 3) + 1; The possible values are now 1, 2, and 3.
70,691,678
70,692,354
Is it possible to define a group of template parameters and specialize it conditionally
struct TypeA { using data_t = int; enum { thread_create = pthread_create }; // ??? }; struct TypeB { using data_t = double; enum { thread_create = another_kind_of_thread_create }; // ??? }; template<typename T> class Test { public: void func() { T::thread_create(); // ??? } private: ...
I if understand you correctly, you want to switch thread creation function and data type depending on the specialization. If so, why not sth like this? #include <type_traits> void pthread_create(void*, void*); void another_kind_of_thread_create(void*, void*); //my fakes. use your includes here struct TypeA { usin...
70,692,034
70,733,052
'dllimport' attribute only applies to variables, functions and classes warning even though applied to class function
I'm in the middle of a port to the newest c++ Builder 11 (Clang) compiler and I ran into a warning that I don't understand The warning: 'dllimport' attribute only applies to variables, functions and classes The simplified code: class Test { public: Test() ; int __declspec(dllimport) (*DllFunction) (int a, ...
As the error message says, dllimport cannot be used to import individual class methods. Only standalone variables and functions, and whole classes. However, dllimport is meant for static linking only, but you are using dynamic loading instead, so there is no need to use dllimport in this code at all.
70,692,366
70,692,659
Difference in evaluation of expression when using long long int vs double in c++
I'll refer to the below code to explain my question. typedef long long int ll; void func(){ ll lli_a = 603828039791327040; ll lli_b = 121645100408832000; double d_b = (double)lli_b; cout << "a " << lli_b - d_b << endl; \\0 cout << "b " << (lli_a - 4*lli_b) - (lli_a - 4*d_b) << endl; \\64 cout <...
Some code to walk you through it, bottom line don't mix doubles with ints implicitly #include <cassert> #include <iostream> #include <type_traits> // typedef long long int ll; NO , use using and never use aliasing to safe a bit of typing. Aliases are there to introduce meaning not shortcuts //using namespace std; // ...
70,692,369
70,692,963
Pointers in recursion not working as expected
I'm trying to do BST insertion; struct Node { Node* left; Node* right; int data; Node(int d) :left(nullptr), right(nullptr), data(d) { } }; void Insertion(Node* head, int value) { if (!head) { head = new Node(value); return; } if (head->data > value) ...
You can use a reference to pointer like mentioned in the comment, or you can also use a pointer to pointer like the following: void Insertion(Node** head, int value) { if (!(*head)) { *head = new Node(value); return; } if ((*head)->data > value) Insertion(&(*head)->left, value);...
70,692,502
70,693,027
Converting Apache Arrow Table to RecordBatch in c++
I would like to obtain a std::shared_ptr<arrow::RecordBatch> from an std::shared_ptr<arrow::Table> as std::shared_ptr<arrow:Table> table = ... auto rb = std::RecordBatch::Make(table->schema(), table->num_rows(), table->columns()).ValueorDie(); However the compiler complains that there's no known conversion from 'cons...
There is a helper method arrow::Table::CombineChunksToBatch which should become available in the 7.0.0 release. In the meantime you can do this: ARROW_ASSIGN_OR_RAISE(std::shared_ptr<Table> combined, table->CombineChunks(/*Can pass memory_pool here*/)); std::vector<std::shared_ptr<Array>> arrays; for (const auto&...
70,692,739
70,793,464
Detect client context destruction from gRPC server
I have create an Async C++ gRPC server that offer several APIs similar with a signature similar to this: service Foo { rpc FunctionalityA(ARequest) returns (stream AResponse); rpc FunctionalityB(BRequest) returns (stream BResponse); } The client creates one channel to connect to this service, and uses calls th...
There are two ways to detect call cancellation on the server. The first one is to check ServerContext::IsCancelled(). That is something you can check right before you do a write, which in this case may be fine. In the general case, though, it may not be ideal, because your application might be waiting for some other ...
70,692,897
70,694,614
Last 52 lines are not written in csv file using qt
I have one csv file in which 3 column and 866300 lines. I have try to write this data into other csv file. when i try to write it has write 866248 lines in file after that remaining 52 lines are not write in file. what is the problem I do not understand it. I have try to debug this problem using print that data on cons...
Please close the file before the return a.exec(); this line and after the while loop. add this line below line. write.close();
70,693,002
70,693,600
AtCoder DP Contest Q -I Coins (getting wrong answer may be using double)
Link to Problem -> https://atcoder.jp/contests/dp/tasks/dp_i question Coins-I Code I wrote gave wrong answer to TEST CASE 3 5 0.42 0.01 0.42 0.99 0.42 Expected output 0.3821815872 MY code output 0.382182 As the error is greater than 1e-9 it got WA What I tried: I made double to long double but still it doesn't g...
The number of digits to be printed via output streams is controlled by their precision parameter. The default is 6 digits, if you want more you need to adjust it accordingly by std::setprecision : std::cout << std::setprecision(num_digits) << solve(n,(n-1)/2); Most of your indexing is off by one. Valid indices of an ...
70,693,057
70,693,263
Partial Constructor arguments from tuple
In C++17 there's std::make_from_tuple; However that only applies to situations where the number of the elements stored in the tuple matches with that of the constructor. I was able to concatenate two tuples and use std::make_from_tuple. #include <iostream> #include <utility> #include <tuple> class ConstructMe{ public:...
std::bind does something completely different. Quoting cppreference The function template bind generates a forwarding call wrapper for f. Calling this wrapper is equivalent to invoking f with some of its arguments bound to args. You can just use the cpp reference link to build your own implementation of the standardi...
70,693,121
70,693,396
Why vector's insert() creates a copy of inserted element and assigns to the copy, not the inserted element?
Consider an insert(iterator position, const value_type &x) call: if no reallocation is happening (capacity != size), then in many implementations of the vector I saw this behavior: ... template<typename _Tp, typename _Alloc> void vector<_Tp, _Alloc>:: _M_insert_aux(iterator __position, const _Tp& __...
The __x_copy is only used if the __GXX_EXPERIMENTAL_CXX0X__ macro isn't set. This means it is only used in C++98 and C++03 mode. Nowadays you probably shouldn't be using these old modes without a reason. The macro name also indicates that you have an old copy of libstc++. It was replaced in 2012: https://gcc.gnu.org/gi...
70,693,786
70,693,801
Why is Universal reference being treated as R-Value reference?
#include <iostream> class A { public: A() {}; }; template <class T> class Test { public: void func1(T&& t) { } }; int main() { A a; Test<A> o1; o1.func1(a); return 0; } Following errors are seen on compilation error C2664: 'void Test<A>::func1(T &&)': cannot convert argument 1 fr...
I thought T&& in void func1(T&& t) should be deduced as a universal reference or a forwarding reference [...] No. t in your example is not a universal reference. To be a universal reference it must be deduced from the call, but in your example T is just A. This is a universal reference: template <class T> class Test ...
70,693,916
70,694,339
Why is is showing error in rotating the strings of larger length?
my code #include<bits/stdc++.h> using namespace std; int main() { int n ; cin >> n; string s1 , s2 , s3; cin >> s1 >> s2; string s = s1 + s1; int count = 0; for (int i = 0 ; s3 != s2 ; i++) { // int a = s.find() s3 = s.substr( i , s1.length() ); count++; ...
This is quite simple your for loop has condition which is never false for this input. So you are increasing i beyond size of s (double of size of s1). Note common part of this two strings is: zqpquwjhuftohawpfegsjvnxwipwqlswvawogjuyiqtzsgpwgosegmuuhpzwchejuiitumyescxxyecnsatcbfpseqzowvdjyvchg. Difference is: s1 has i...
70,694,337
70,694,556
template function overloading ambiguity
A beginner's question here, so I have the following code foo.h enum class Fruit : uint16_t { Apple = 8019U, Orange = 8020U, Banana = 8021U, Cactus = 8022U }; class Foo { public: template<typename T> void SetValue(unsigned int location, const T& value); template<typename T> void SetValue(unsi...
I'm aware that this is ambiguous It is not. const T& value is a better match than const T* value for float*. The former is an exact match, whereas the later require a qualification conversion. You might drop the const for pointer: template<typename T> void SetValue(Fruit fruit, T* value_ptr); Demo
70,694,478
70,694,662
Same array giving garbage value at one place and an unrelated value at the other place
In the following code: #include<iostream> using namespace std; int main() { int A[5] = {10,20,30,40,50}; // Let us try to print A[5] which does NOT exist but still cout <<"First A[5] = "<< A[5] << endl<<endl; //Now let us print A[5] inside the fo...
Well you invoke Undefined Behaviour, so behaviour is err... undefined and anything can happen including what your show here. In common implementations, data past the end of array could be used by a different element, and only implementation details in the compiler could tell which one. Here your implementation has plac...
70,694,574
70,695,113
Checking reversed text on C++ (doesn't work with a -1 index?)
I was making a simple palindrome checker and can't understand why the iterator works with index 0, but won't work with index -1, you can see that both codes print the SAME text, but not the same boolean. Can anyone explain me what's the logic behind this? The only different part on both codes is this: for(int i=text....
C++ uses 0-based indexing, ie valid indices of a N sized container are 0,1,2...N-1. If you try to use an index out of bounds your code invokes undefined behavior. Look at the output of this code: #include <iostream> #include <string> void foo(const std::string& text){ for(int i=text.size();i>=-1;i--){ std:...
70,694,600
70,705,984
How can I read lines from a text file into a variable
I know that there's many questions here about reading lines from a text file and storing it in a c++ struct. However, those questions all contain text files that have precisely the information they needed, such as a text file with : Tom 123 Jim 234 However, what if my text file had something like // The range of 'hor...
I managed to solve this by adding in if (line[0] != '/' && !line.empty()) { inside the while loop and creating a new string variable called lineArray[5]. The function now looks like this config openFile(std::string filename, config &con) { std::fstream inputFile(filename.c_str(), std::fstream::in); if (inpu...
70,694,660
70,694,762
How to obtain nanosecond file creation time in C++
In the process of software development, I encountered a requirement to obtain the time stamps of file creation time, modification time and access time. It is easy to obtain this information by calling struct stat related interfaces, but the requirement is to obtain nanosecond timestamps. So I don't know what to do, is ...
Not all file systems support this (ext4 does): struct stat result; if (stat(filename, &result) == 0) { printf("Last access of %s: %sns: %ld\n", filename, ctime(&result.st_ctim.tv_sec), result.st_ctim.tv_nsec ); } else { fprintf(stderr, "%s: %s.\n",...
70,694,672
70,694,754
C++ How to make a non void function return nothing for if else statements?
So my problem goes like this: string something (string something){ string letter; cout << "press a"; cin >> letter; if (letter==a){ return a; } else cout << "wrong letter"; //what should I put here if I don't want it to return any value? } Any alternatives would also be welcome
One way to handle this would be a std::optional<std::string> #include <optional> std::optional<std::string> dingas(std::string something) { string letter; cout << "press a"; cin >> letter; if (letter==something){ return "a"; } else { std::cout << "wrong letter"; retu...
70,695,086
70,697,779
How Do I Set Include Path Library Directory And Linker For VSCODE When I Have Visual C++ Build Tools To Work With (not g++)
I have set up VS code as my development environment and used MSVC build tools (cl.exe compiler) instead of g++. I tried to set up SFML for my environment. I want to know how do I set the SFML include path and library path. And also, How do I perform static Linking with cl.exe. Note: I am using only VS code and NOT Visu...
As mentioned in the comments, you need to use a C++ build system to manage dependencies and build your project. VSCode does not come with any built-in build systems like Visual Studio does. VSCode tasks allow you to specify a command line, which can then be invoked easily in the IDE. The task shown is just a "build act...
70,695,121
70,695,181
how does getline() read a multiple-line file in loops?
I have some confusion about the use of std::getline function. see the following code: #include <sstream> #include <string> std::ifstream ifs(filename); std::string line; while (std::getline(ifs, line)) { //...// } for ( std::string s; getline(ifs, s)){ //...// } For both of the while loop and the for loop, it se...
A file stream is a source of bytes (“characters”). Each time you read a character from the file the file get pointer is advanced to the next character to read. That is, each time you read, you get the next unread character. std::getline() simply reads characters until it gets the delimiter value (which is '\n' by defau...
70,695,178
70,695,590
Why do we need to downcast a variable even if the function will upcast it again right before returning?
While reading a book about modern C++, I have seen a code snippet that confused me. The code has been written to set up PWM (16 bit Timer) for 8 bit AVR microcontroller. The code is like that: class pwm_base : private util::noncopyable { public: typedef std::uint_fast16_t duty_type; pwm_base(const duty_typ...
This code seems severely over-engineered, which is always the biggest danger whenever you allow C++. The language tends to encourage making things needlessly complicated just for the heck of it, instead of utilizing the KISS principle. The hard requirements are: on the given hardware, the CPU works fastest with 8 bit t...
70,695,190
70,695,250
If code changed to std::move(vector) will that save a copy operation in this function
The function is to extract the file contents into a vector as below: std::vector<uint8_t> GetFileContents(const std::string& filename) { std::ifstream file(filename, std::ios::binary); if (!file.good()) { return {}; } file.seekg(0, std::ios::end); std::streampos fileSize = file.tellg(); ...
No, you shouldn't use std::move there. That avoids possible NRVO, and there is an implicit move anyway. See Automatic_move_from_local_variables_and_parameters for further detail.
70,695,389
70,695,489
Returning anonymous struct from template function (for structured binding)
I wanted to use new C++17 features and wanted to use a structured binding to return multiple values from a (template) function. I can get it to work, but I want it to work better. A simplified version of the code is (the real code is larger and have better variable names): template <class O> struct { int a; double...
How about local struct: template <class O> auto F(int i, O o) { struct { int a; double b; } res {i, o(i)}; return res; } void foo(int i) { auto [a,b] = F(i, [=](int k)->double {return 1.0/k; /*...*/}); // ... }; Demo
70,695,554
70,695,589
Difference between -= and =- in C++ and C?
I often confuse both "-=" and "=-", like what is the exact difference between them? int main() { int x=10, a=-3; x=-a; printf("%d",x); return 0; } Output 3
-= is a compound assignment operator. =- is two operators applied seperately. While a =- 3; is the same as a = (-3); This x -= a; is more or less equivalent to x = x - a; "More or less" because operators can be overloaded (in C++) and typically the compound operator avoids the temporary right hand side. Btw you ar...
70,695,969
70,696,112
Why is pair not working with unordered_map?
The following code doesn't compile. The line with pair is giving the error. Is there some other way to access the data or is this way correct?? unordered_map<int,int> hm; unordered_map<int,int>::iterator it; it=find(hm.begin(),hm.end(),x+c); if (it!=hm.end()) { bNotFound = false; pair<int,int> p = *it; ind = p.se...
Sometimes the compiler does a lousy job with the error messages. Your problem is the find algorithm. unordered_map & map have their own find, which take the key as argument and returns an iterator. The algorithm is looking for the key: auto it = hm.find(key); if (it != hm.end()) { // ... } The global find ...
70,696,083
70,696,399
For reversing a number in C++ which ends with zeros
I want to write a program for reversing a number. For reversing a number like 2300 to 32 so that the ending zeros are not printed, I found this method: #include<iostream> using namespace std; int main() { int l; cin>>l; bool leading = true; while (l>0) { if ((l%10==0)&& (l...
The reason for the difference in output is because when you make leading = false inside the if statement, you are making it false right after encountering the first zero. When you encounter the remaining zeroes, leading will be false and you will be printing it. When you make leading = false outside the if statement, y...
70,696,092
70,728,366
C++ Store an expression template inside a class whose objects will be part of a vector
[Extensively edited for clarity and typos, and now with attempted solution, old version at the end] New version of the question I have a class which needs to store a functor. The problem is that the functor is an expression template (meaning that each functor is of different type). On top of that I need to collect all ...
I see you have improved your question. Yes there are debatably better solutions. One nice solution the std lib offers you, is to use type-erasure using std:function. #include <vector> #include <functional> #include <iostream> #include <cmath> struct FunctorTypeA { double a; FunctorTypeA(const double ap): a(ap)...
70,696,149
70,696,541
Comparator for matching point in a range
I need to create a std::set of ranges for finding matching points in these ranges. Each range is defined as follows: struct Range { uint32_t start; uint32_t end; uint32_t pr; }; In this structure start/end pair identify each range. pr identifies the priority of that range. It means if a single point falls ...
find returns an element that compares equivalent to the argument. Equivalent means that it compares neither larger nor smaller in the strict weak ordering provided to the std::set. Therefore, to make your use case work, you want all points in a range to compare equivalent to the range. If two ranges overlap, then the p...
70,696,610
70,696,844
Is there an easier way to get the current time in hh:mm:ss format?
I tried to print the current time in the usual format of hh:mm:ss however I get the full date format instead. I need the answer to be in string or int, so it is easier to deal with. I was thinking of adding it to a log file so that I can make it easier to track my program. #include <iostream> #include <chrono> #include...
The following example displays the time in the "HH:MM:SS" format (requires at least c++11 - tested with clang): #include <iostream> #include <iomanip> #include <chrono> #include <ctime> int main() { std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); std::tm ltime; local...
70,696,879
70,697,114
Visual Studio 2019/C++ bug?
I'm using native C++ with Visual Studio 2019 16.11.8. I don't understand this: whis can the false keyword be used as NULL (or nullptr)? Below the test code: bool test(bool* pb) { if (NULL != pb) return *pb; else return false; } void main() { test(false); // compiles (not what I was expectin...
MSVC treats the expression false as a null pointer constant. A null pointer constant can be implicitly converted to any pointer type, resulting in a null pointer value. The correct behavior according to the standard is to treat only integer literals with value 0 as null pointer constants. Although it has value 0, false...
70,697,017
70,697,142
Is there a way to declare a class and then define it later in c++?
So i want to declare a function func(temp t1, temp t2) and use it in class temp. But i do not want to define it as a member function of the class temp mainly because i want other functions to be able to access func without using any object of temp. I know it is possible by declaring func() as a friend to temp but is th...
Yes it is possible. One example is given below: func.h #pragma once //declaration for class temp class Temp; //declaration for function func void func(Temp t1, Temp t2); func.cpp #include "func.h" #include "temp.h" #include<iostream> //implementation for function func void func(Temp t1, Temp t2) { std::cout<...
70,697,368
70,722,337
How to let a thread wait itself out without using Sleep()?
I want the while loop in the thread to run , wait a second, then run again, so on and so on., but this don't seem to work, how would I fix it? main(){ bool flag = true; pthread = CreateThread(NULL, 0, ThreadFun, this, 0, &ThreadIP); } ThreadFun(){ while(flag == true) WaitForSingleObject(pthread...
While the other answer is a possible way to do it, my answer will mostly answer from a different angle trying to see what could be wrong with your code... Well, if you don't care to wait up to one second when flag is set to false and you want a delay of at least 1000 ms, then a loop with Sleep could work but you need ...
70,697,517
70,697,728
c++ libcurl get request is returning 0 but still printing in the console
I've installed libcurl on ubuntu 20.4 and I've been playing around with it. I decidedly wanted to create a program that would write a file from the internet. So I wrote this. #include <iostream> #include <string> #include <curl/curl.h> #include <fstream> #include <unistd.h> int main() { std::ofstream htmlFile("inde...
curl_easy_perform returns a CURLcode. where "CURLE_OK (0) means everything was ok". That's what is written to your file. If you want to capture the text inside the program, you need to set a callback function with CURLOPT_WRITEFUNCTION and also provide somewhere to store the data via CURLOPT_WRITEDATA Example: #includ...
70,698,268
70,730,409
constexpr position in variable declaration
Usually I like to put "const" behind the type, as int const foo1 = 123; Now, if i want to declare a second variable (which should even be constexpr) I would like to use the same style: int constexpr foo2 = 123; However, this led to a warning upon running a code analysis tool (however, all compilers I tried accept it)...
constexpr is a decl-specifier, as are int and const. Other decl-specifiers are for example thread_local, mutable, extern, virtual, extern, friend, typedef, consteval, constinit and inline, as well as other type-specifiers such as volatile, long, double, auto, signed, decltype(...), names of types, types introduced by c...
70,698,367
70,701,420
Is it possible to expand GCC/Clang compile and link options that start with "-f"?
I write C/C++ with GCC/Clang, but know little about compiler options that starts with "-f". For example, to turn on Address Sanitizer, I pass "-fno-omit-frame-pointer -fsanitize=address" to the compiler. This should both affect compile and link stages. Another example, to turn on OpenMP, I pass "-fopenmp" to the compil...
Let's check the docs of clang at https://clang.llvm.org/docs/ClangCommandLineReference.html --verbose or -v looks very promising. A quick check at compiler-explorer.com gives promising results. GCC has a similar page with all options: https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html Here we have -v as well, thoug...
70,698,391
70,700,081
How to correctly loading shp file by code
I am trying to load a .shp file by OGRFeatureSource class, and it is not showing in the scene, but when I load .earth file, using osgearth_viewer by arguments, the shape file works. Any errors are printing on terminal. I based my code on tutorials that i found on web, but i think these are for an old version (some clas...
Your AltitudeSymbol also needs to specify the clamping: alt->clamping() = alt->CLAMP_TO_TERRAIN;
70,698,635
71,745,745
QRect of full Virtual Desktop on Qt6
How to get QRect of a full Virtual Desktop? For example, for putting a window on a whole Virtual Desktop (multimonitor system). The obsolete Qt5 function is: QApplication::desktop()->geometry()
Something like this: QRect desktopRect() { QRegion virtualGeometry; for (auto screen : QGuiApplication::screens()) { virtualGeometry += screen->geometry(); } return virtualGeometry.boundingRect(); }
70,698,656
70,698,708
In struct nested union/array member default initialization compiles, but is not happening correctly?
I am trying to initialize array members at struct declaration in the following struct with nested union & array: struct Nested { union { short sArray[5] = {42}; float fVal; // Must NOT be initialized - obviously, only 1 member of a union can be }; double dArray[5] = {77.7}; }; While the code com...
What you are doing is aggregate initialization, which means the elements in sArray and dArray are value initialized when not specified. Because short and double are scalar types, this means zero initialization Since you don't specify anything but the first element, all remaining elements will be initialized to 0 As req...
70,698,805
70,698,847
Why is this code running without vector header file?
I couldn't find out why is the code below working fine on my local system without including the vector header file but not on online judges or online compilers. #include<iostream> #include<algorithm> using namespace std; int main(){ vector<int> v(10); for(int i = 0; i<10; i++) v[i] = i; sort(v.begin(),v.e...
Your algorithm header itself includes the vector header (either directly or indirectly). Because of this, the code after the preprocessor looks the same as if you had included the vector header yourself. You should not rely on this behavior though, as it depends on the standard library implementation you are using and ...
70,698,842
70,699,109
concept to check existence of function in class (problem in GCC?)
I would like to detect if a function (operator() in my case) is present in a class, regardless of its signature or whether it would be possible to get a pointer to it (may be impossible without additional info because it is templated or overloaded). The following code using a concept compiles on MSVC and clang, but not...
First, the way to check a concept is just to static_assert (not to try to instantiate a constrained class template). static_assert(HasCallOperator<functor>); static_assert(HasCallOperator<functorOverloaded>); static_assert(HasCallOperator<functorTemplated>); Second, you can't write t.operator() for the same reason tha...
70,698,852
70,963,934
Unable to delete file with _wremove API (permission issue)
I'm unable to delete a temporary file from my C++ application, it's failing with "permission denied" error. Here's the code snippet, void DeleteTempFile(const std::wstring& path) { wchar_t* wc = const_cast<wchar_t*>( path.c_str() ); if( _wremove( wc ) != 0 ) Log(fatal, std::string("Error: ") + std::stre...
From Microsoft docs: remove, _wremove [...] Return Value Each of these functions returns 0 if the file is successfully deleted. Otherwise, it returns -1 and sets errno either to EACCES to indicate that the path specifies a read-only file, specifies a directory, or the file is open, or to ENOENT to indicate that the fi...
70,698,983
70,699,009
Const after operator function c++
I'm learning C++ i saw a const after an operator function. It doesn't make sense because the function returns the same value regardless of the const. What's the purpose of using it? using namespace std; class Person { public: int age; Person(int age) : age(age) {} int operator *(int &b) const { re...
A const operator behind a member function applies to the this pointer, i.e. it guarantees that the object you call this function on may not be changed by it. It's called a const-qualified member function If you tried, in this example, to change the persons age in the openrator*(), you would get a compile error.
70,699,450
70,699,709
How do I use catch2 just by cloning its repository and copying its src to my project?
I am trying to get catch2 running for a barebone project just to get familiar with it but so far I failed installing it in whatever sense possible. the catch2-git repository either points you to installing it together with cmake (via vcpkg (I cannot use MSVC and don't want to at this point) or points to some Ubuntu sol...
The GitHub page says: Catch2 v3 is being developed! You are on the devel branch, where the next major version, v3, of Catch2 is being developed. As it is a significant rework, you will find that parts of this documentation are likely still stuck on v2. For stable (and documentation-matching) version of Catch2, go to t...
70,699,498
70,738,590
Retrieve always latest messages from Kafka on reconnection
I'm writing a piece of code that needs to read hundreds of messages from Kafka each few milliseconds. I'm using C++ and librdkafka. When my program stops and then restarts it does not need to recover all lost messages since it was stopped, but instead it needs to always read from latest messages sent. As far as I know ...
Finally I solved by managing myself the callback on rebalance. This callback will be always executed when a new consumer join or leave the group. The rebalance callback is responsible for updating librdkafka's assignment set based on the two events: RdKafka::ERR__ASSIGN_PARTITIONS and RdKafka::ERR__REVOKE_PARTITIONS. ...
70,699,881
70,699,942
C++ : Is there a good way to choose between 2 implementations?
Is there a good way for my header class to choose which .cpp file he can call at runtime? For example : a.h #pragma once #include <iostream> class a { public: a() {}; void printA(); }; a.cpp : #include "a.h" void a::printA() { std::cout << "first"; } a_mockup.cpp : #include "a.h" void a::printA...
You cannot have two implementations of one function. That would violate the One Definition Rule. You cannot link both translation units into one program. You can choose between two implementations at link time. If you link the main.cpp translation unit with a.cpp, then you call that implementation, and if you link with...
70,700,179
70,700,671
Why is a lambda considered an expression (Or: What constitutes an expression in C++)?
Lambdas are considered expressions. According to cppreference an expression is "a sequence of operators and their operands, that specifies a computation." An expression also has a value category and a type: "The lambda expression is a prvalue expression of unique unnamed non-union non-aggregate class type [...]" The un...
What's the value of this expression? Is it an object of the unique class type? Yes, exactly that. Where is the computation that is mentioned in the cppreference definition? In the same way that 1 or std::vector<int>{} can be said to compute values, so do lambda expressions. On their own, those all do nothing. The v...
70,700,370
70,752,733
How do I compile and deliver my application without requiring installation of shared libraries on other machines
On my Ubuntu machine I installed libGLEW. However, I did not install it on my other Ubuntu machine. It works on my compiling machine, but now I received the following error after copying my executable to my other machine. I want to find a solution where I don't have to require my other machine to install the library. M...
To solve the issue for my situation, I added glew.c to my source files which solves the issue.
70,700,386
70,700,618
Do the order of edges matter in union find?
I am learning union-find and to understand it better, I have written a small program: #include <iostream> #include <vector> #include <numeric> using namespace std; vector<int> parent, sz; int find(int i) { if(parent[i]==i) return i; return parent[i]=find(parent[i]); } void merge(int i, int j) { int p1...
The output you got does not signify that one node is disconnected. The parent data structure represents links from one node to another (or itself, when it is a root). At the start you have this: And at the end we have this: The important thing here is that there is one tree. It is not required that all nodes are link...
70,700,592
70,701,809
What is a correct way to setup protobuf and grpc for cpp project?
I have a cpp project, and I want to build everything from source, to get latest things likned in. So under my project root I've created a 3rd_party folder and assemble following script: sudo apt-get install autoconf automake libtool curl make g++ unzip -y git clone https://github.com/google/protobuf.git cd protobuf git...
Here are the steps I took: $ mkdir .local $ export INSTALL_PREFIX="$PWD/.local" $ export CMAKE_GENERATOR=Ninja # optional, but recommended $ git clone --recurse-submodules -b v3.19.3 --depth 1 https://github.com/google/protobuf.git $ pushd protobuf $ ./autogen.sh $ ./configure --prefix=$INSTALL_PREFIX $ make -j$(npro...
70,700,659
70,710,235
c++ boost locale - generator throws runtime_error with "Invalid file format" message
I try to reproduce the example of boost locale documentation with this piece of code : #include <boost/locale.hpp> #include <iostream> #include <stdexcept> using namespace boost::locale; using namespace std; int main() { generator gen; // Specify location of dictionaries gen.add_messages_path("./languages"...
I forgot to compile the .po file... xgettext generates a .po text file which needs to be compiled into a .mo file. This can be done with msgfmt : msgfmt hello.po -o hello.mo
70,701,701
70,707,906
Dynamic Programming Using STL Vectors Makes Program Freeze Beyond Certain Values
I wrote the following program, trying to optimize a recursive algorithm using Dynamic Programming. #include <bits/stdc++.h> using namespace std; int mini(int n, vector<int> &memory){ if(n<memory.size()){ return memory[n]; } else{ int m = (n+1)+mini(((n-1)/2), memory)+mini(((n-1)-((n-1)/2))...
Following insights from the comments, the problem has been solved. There were two issues with the initial program: Trying to insert elements beyond the current size of the vector: To fix this issue, use an if statement before inserting elements to the vector to ensure that it has the correct capacity. if(memory.capaci...
70,702,030
70,702,125
How to use three-way comparison (spaceship op) to implement operator== between different types?
Simple Task: I have these two types struct type_a{ int member; }; struct type_b{ int member; }; I want to use this new C++20 spaceship op that everyone says is so cool to be able to write type_a{} == type_b{}. I didn't manage to do that. Even if I write operator<=> between them, I only ever can call type_a{} <=...
The premise of the question is wrong. You don't use the three-way comparison operator (<=>) to implement ==: you use == to implement ==: bool operator==(type_a a, type_b b) { return a.member == b.member; } The source of confusion is that there is one exception to this rule: if a type declares a defaulted <=> then ...