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 |
|---|---|---|---|---|
63,156,313 | 63,160,493 | Fastest way to send struct containing pointer through TCP socket | Please keep in mind that I'm trying to build sub-millisecond level latency sensitive server.
Therefore, I want to keep the process as minimal as possible. Such as minimizing memcpy call.
Here's the thing.
Let's say, I have a following struct:
struct data {
int sequence;
...
size_t len;
void* buf;
}
Simplest wa... | If you have struct like this
struct data {
int sequence;
...
size_t len;
void* buf;
};
data my_data;
you can send it like this:
send(fd, &my_data, sizeof(my_data) - sizeof(void*));
send(fd, my_data.buf, my_data.len);
This code looks unclear and will break if someone change fields order. But, probably, it's f... |
63,156,430 | 63,157,966 | Seeking correct CLSID for Control Panel | I am trying to filter IShellFolder::EnumObjects result, by following instructions from this question.
Although links from the highest voted answer are invalid, I was able to find them and apply Mr.Chen's code in my own. Everything worked fine for Recycle Bin, it was filtered out, but Control Panel stayed.
Below is the ... | According to the Registry 1, {26EE0668-A00A-44D7-9371-BEB064C98683} is for the "Control Panel", whereas {21EC2020-3AEA-1069-A2DD-08002B30309D} is for "All Control Panel Items".
1: See the HKEY_CLASSES_ROOT\CLSID\{26EE0668-A00A-44D7-9371-BEB064C98683} and HKEY_CLASSES_ROOT\CLSID\{21EC2020-3AEA-1069-A2DD-08002B30309D} ke... |
63,156,441 | 63,157,790 | How to run a program when a service crashes in Windows in C++? | I would like to run another program when a service crashes. I know that I should use SERVICE_FAILURE_ACTIONS and ChangeServiceConfig2() provided by Microsoft. But, I got stuck using them because I can not find any example of using these structure and function.
I would appreciate it if anyone can show me an example to i... | It's not so hard. You need something like this:
SC_ACTION sc_actions = { SC_ACTION_RUN_COMMAND, 0 };
TCHAR command [] = __T ("path/to/command");
SERVICE_FAILURE_ACTIONS failure_actions =
{ INFINITE, NULL, command, 1, &sc_actions);
BOOL ok = ChangeServiceConfig2 (service_handle,
SERVICE_CONFIG_FAILURE_ACTIONS, ... |
63,156,638 | 63,157,204 | c++ binary arithmetic operator for returning derived type? | im wraping glm library and when i encapsulate the Vector3 derived from glm::vec3, i found i can literally use Vector3 a = b + c where b and c are both Vector3
but when i tryed it on my own project, i got no suitable user-defined conversion error,
here's my code:
#include <iostream>
#include <assert.h>
using namespace s... | You could provide a constructor that converts a cbas to C such as:
struct C : cbas
{
C (const cbas& c):cbas{c.value}{}
};
|
63,156,916 | 63,174,845 | Access to STL lists of pointers to objects | I wonder how to get access to element of list that contains pointers to objects. I want to achieve that without dereferencing. Propably it will be much easier if i just show what i want. So I have list:
list<ObjectClass*> nameOfObject;
and I have method:
bool collision(list<ObjectClass*>::iterator&);
And inside defin... | You usually don't pass single iterator around.
If you want single object, pass single object (whether by reference or pointer)
I write an example code, hope it helps.
fIter is probably what most close to what you currently have
f is demonstrate you can iterate collection without directly use iterator
//
// https://... |
63,156,964 | 63,157,072 | Using std::make_pair with std::string (non rvalue reference problem) | std::pair<Url, std::string> UrlParser::parse()
{
return std::make_pair({ extract_scheme(), extract_hostname(), extract_port(),
extract_path(), extract_filename() }, host_ip_);
}
The host_ip_ variable is defined as
std::string host_ip_;
I get
UrlParser.cpp:91:64: error: no matching function for ca... | The problem has nothing to do with passing host_ip_ as lvalue or rvalue to std::make_pair; both should work fine. Instead, the braced-init-list { extract_scheme(), extract_hostname(), extract_port(), extract_path(), extract_filename() } makes template argument deduction for the 1st template paramter of std::make_pair f... |
63,157,172 | 63,157,359 | How do i convert an array with booleans to a byte in Arduino/C/C++? | I'm new in arduino programming (c/c+). And would like to convert a array with bool's to an byte like. The booleans repreprents a buttons here.
bool array[] = {0,1,1,0}; // needs to convert to 0b0110
// bool array[] = {1,0,0,0}; // needs to convert to 0b1000
// bool array[] = {true,true,false,true}; // needs to convert ... | I can't rewrite all your code right now, but I can lay out a basic algorithm. I think it'll help you.
You need something, either in a loop or hardcoded (if you really only have four bits). For brevity, I'm going to call your array a and I'll just hardcode the calculation so it's super-clear.
If you think of the entri... |
63,157,338 | 63,157,586 | C++ check std::array or unordred_map/map contain same element type | I have a templated class accepting a container of MyIDType:
std::array<MyIDType, SIZE>
std::unordered_map<A, MyIDType>
std::unordered_map<B, MyIDType>
etc
I'd like to statically-assert for MyIDType being the element. I tried this:
template<class CONTAINER>
class Cod
{
using ELEMENT_TYPE = typename CONTAINER::valu... | You can define a type trait like
// primary template, for types containing value_type
template <typename T, typename = void>
struct get_element_type {
using type = typename T::value_type;
};
// partial specialization, for types containing mapped_type
template <typename T>
struct get_element_type<T, std::void_t<type... |
63,157,825 | 63,170,898 | target_link_libraries adds unwanted optimization flag when compiling in Debug mode, how-to remove? | I am including this external library https://github.com/S-Dafarra/alglib-cmake when compiling one of my projects.
In my CMakeLists.txt, I add link this library as PRIVATE:
find_package(ALGLIB REQUIRED)
target_link_libraries(<target> PRIVATE ALGLIB)
When I compile my project in debug mode with make VERBOSE=1, I find an... | Thanks for your inputs.
I followed your suggestion and came up with this solution:
find_package(ALGLIB REQUIRED)
if (CMAKE_BUILD_TYPE STREQUAL Debug)
get_target_property(ICO ALGLIB INTERFACE_COMPILE_OPTIONS)
string(REPLACE "-O3" "" ICO ${ICO})
string(REPLACE "-" " -" ICO ${ICO})
separate_arguments(ICO)... |
63,157,992 | 63,158,139 | Using a struct variable as a formal parameter | #include <iostream>
using namespace std;
void input(partsType inventory[100]&)
{}
int main()
{
struct partsType
{
string partName;
int partNum;
double price;
int quantitiesInStock;
};
partsType inventory[100];
}
I am trying to use a struct variable as a formal parameter. Later I ... | You have two issues:
You need to define the partsType outside the main, and of-course
before the input function otherwise, it does not know what is partsType.
Secondly, your function parameter syntax is wrong. It should have
been
void input(partsType (&inventory)[100])
// ^^^^^^^^^^^^^^^^^^ --> if y... |
63,158,083 | 63,158,202 | How do I order a set of integers from smallest to greatest without if statements? | I'm currently stuck on a C++ problem that asks me to sort five inputted integers from least to greatest. I've tried using if statements to do this, but it just seems way too inefficient to list out all the possible combinations. I've also experimented with the min and max functions, but these only work on the smallest ... | The standard library has a function called std::sort, which works on any range. You can either put the numbers in an array, or you can put them in some other contain (like std::vector). In this case, arrays are simple enough given the five-item restriction. For example:
#include <iostream>
#include <algorithm>
#incl... |
63,158,169 | 63,164,502 | Android NDK 2020 C code - How to enable release mode with all optimizations |
I see that people do this by changing their Android.mk and Application.mk files. However, I cannot find the file in my project at all. What I wish to do is to optimize the code as much as possible (in Visual Studio, Release mode can be 10x faster than Debug mode). How can I do this in android NDK ?
Thank you.
APP_OPTI... | If you'd like to specify some options manually only in release configuration, append cppFlags to the relevant section in app/build.gradle as follows.
android {
:
buildTypes {
release {
// debuggable false
minifyEnabled false
proguardFiles getDefaultProguardFile('pro... |
63,158,351 | 63,165,022 | How to make a hierarchy of different object "generators" in plain C++11 | What I need is the following hierarchy of classes (given here as a sketch):
class DataClass {}
class AbstractGenerator {
public:
// Generates DataClass objects one by one. In a lazy manner
virtual DataClass produce() = 0;
}
class RandGenerator : AbstractGenerator {
public:
RandGenerator(int maximal_int) :... | boost::function_input_iterator is the normal tool for this job, but since you want "plain" C++, we can just reimplement the same concept.
class generator_iterator {
std::shared_ptr<AbstractGenerator> generator;
public:
using iterator_category = std::input_iterator_tag;
generator_iterator(std::shared_ptr<Abstra... |
63,158,352 | 63,158,423 | C++ Smart Pointers Scope and Resource Deleting | I have the following simple code example:
#include <iostream>
#include <utility>
#include <memory>
using namespace std;
class resource
{
public:
void print() { cout << "Class Still Alive" << endl; };
};
resource* create_resource()
{
std::unique_ptr<resource> r = std::make_unique<resource>();
return r.get();
... | Yes, your understanding is correct about the function scope. The std::unique_ptr<resource> will be destroyed after the create_resource function scope.
So how is the actual resource wrapped by the unique pointer still
reachable and does create a segmentation fault since its owning unique
pointer should have gone out o... |
63,158,439 | 63,158,998 | bazel run immediately Segmentation faults | I am trying to use a locally built package (this one) within an existing bazel project. It bazel builds without any errors, but when I try to bazel run it, it immediately segfaults. I tried building it in debug mode, but when I run it in debug mode it still immediately segfaults without any useful error message.
I buil... | I found my mistakes. First, I was changing a lot of things and forgot to rebuild the external package, so the libraries didn't exist... oops.
But more importantly, when the external package is built, it outputs library files that have file extensions other than .o and .so so I had to change the following line in the cc... |
63,158,979 | 63,159,343 | error: no matching function for call to 'std::optional<smoltcp::Buffer>::optional(smoltcp::Buffer&)' | I am trying to make a function that returns an std::optional to Buffer:
std::optional<Buffer> receive(SmolSocket smolSocket)
{
//...
return std::optional<Buffer>(buffer);
}
Where Buffer is simply
struct Buffer
{
public:
std::unique_ptr<uint8_t[]> data;
size_t len = 0;
bool empty = false;
Buffer(CBuf... | The problem is, in order to do
std::optional<Buffer>(buffer);
you need a copy-or-move constructor. When you provide a parameterized constructor (i.e. Buffer(CBuffer cBuffer)), the compiler will not generate both of them. So you need to explicitly provide them.
However, in your case, you have one more issue. The member... |
63,159,019 | 63,234,802 | Type mismatch with Regex match in C++ Windows API | Expected result: print the regex match text in a Window
Tools: Visual Studio 2019
Language: C++, Windows API
Error message: Usually I get weird characters (as with the example below), which I understand is probably a Unicode conversion problem. Sometimes I also get various messages, depending on what method I use to co... | Found the answer here: https://stackoverflow.com/a/35348217/14017267
The working code:
#include<regex>
...
wstring target(L"The answer is blowing in the wind");
wsmatch wideMatch;
wregex wrx(L".+(answer).+");
sendToReportWindow(L"text to search using regex:%s\n", target.c_str());
if (regex_mat... |
63,159,023 | 63,159,578 | Limit recursion on C++ target | While fuzzing a language made with antlr, the fuzzer reported a slow testcase that was using quite a lot of parens.
One of the rules in the grammar is somewhat like:
paren_expression: '(' expression ')';
Even if it was reported as a slow unit, it underlies the bigger problem of being able to somewhat easily crash the a... | You could add a predicate that checks how deep the nested expression is, and let the predicate fail if it exceeds a certain number.
For example, you allow a maximum of 3 nested expressions, you could do that like this:
grammar T;
@members {
private int depth = 0;
}
parse
: expr EOF
;
expr
: '(' expr ')' {++dept... |
63,159,123 | 63,159,822 | How can I include the Firebase libraries into a program in c++? | I am trying to use Firebase in a Windows program in C++, but I can't find the documentation on the firebase web.
Any help?
| Firebase's only C++ support is in the context of its Games SDKs, so you can find it under the Games heading in the left navigation. The setup page is here.
|
63,159,477 | 63,159,592 | Inheritance In Default Constructor Definition | I've been learning about Design Patterns and in my implementations of Strategy Design Pattern I discovered that I couldn't declare inheritance in a class definition like so:
class Context
{
private:
Strategy *strategy_;
public:
Context(Strategy* strategy) : strategy_(strategy); // This line
~Context();
... | You write one of:
Context(Strategy* strategy) : strategy_(strategy) {} or Context(Strategy* strategy); in your class declaration.
That colon doesn't indicate inheritance at all here, but direct member initialization. It's a very good thing to use in C++ and I highly recommend it. But you use it when you are implementin... |
63,159,518 | 63,159,712 | vector<Class> --- Question about Copy Constructor in Class | Upd: Sorry if I bother somebody with such questions. I'm 48. I'm trying to get a new profession to live from. And I need little more info than 'Do this. Don't do that. And never ask why.' :)
Thanks all for answering and patience with me_kind people :)
I have Class Car.
class Car {
protected:
std::string Name;
s... | The correct declaration for the copy-constructor should be:
Car(const Car& other)
Same with the copy-assignment operator, which also needs a return value of Car& as well:
Car& operator= (const Car& other)
{
...
return *this;
}
Also, your move-constructor is implemented incorrectly. It is copying the Name mem... |
63,159,520 | 63,161,400 | Replacing vector with array or static vector for a better approach | My application runs particular number of processes(different executables) using createprocess(windows api) in parallel(using threads). User can refresh / close my application at any time. As of now, I am pushing the process handles into vector and whenever close request received, I am iterating the vector and terminati... | You should not use handles (in GetExitCodeProcess for example) after they are closed.
I would simply not close those process handles in the threads, and just leave them for the forceKill or other clean-up function to close.
Also, since you are not using procInfo.hThread, you could close it right after CreateProcess ret... |
63,159,662 | 63,161,421 | Techniques for getting compile time errors for switch statements which do not have handlers for all enums? | Let's say you have an enum class with several values. Using the enum class makes the code more typesafe, but the issue I run into is that I often have switch statements on the enum, which are supposed to handle all cases. What I'll typically do, is have the default throw an exception, the issue being that I'd rather ha... | A compile time check is definitely what you want. The big-3 compilers have command line options to achieve that.
GCC and Clang provide the -Wswitch warning that checks for exactly that. You turn it into an error with -Werror=switch.
MSVC has warning number 4062. You make it an error with /We4062.
Now you can forget t... |
63,159,807 | 64,123,081 | Return Array of Eigen::Matrix from C++ to Python without copying | I have some C++ code that generates and manipulates arrays of Eigen matrices.
In the end I want to use those matrices in python and thought this might be a job for pybind11.
Basically what I want back in python are two nested lists / numpy arrays
mat_a(I, 4, 4) and mat_b(J, K, 4, 4).
Because I have to do a lot of linea... | Your best option may be to create the data on python side so it gets refcounted and garbage collected.
test.py
import example
import numpy as np
array = np.zeros((3, 2, 4, 4), 'f4')
example.do_math(array, 3, 2)
print(array[0, 0])
example.cpp
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <Eigen/Dense>
Eigen... |
63,160,181 | 63,160,209 | Is it legal to call virtual functions without a base pointer | This code works but I can't tell if it's legal.
I'm instantiating the most derived class Three and then calling its function run() which happens to be implemented in the base class One. That function then calls its own function fn1(), and then the two virtual functions fn2() and fn3().
I seem to be calling virtual fun... | Since fn1 is a non-static member function, fn1() implicitly means this->fn1(). Same goes for fn2() and fn3().
|
63,160,589 | 63,160,655 | How to add unlimited count of records to .txt file in C++ | I'm new to coding and I'm creating "Phone book" program. I want to add records to .txt file and for now everything is fine. When I want to add another record to file, it deletes the previous one and save only the last one entered. I want to store all records but have no idea how to do that.
Here is the peace of my code... | You are rewriting the output file every time you call addRecord. Instead, you should append to the file, like this:
// Open file to write
std::ofstream out_file(filename, std::ofstream::app | std::ofstream::out);
|
63,160,628 | 63,160,954 | How to declare operator++(int) in an abstract class? | I have an abstract class that is basically meant to serve as an "iterator interface". That is, it is an abstract iterator that a few concrete classes will later implement. To make the abstract class an iterator, I need to overload T operator++(int), where T is the class for which the operator is overloaded.
class Abstr... | Abstract classes with virtual members are usually accessed through base pointers, so you teh caller doesn't know the derived type, but the return value from operator++(int) must be known at compile time by the caller, so there's no way to do this directly. I would simply not provide this method, and have your class be ... |
63,160,647 | 63,160,956 | Using explicit casting to solve invalid conversion from ‘int’ to ‘AVRounding’ | I'm trying to follow the "learn ffmpeg the hard way" guide on github (https://github.com/leandromoreira/ffmpeg-libav-tutorial#chapter-2---remuxing) and when I try to run the remuxing code for myself using a C++ compiler I always get the error
invalid conversion from ‘int’ to ‘AVRounding’[-fpermissive]
The only real di... | AVRounding is indeed an enum (to be exact, an unscoped enum without a fixed underlying type):
/**
* Rounding methods.
*/
enum AVRounding {
AV_ROUND_ZERO = 0, ///< Round toward zero.
AV_ROUND_INF = 1, ///< Round away from zero.
AV_ROUND_DOWN = 2, ///< Round toward -infinity.
AV_ROUND_UP ... |
63,161,107 | 63,161,317 | Can abstract types be used as the return type of a pure virtual function? | If I understand correctly, abstract types cannot be used as the return type of a pure virtual function. However, if a trailing return type is used, then gcc (but not clang) accepts the following code:
struct S {
virtual auto f() -> S = 0;
};
demo.
Is this a gcc bug, or does the language not require a diagnostic t... | According to C++17 [class.abstract]/3, an abstract type cannot be used as the return type of any function:
An abstract class shall not be used as a parameter type, as a function return type, or as the type of an explicit conversion. Pointers and references to an abstract class can be declared. [ Example:
shape x; ... |
63,161,210 | 63,161,401 | Does conditional operator in cpp evaluate both operands? | https://leetcode.com/problems/decode-ways/
my solution:
class Solution {
public:
int numDecodings(string s) {
vector<int> dp(s.size(),0);
for(int i=0;i<s.size();i++)
{
int x =0;
if(s[i]-'0'>0 && s[i]-'0'<=9)
{
x = (i>0)? dp[i-1]:1;... | This line:
x = x + (i>=2) ? dp[i-2] : 1;
is likely not doing what you intend. The ternary ?: has lower precedence than +, so the statement actually becomes:
x = (x + (i>=2)) ? dp[i-2] : 1;
which means you are checking the trueness of x + (i>=2) instead of just i>=2. This is why dp[i-2] can be evaluated even when i < ... |
63,161,380 | 63,161,490 | Instantiating an array in a class and then creating an object of that class with the values for that array | So I've been trying to get a hold of the C++ syntax coming from python and I decided to do that by replicating a little library I wrote for handling exponentials in python. But I've been running into this oddity that I just don't really understand. Here's the 'simplified' code.
using namespace std;
int exponential_inpu... | Your initialize() method is implemented backwards.
It is trying to assign the member list[] array to the input parameter list_, which "works" only because int list_[] is the same as int *list_ in a function parameter, and an array decays to a pointer to its 1st element. But the code is not actually copying any values f... |
63,161,442 | 63,161,723 | Why am I getting a re-definition error in C++? | I wrote a Fraction class to do some work with Fraction objects and overloading and such and I need to separate the implementation from the definitions of the methods but I get a redefinition error when it comes to the constructors of the class Fraction.
Code snippet from Fraction.h
class Fraction
{
private:
int calc... | There are a few mistakes in the code you posted.
First, the copy constructor is declared twice in the header file. Both these declarations are the same because their parameters are of the same type.
Fraction(const Fraction& fraction);
Fraction(const Fraction& orig);
Secondly, the constructors are defined twice: once i... |
63,161,939 | 63,163,521 | Performance of multithreaded TCP networking | I'm working on a project using the TCP protocol that may have to work with many 100s or more connections at once.
As such, I am uncertain as to what method I should collect and send this data.
I was wondering whether the principal of more threads = more performance applied here.
My reason for doubt is because all data ... | ASIO is a wrapper around epoll/IOCP, and as such is optimized for high-performance non-blocking I/O. It's possible to achieve hundreds of thousands of simultaneous connections with this setup on a single thread. Indeed, the old-fashioned "a thread per client" setup could never reach this level is performance due to the... |
63,162,320 | 63,167,522 | Can I use one DLL process per executable | I am using DLL to enable modding in my game. In Visual Studio linker I link DLL's .lib with executable. Everything works fine but problem comes with adding multiplayer. Since it is DLL it is just one process for whole Windows, if I'm not wrong. But I need "client.exe" and "server.exe" to run without sharing same DLL. I... | DLL is a binary file which is composed of several sections. These sections can be divided into two types. One is not related to absolute address addressing, so it can be shared by multiple processes; the other is related to absolute address addressing, and each process must have its own copy for exclusive use.
The two ... |
63,162,372 | 63,162,393 | Only getting reoccuring singular response with C++ grading program | Hello I am having a very simple issue with a program ive written for an exercise from a C++ tutorial site. The exercise asks to write a program where you enter a number then it spits out your grade i.e. 0-59 is an F, 60-69 is a D etc...
#include <iostream>
using namespace std;
int main (){
unsigned int x;
cout ... | This condition:
if (0 <= x <= 59)
is not correct. It evaluates to:
if ((0 <= x) <= 59)
which is always true. Since x is unsigned and cannot be negative x <= 0 will always be true. Even if it were signed, the result would be either 0 <= 59 or 1 <= 59, both of which are true.
Instead, you need to do:
if (0 <= x && x <=... |
63,162,419 | 63,162,641 | Cannot cast struct pointer to PUCHAR | I'm testing a code (based in this reference) and i'm receiving a error that says:
'type cast': cannot convert from 'SYSTEM_SERVICE_TABLE' to 'PUCHAR'
How can solve it?
Edition:
The goal is try find Shadow SSDT table address on Windows 10 32bit.
#include <ntddk.h>
#define NTOSAPI __declspec(dllimport)
typedef struct... | Your title says "Cannot cast struct pointer to PUCHAR", but the code is not trying to cast a pointer, it is trying to cast the struct itself, which is why the compiler complains. You need to get the address of the struct and cast that instead, ie:
(PUCHAR)&KeServiceDescriptorTable
|
63,163,371 | 63,163,434 | standard string rfind not finding period | I am trying to extract the name of file, without the extension or qualified path e.g. extract file from /path/to/file.txt
I have the following:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string temp = "dir/filename.txt";
auto bpos = temp.rfind('/')+1, epos = temp.rfind('.')-1;
... | The second argument to std::string::substr is a count of characters, not a position.
Instead, you need something like:
temp.substr(bpos, epos - bpos + 1)
which computes the count of characters given the 2 positions.
Here's a demo.
|
63,163,471 | 63,163,589 | static and shared library and their cross linking | After reading a lot of threads, I am still confused regarding shared and static library and the way how they can be cross linked.
So my understanding is that when I have an executable that links to a static lib, the executable copies full contents of the functions/resources it needs into itself, so when it runs, it no ... |
when I have an executable that links to a static lib, the executable copies full contents of the functions/resources it needs into itself, so when it runs, it no longer needs the static lib
Correct.
If the executable links to a shared lib, then it only create place holder for all the contents it needs, so when it ru... |
63,163,562 | 63,163,990 | How can I program the function "go back" as a Menu Bar option of a MainWindow in QT? | I am working in a Program in QT where I have a LOGIN Dialog, if the person is logged successfully then the program shows a MainWindow object. There's a Menu Bar in that object. One of the options of the Menu Bar is LOGOUT, then what can I do to make the MainWindow object close or hide and the LOGIN Dialog show again?
H... | Here you would need a finite state machine...
Depending on which state your application is in and which functions are called will determine the behavior of the overall system. You will want to have your own functions to show a login window, to show the main window, to log in, to log out, etc... then you need to build y... |
63,163,672 | 63,163,846 | struct int data type not working with relational operaters | #include <iostream>
#include <fstream>
using namespace std;
struct studentInfo {
string studentFname, studentLname;
int testScore;
char grade;
}student[20];
void inputs(studentInfo(&student)[20]) {
ifstream openFile;
openFile.open("Students.txt");
... | If student[i] is 87, it will fulfill the second conditional and get a grade of 'B', but then it will also fail the fourth conditional and go into else, getting a grade of 'F' which overwrites the 'B'.
Only your fourth if is associated with the else. The above three are independent so the checks will occur unnecessarily... |
63,163,730 | 63,164,503 | LibCurl & Sql Commands | i'm a beginner in c++, and i have 2 small problem.
1 - I want to get the public ip address of the user. To do this I use curl like this :
CURL* curl;
CURLcode verif;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "https://ifconfig.me/?action=render");
verif = curl_easy_perform(curl);
... | If you are only interested in the IP address and nothing else, query https://ifconfig.me/ip instead of https://ifconfig.me/?action=render. And then use a CURLOPT_WRITEFUNCTION callback to save that output to a variable, such as a std::string, eg:
size_t write_str(char *ptr, size_t size, size_t nmemb, void *userdata);
{... |
63,163,844 | 63,164,193 | Array of Structs with an enum member causes error when giving the array a NULL termination, but no error when not doing so | I've tried searching for this, but I've not found what causes this strange behavior, there must be something I'm missing but I can't tell what it is:
The problem is the following i have the following struct:
struct s_log_message{
lll level;
const unsigned int i;
const char *msg;
}typedef log_message;
and t... | NULL is a null pointer constant. It's intended to set pointers to a null, not-pointing-to-anything, value.
logging_messages doesn't hold pointers though. It's an array of log_message objects. It doesn't make any sense to initialize a log_message to NULL.
If you want to add an "empty" object to serve as a terminator ... |
63,164,340 | 63,169,230 | Why the linker is looking for non-needed libs | I have two C++ modules: A and B, where B links to a set of static libs lib*.a (I use * here to mean a set of lib files) and A links to B.
I have CMakeLists.txt for B:
add_library(B STATIC B.cpp)
target_include_directories(B PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} "/path/to/headers/directory/for/lib*.a")
link_directories("Pa... | Your initial setup was already not working, but you did not see the error until switching to a shared library.
The reason for this is that all your target_link_libraries dependencies on A and B were not actually processed at all so long as both were static libraries. This has to do with what a static library is: Just a... |
63,164,506 | 63,164,570 | Which "math.h" definitions to use to work out maths equations | So I want to work out eqations for things such as the circumfrance of a circle that use things such as pi/π. Looked around and worked out that I need to use
#define _USE_MATH_DEFINES
#include "math.h"
and
M_2_PI //presumably
But I'm having issues figuring out how to piece this together since the π doesn't exis... |
If my radius input is r and I try to use something like x = M_2_PI * r; I'll get close results, but close isn't enough in maths.
Arithmetic operations on intrinsic number types in pretty-much every non-mathematics programming language will always give you only approximate results - because that's how integer-types an... |
63,164,558 | 63,183,079 | How do I make my executable files smaller? | I use visual studio 2019, and one thing I've noticed was that my output files are very large. I'm using release, and have set optimization to favor small code. I've also disabled generating a manifest file and debug info. However, even after these changes, the following code's executable file was 394 KB.
#include <Wind... | The whole time I was editing the settings, I was editing the settings for Release, when my active configuration was still Debug. I've accidentally discovered this when I found that std::filesystem didn't work on the other project, even though the standard was set to C++17. Here is an image of what I forgot to have done... |
63,164,974 | 63,165,524 | regex c++- how to save multiple punctuation characters at the end of a string? | If I have a word like "blue..." or "sky!!" or "r;e;d"
I want to save the punctuation characters at the end of each word. So if I inputted blue... into a function, it would return ... If I inputted sky!! into the same function, it would return !! Nothing should be returned if I input r;e;d because the punctuation char... | Your current regex only supports has only punctuation.
Your regex needs to be able to satisfy: no ending punctuation, has tail end punctuation, has only punctuation.
The logic would probably be easier not to use a regex at all, but rather check from the end of the string for punctuation characters and return the subst... |
63,165,020 | 63,165,666 | Check all files sizes in a path (C++) | I'm trying to loop so that my program can get the weight of all files in a folder, and if the weight of any of these is equal to X, it will do an action, I need to know how I can loop like this, and i have a func to know whats the file size
std::ifstream::pos_type filesize(const char* filename)
{
std::ifstream in(f... | Here's a short example program that demonstrates how to use C++17's <filesystem> library to iterate over a directory. If your compiler is fairly up-to-date, it should support C++17 without issue.
#include <filesystem>
#include <iostream>
int main() {
namespace fs = std::filesystem;
fs::path pwd(""); // Current d... |
63,165,315 | 63,184,300 | Is it a bug in clang that defines a member of a namespace without using nested-name-specifier | namespace A{
namespace B{
template<typename T>
struct Test{
};
}
using namespace B;
template<>
struct Test<int>{}; //#1
}
int main(){
}
Consider the above code, GCC complains such code is ill-formed and Clang consider such code is well-formed. The outcome is here. At #1, ... | You are correct that the existing wording is more than a little unclear. I won’t try to fathom its meaning as written, if it has one, further than you already have; I consider it all bad enough to need a complete rewrite.
The intent, however, is that this code is well-formed (as Clang says); because the explicit speci... |
63,165,937 | 63,181,960 | how to save the conditional statement of an if command as a string? | I have a numerical algorithm. I create a set of x, and y coordinates for points in R^2. Then, I use a rule to see which points are suitable for my purpose, a simple if statement like below:
int N = 0;
for (int i1 = -xN; i1 < xN + 1; i1++)
{
for (int i2 = -yN; i2 < yN + 1; i2++)
{
double x = dist(0) * i1... | Looks like you need Stringification. You can read more about it here:
https://gcc.gnu.org/onlinedocs/gcc-4.8.5/cpp/Stringification.html
Stringification of a macro value
So, you can define macros and pass to it your condition. Inside macros you can put your computation code, use passed condition and also stringify you... |
63,166,031 | 63,167,375 | How to debug using Visual Studio on a remote Linux server using "double" ssh? | I am trying to connect to a Linux server for c++ development through Visual Studio for debugging purposes. The server is a computing cluster and works in the following way:
You have a ssh portal let's say login@website.com where I use my username and password to log in.
But then to actually run an application I need t... | One way would be to setup a SSH tunnel so that visual studio can connect directly to your target machine.
For example if you are using Putty as your SSH client go to "Connection", "SSH", "Tunnels", set the "Source Port" to something like 8000 and the "Destination" to gpu-server:22 select the type as "Local". Once you h... |
63,166,194 | 63,166,248 | implicitly convert string to string_view | void Foo1(string_view view) {
...
}
string str = "one two three";
Foo1("one two three"); // Implicitly convert char* to string_view
Foo1(str);
I wonder which constructor converts char* to string_view implicitly and which one converts the string to string_view implicitly?
I know constructor (4) convert const cha... | std::string_view has a non-explicit converting constructor taking const char*, which supports implicit conversion from const char* to std::string_view.
constexpr basic_string_view(const CharT* s);
When you say:
but what I passed is char*.
You're actually passing a string literal (i.e. "one two three"), whose type i... |
63,166,220 | 63,166,418 | Argument type "WCHAR *" is incompatible with parameter of type "const char *" | Found this useful code below, here in forum but it raised an error at this line
if (stricmp(entry.szExeFile, "target.exe") == 0)
says
Argument type "WCHAR *" is incompatible with parameter of type "const char *".
I'm using Visual Studio 2019.
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
void EnableD... | You are compiling your project with its Character Set option set to Unicode, so Process32First() and Process32Next() map to their Unicode versions, thus entry.szExeFile is a WCHAR[] array.
But stricmp() takes char input instead, which is why the code fails to compile.
You need to use the Unicode version of stricmp inst... |
63,166,279 | 63,166,328 | Passing data from constructor to member function | I am trying to write a class that do matrix multiplication. The
class matrix declared like below:
class matrix
{
public:
vector<vector<int> > M;
matrix();
matrix(int m, int n);
matrix(vector<vector<int> > &m);
matrix Mul(matrix m1);
void Inverse();
bool SquareMatrix();
void GetDet();
... |
I initialize and enter the elements of the matrix M in this
constructor!
No! You are working with a local M, not with the member M.
In the constructor
matrix::matrix(int m, int n)
{
vector<vector<int> > M(m, vector<int>(n, 0)); // local to the constructor only!
// .........
}
the M is local to the scope of ... |
63,166,383 | 63,166,532 | Tips for optimizing identification of `k` consecutive equal characters | I am trying to solve a question:
An operation consists of selecting k consecutive equal characters and removing them. This operation is to be performed as long as possible. Return the final word after all the operations have been performed. For e.g., for abbcccb and k=3, the output should be a.
The code that I cou... | This is a standard problem that can be solved using stack in O(n) time. Full explanation is already given on this site. Please refer this Reduce the string by removing K consecutive identical characters
|
63,166,607 | 63,166,749 | What do you mean by drawing an image in Qt/QML? | https://doc.qt.io/archives/qt-5.11/qpainter.html#drawImage-5
void QPainter::drawImage(const QRect &rectangle, const QImage &image)
Draws the given image into the given rectangle.
They have used the word draw for a reason. I believe if I have an image I can myself put it in a rectangle. I don't need a specialized func... | Short answer: You are confusing concepts: QImage is not the same as QML Image item, and similar for QRect and Rectangle.
Long answer:
QImage is a class that allows to represent an image, in simple words it is a container of the bytes that represent the image and how those bytes are related. Instead Image is an Item tha... |
63,166,624 | 63,166,968 | how does __declspec(dllimport) actually work? | I am trying to understand how dynamic linking works and I understand most of it but now how does the compiler or the linker know which dll exactly I am importing from?
For example I have test_program.dll that exports a function called test(); and I used __declspec(dllimport) in my program to import that function there ... | When you use test() in your code the resulting object file is marked as requiring the symbol for test.
You then supply the .lib file for your dll to the linker, the lib contains the symbol for test and contains the required code for loading your dll which includes the name of the dll.
You could supply a different .lib ... |
63,167,628 | 63,168,168 | Object of a class corrupted when calling a member function of the class | A great deal of unexpected numbers outputted on my console window when I compiled and ran the program.
The class "matrix" is declared as below:
class matrix
{
public:
vector<vector<int> > M;
matrix();
matrix(int m, int n);
matrix(vector<vector<int> > &m);
matrix Mul(matrix m1);
void Inverse... | You forgot to add a return statement, which is trivial to fix. However, your code is not written in a good OO manner, so here come few suggestions for the improvement:
don't pass matrix m1 by value, because you are paying an expensive copy each time you invoke this function; use const matrix& m1 instead
in the body o... |
63,168,256 | 63,169,714 | How can I store an array of char in an array in c++ | Hi so I'm writing code in C++ that asks the user to submit a message like "the house is green" and then store it an array that stores messages so this is what i have so far
#include <iostream>
using namespace std;
char message[100];//limits the message to 99 characters.
char arrayOfMessages [5];
cout<<"Please ente... | So I found the simplest answer was to simply change the
char arrayOfMessages [5];
to
string arrayOfMessages [5];
and then just do a simple
arrayOfMessages [0]=message;
And that worked, so thanks for everyone's help and suggestions!!
|
63,168,404 | 63,168,805 | Create repeated declaration | I was wondering if anyone knows a way of creating repetitive type declarations, and since this might be confusing an example will be helpful:
For our project we need to have function and type declarations like:
using FunType = std::function<void(double,double,double,double,double,double,double,double)>;
using D... | This is easy with Boost.Mp11:
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/list.hpp>
namespace mp11 = boost::mp11;
template<class... Args>
using make_fn = std::function<void(Args...)>;
using TypeList = mp11::mp_repeat_c<mp11::mp_list<double>, 8>;
using FunType = mp11::mp_apply<make_fn, TypeList>;
usi... |
63,168,479 | 63,259,801 | How to access std::vector<enum> in qml? | The TestMethod of c++ is called in qml.
c++
class Test : public QObject {
Q_OBJECT
public:
enum TestEnum
{
RED = 0,
BLACK = 0x1,
YELLOW = 0x2,
PINK = 0x4,
};
Q_ENUM(TestEnum)
Q_INVOKABLE std::vector<TestEnum> testMethod();
};
Q_DECLARE_METATYPE(std::vector<Test::... | I have solved with QVariantList
|
63,168,758 | 63,219,799 | FLTK - FL_Tooltip - Modify tooltip size | I am using FLTK 1.3.5 (on Mac, Catalina 10.15.5, clang version 11.0.3) and I would like to have widgets with tooltips for whom I want to decide margins and other options. In particular, I want to work on margin_width and on wrap_width, so I tried the following
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/F... | I don't know about the Mac but to get this to work on MS compilers
#if FLTK_ABI_VERSION >= 10301
should be changed to
#if (FLTK_ABI_VERSION >= 10301)
Try that on the Mac. If it works, please report the bug and fix to https://www.fltk.org/applications/str.php and remember to specify Mac and Windows.
I've looked throu... |
63,168,796 | 63,175,196 | Translate UniGui Delphi code to C++Builder | How can I translate this code into C++? UniGui component.
var
FrmList : TList;
I : Integer;
Frm : TUniBaseForm;
begin
FrmList := UniSession.FormsList;
UniListBox1.Clear;
for I := 0 to FrmList.Count - 1 do
begin
Frm := FrmList[I];
UniListBox1.Items.Add(Frm.Name + ' ' + Frm.ClassName );
end;
I... | Delphi allows an untyped pointer (void* in C++) to be assigned to another typed pointer without a cast. C++ does not, you need an explicit cast.
You were on the right track with your 2nd attempt, but you need to use either static_cast or reinterpret_cast, instead of dynamic_cast, eg:
TUniBaseForm *Frm = static_cast<TUn... |
63,168,799 | 63,169,143 | Simple semi-compile-time 'event-bus' in c++ | I am trying to hide serious design flaws in my application behind event bus :)
I created template class with static event handlers holder like this:
template<typename ET>
class EventHandler;
template<typename ET>
class EventBus {
public:
static std::vector<EventHandler<ET>*> handlers;
};
template<typename ET>
std... | There won't be any issues resolving the handle_event overload with the given publish() function, because only one handle_event member function is actually visible in this function: the type being invoked on is EventHandler<ET>, which only knows about handle_event(ET&) (whatever ET happens to be).
For example, if ET is ... |
63,169,400 | 63,172,481 | How to store the readed image (libpng) in a std::vector<std::vector<uint8_t>>? | I want to read a png image using the libpng and store the pixel values into a std::vectorstd::vector<uint8_t>.
But the compilator throw an error.
My C++ code is :
char fileName[] = "test.png";
// We try to open the image file
FILE * inputImageFile;
if((inputImageFile = fopen(fileName, "rb")) == NULL) {
throw std::ru... | You need to do more to pixels to get something compatible with png_read_image, and you need to fill pixels before using it.
#include <algorithm>
size_t row_bytes = png_get_rowbytes(png, imageInfo);
std::vector<std::vector<png_byte>> pixels (height, std::vector<png_byte>(row_bytes));
std::vector<png_byte *> ppixels(hei... |
63,169,505 | 63,169,863 | Is the if-statement with a const condition optimized inside a for loop (c++) | Consider the following code:
void func(int a, size_t n)
{
const bool cond = (a==2);
if (cond){
for (size_t i=0; i<n; i++){
// do something small 1
// continue by doing something else.
}
} else {
for (size_t i=0; i<n; i++){
// do something small 2
// continue by doing something ... | Details do matter and you included too little. As you are asking for compiler optimizations you need to know that the compiler will optimize according to the as-if-rule. Sloppy speaking, the compiler can do any optimization as long as they do not change the observable behavior (there are few exceptions). Both your func... |
63,169,538 | 63,173,476 | OpenMP: how to realize thread local object in task? | What I am trying to do is to iterate over all elements of a container in parallel comparable to #pragma omp for; however the container in question does not offer a random access iterator. I therefore use a workaround via tasks described in this stackoverflow answer:
for (std::map<A,B>::iterator it = my_map.begin();
... | According to your update, I would suggest to use a global/static thread-private pointer and then initialize it by each thread within your parallel section.
static Object* scratch_ptr;
#pragma omp threadprivate(scratch_ptr);
void method(int argument_for_scratch_object)
{
#pragma omp parallel
{
scratch_ptr = new O... |
63,169,578 | 63,169,815 | Calling overridden method of helper class in C++ | I come from a Python background, and currently I'm learning OOP in C++.
I'm having problems figuring out how to get the code to call the correct method in a helper class HelperBase that is inherited to HelperChild.
#include <iostream>
class HelperBase {
public:
HelperBase() {}
virtual void something() {
... |
Copy constructor will NOT copy derived object, it will get sliced and create a base object.
To elaborate, you may consider copy constructor as "copy by value", every value of derived object would be copied to create a base object. Since your Helper classes have no class members, it copied nothing.
Also function is no... |
63,169,853 | 63,174,930 | C++11 GCC 4 Fast Optimization don't store implementation class from abstract class in the stack | So guys, I have an abstract class, other class that stores an implementation from this class in the stack (I don't want heap allocations and I don't know other way to do it without making the caller explicitly declares the implementation) and another that stores a reference of this interface class. But, it seems that G... | As one of the comments said there is something weird going on with storing TCustom in the unrelated type RCustom. The implicit constructor RCustom(TCustom) threw me off.
The issue is quite subtle. If something works with -O0 but not with -Ofast (or -O2/-O3), most of the time something funny is happening with the memory... |
63,170,278 | 63,170,379 | static binding with new operator c++ | i want to be sure if i understand that corectly. If i have something like that:
Base* wsk = new Derived
and if i've done that with static-binding than wsk is type of Base, but Derived type object is still created? And wsk is pointing to that Derived type object, but it cannot use methods from derived class, because ws... | wsk is of type Base *, not Base nor Derived.
It was initialised with a value that was (implicitly) converted from type Derived *. It points to a Base object, which so happens to reside within a Derived object.
That means that static_cast<Derived *>(wsk) will give you a value that points to a Derived.
It may be that the... |
63,170,526 | 63,181,817 | How to add prebuilt/precompiled *.o object files to executable in GN | I have a prebuild object done by 3rd party library, I need to add it to the final executable build by GN.
Is any way to add prebuild object that source is missing directly to GN executable target?
I see GN has precompioed_source, but seems to be linked to precompiled_header and not what I'm looking for.
The GN toolchai... | Ok, seems it is enough just to add object file to sources.
GN does a hard match by file extensions with specific tool, so if object file has a different extension (e.g. not libfoo.o for POSIX), then best is to use copy action to correct the object extension.
The answer was provided by gn-dev in https://groups.google.co... |
63,170,771 | 63,193,287 | InternetOpenUrl with self signed certificate | The following code is used to download files, but not working if the server has a self signed certificate:
DWORD errCode = 0;
HINTERNET intOpenHandle = InternetOpen("Snippet", LOCAL_INTERNET_ACCESS, NULL, 0, 0);
errCode = GetLastError();
if (intOpenHandle != NULL && errCode == ERROR_SUCCESS)
{
HINTERNET urlOpenHand... | It seems it is not possible with InternetOpenUrl() and InternetSetOptions(): The latter requires an open connection handle, not the session handle the former provides.
Therefore i had to use a bit longer version:
DWORD errCode = 0;
HINTERNET intOpenHandle = InternetOpen("Snippet", LOCAL_INTERNET_ACCESS, NULL, 0, 0);
if... |
63,170,801 | 63,170,936 | How can I copy the contents of string to an array of char c++? | So I have this issue
//This holds 5 messages submitted prev by the user, temporarily stored
string arrayOfMessages[5];
lets say
arrayOfMessages[0]="This is my message"//The message in the first position.
I need to copy arrayOfMessages[0] to an array of char like this one;
char message [20];
I tried using strcpy(mess... | There are many ways of doing it
By using the c_str() function of the string class
string message = "This is my message";
const char *arr;
arr = message.c_str();
By copying all the characters from the string to the char array
string message = "This is my message";
char arr[200];
for(int i = 0; i < 200 && message[i] != ... |
63,170,836 | 63,171,575 | std::byte's to_integer<uint8_t> interprets to char instead of integer | I was playing around with C++17 std::byte, and I came across some weird behaviour.
I don't know if it is intended or not, or if I am doing something wrong.
std::byte test_byte{80};
std::cout << "Test: " << std::to_integer<uint8_t>(test_byte) << " vs " << std::to_integer<uint16_t>(test_byte) << "\n";
This will print ou... |
My question is if this is the intended
Sort of.
if it's a bug
No. It's just a slight inconvenience in the API.
or maybe even OS/Compiler specific?
No.
This has nothing to do with std::to_integer. The issue is that the integer type that is 8 bits wide on your system happens to be (unsigned) char. And this integer ... |
63,171,287 | 63,171,654 | Recursion in includes (file 1 includes file 2 that includes file1) | I have been looking around but I have not found any question that really helps me to solve this issue. I am not very experienced, so maybe this problem is trivial and it is a question of my lack of knowledge.
I am trying to solve an issue. Our system has a Logger that takes different logs and puts them into a SharedMem... |
Try to move includes from header files to source (*.cpp) files
Use forward declarations: What are forward declarations in C++?
Change interfaces to work with pointers or references to needed types instead of using actual types, to make possible using forward declaration (if needed)
|
63,171,345 | 64,256,102 | How to solve eclipse cross-compilation c/c++ error. Symbol could not be resolved issue | I'm trying to make changes and compile open source 3d printers firmware in eclipse. Added all the project related to firmware but it showing symbol could not be resolved error. The cause of error is IDE cannot find the symbols. How can I solve this. It's compiling properly and also working on board.
| Found the solution in indexer of the eclipse used active configuration settings and it solved all the Indexer error. Thanks for the help guys.
|
63,171,944 | 63,172,056 | Error: no matching function for call to 'std::vector<Movie>::erase(size_t&)' | I am currently learning C++ / making a simple movie database. I use classes and I have a method Delete Movie. Unfortunately, when I try to delete object Movie from a vector database, there's this error.
for (size_t num {}; num < database.size(); ++num)
if ((database.at(num)).getname() == name) {
... | erase accepts iterator as said pptaszni
Replace your for code by this:
auto it = std::remove_if(database.begin(), database.end(), [&name](const Movie& item) -> bool { return item.getname() == name; });
database.erase(it, database.end());
Or change just 1 line (database.erase(num)) like this:
database.erase(database.be... |
63,172,012 | 63,188,566 | What is triggering "ASSERT failure in QCoreApplication::sendEvent" here? | I'm getting this error: ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 0x0x20e51b65eb0. Receiver 'gw2g' (of type 'gw2g') was created in thread 0x0x20e4fd0c930"
DEBUG:
MAIN_thread started: QThread(0x20e4fd0c930)
DUMMY_LOOP started: QThread(0x20... | I figured it out.
The error message was very misleading, since the problem was the QEventLoop in dummy.
When main window(gw2g) QPushButton is clicked it quits this eventloop, so why is the receiver (gw2g)?
So, I just got rid of
wait_xcon.exec();
and replaced it with a simple
while(!quitloop){}
clicking the button n... |
63,172,051 | 63,172,083 | Is there a standard way to iterate over a range of iterators with a range based for loop without using the iterator syntax | I have a range = pair<iterator, iterator>, which I receive from boost::multi_index_container::equal_range I would like to iterate over the range with a range based for loop
for( auto element : range ) {
//do
}
I can solve this problem by implementing a class which receives the iterators as an input like this:
template... | Okay found it 30 seconds after posting the question...
boost::make_iterator_range(begin, end) seems the way to go
|
63,172,280 | 63,229,807 | Cant debug `iostream` related code when using MSVC toolchain in clion | I am new to c++ development, and I find that I can't place breakpoints in iostream related class and if I force step into call of iostream functions like basic_streambuf::xsgetn I will get a disassembly view which I have absolutely no interest to read.
I am using clion with Visual Studio Toolchain. Is there a way to d... | After a few days of digging. It turns out that adding the following to CMakeLists.txt fixed the problem
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "MSVC")
message(STATUS " MSVC DEBUG RUNTIME")
# enable debugging of runtime library
set_property(TARGET archive_patcher_cpp PROPERTY
MSVC_RUNTIME_LIBRARY ... |
63,172,736 | 63,187,166 | Why design a language with unique anonymous types? | This is something that has always been bugging me as a feature of C++ lambda expressions: The type of a C++ lambda expression is unique and anonymous, I simply cannot write it down. Even if I create two lambdas that are syntactically exactly the same, the resulting types are defined to be distinct. The consequence is, ... | Many standards (especially C++) take the approach of minimizing how much they demand from compilers. Frankly, they demand enough already! If they don't have to specify something to make it work, they have a tendency to leave it implementation defined.
Were lambdas to not be anonymous, we would have to define them. T... |
63,172,901 | 63,173,017 | What sort of tools should I use in C++ to create a simple RISC-V disassembler? | I am looking to create a simple RISC-V disassembler in C++.
The goal is to be able to take a .bin file, composed of separate bytes in hexadecimal, and parse those bytes into readable, formatted RISC-V instructions.
I suppose it could be done using just switch statements, but what is a more robust way of approaching thi... | Assuming that the instructions are always of the same size, i.e. take the same number of bytes, including addressmode selections and parameters, then lookup tables are probably a helpful tool.
In case that instructions are of varying size (which I would consider untypical for a RISC concept) the lookup tables probably ... |
63,173,616 | 63,174,546 | How can I "unclick" a button in C++ Builder 6 | I have a button in C++ Builder 6 that I need to activate (and stay activated). But when I don't need it anymore, I want to click again on that button, and it goes back to the UP state.
Thank you for your help.
| if you're working with VCL controls I think you can use a TSpeedButton and implement the toggle logic with its TSpeedButton.Down property. It stays pressed while Down is true and unpressed when Down is false. Check this
there are these properties for this:
TSpeedButton::Down indicates clicked button (you can also prog... |
63,174,232 | 63,196,461 | Find geometry's interior point closest to its centroid | I'm extracting the names of bodies of water from the OpenStreetMap database and getting their label long/lat based on the centroid of their geometry using the Geos library:
geos::geom::Geometry* geometry = BuildInternalGeometry();
geos::geom::Coordinate centroidCoord;
bool result = geometry->getCentroid(centroidCoord)... | While Jeffrey's answer didn't quite answer the question (the Geos library does not appear to support polygon sections), it did give me an idea, well... 2 ideas for how to locate an interior point close to a polygon's centroid.
The first idea (the easier, less accurate one) involves iterating over the geometry's vertice... |
63,174,272 | 63,187,963 | Optimize eigen recomposition (Matrix - Diagonal Matrix - Matrix) product C++ with BLAS and OpenMP | I wrote a C++ code to solve a linear system A.x = b where A is a symmetric matrix by first diagonalizing the matrix A = V.D.V^T with LAPACK(E) (because I need the eigenvalues later) and then solving x = A^-1.b = V^T.D^-1.V.b where of course V is orthogonal.
Now I would like to optimize this last operation as much as po... | This code is currently highly memory-bound. Thus the resulting program will probably poorly scale (as long as compiler optimization are enabled). Indeed, on most common systems (eg. 1 socket non-NUMA processor) the RAM throughput is a shared resource between cores and also a scarce one. Moreover, the memory access patt... |
63,174,436 | 63,174,490 | The value of using string.find() is changed in while loop condition | int main()
{
int pos;
string str = "asd\t123";
pos = str.find('\t');
cout << pos <<endl;
while (pos =str.find('\t') != string::npos) {
cout << pos <<endl;
break;
}
cout << pos <<endl;
return 0;
}
The output is 3 and 1. why would that happen if I put pos = str.find() in the while ... | Try this:
while ( (pos = str.find('\t')) != string::npos)
{
...
}
The value is changed because while (pos = str.find('\t') != string::npos) is being interpreted as:
while (pos = (str.find('\t') != string::npos))
You are assigning the result of (str.find('\t') != string::npos), which is true to pos. Since pos is an in... |
63,174,520 | 63,175,082 | How to get gRPC / protobuf version programmatically? | Is there an API to know gRPC/protobuf version or the git commit hash? We would like to include these in --version information of our C++ application.
The files gRPC-Core.podspec, gRPC-C++.podspec, Protobuf-C++.podspecetc. do have this information; wonder if the same can be extracted without having to parse these files.... | gRPC exposes the version in its API:
const GRPCAPI char* grpc_version_string ( void )
For the C++ implementation there appears to be the following method in the <grpcpp/grpcpp.h> header:
std::string grpc::Version()
For protobuf the macro GOOGLE_PROTOBUF_VERSION is the integer value of its version & can be converted to ... |
63,175,084 | 63,175,267 | Switching between two typedef structs, depending on boolean | I have a class with different functions. This class uses two typedef structs.
typedef struct {
struct head;
struct data1;
} data_struct_1;
typedef struct {
struct head;
struct data2;
} data_struct_2;
If a bool is true the data_struct_2 should be used, otherwise data_struct_1. The boolean is passed, when t... | You have a couple of options:
If the types are conceptually the same type of thing (i.e. they have the same interface and could be substituted for one another), you can:
Create an abstract base type and use polymorphism to change which concrete type is instantiated
Change all places that use these types into template... |
63,175,571 | 63,501,011 | How to call functions from parent class in C++? | TL;DR
I have a class in which some function names conflict with the parent class's function. How to call functions from the parent class in C++?
My problem
I'm trying to make a class with stream functionality. So, I inherited my class from std::basic_iostream . But my class has many functions which conflict with the ba... | Calling functions from parent class directly is easy as the following:
std::stringstream myobj;
myobj << "Something..."
myobj.std::iostream::flush();
Above example calls flush() directly from std::iostream (which is a typedef of std::basic_iostream<char> ). It is also possible to member functions from parent class of ... |
63,175,618 | 63,176,873 | Accessing an external project with add-subdirectory results in CMake Error related to export set | I have a project A that depends on spdlog. Here is the structure:
|--- dir A
...|---src
......|---CMakeLists.txt
...|---include
...|---CMakeLists.txt
|---external/3rd_party/spdlog
I am trying to access spdlog in project A by adding a subdirectory. Here is how my A/CMakeLists.txt looks like:
cmake_minimum_required(VERS... | Meaining of the error
Since you use PUBLIC keyword when link your library (A) with spdlog_header_only, CMake expects that this linking is also needed for users of your library. So, when you create config file for your library (with install(EXPORT)), CMake adds linking with spdlog_header_only target into the config file... |
63,175,890 | 63,176,501 | Static cast from negative int to uint | I have the following check where it is possible for the condition to underflow.
uint16_t lo;
uint16_t input;
...
uint16_t newLo = std::clamp(lo-input, 0, lo);
This causes a compiler error due to the promotion of types to int when doing the calculation ("Compiler error" is caused by gcc flags: -Wall -Werror).
Is it s... | Since you are using std::clamp with argument 0 as second argument then apparently you are expecting possible negative value.
uint16_t compVal = static_cast<uint16_t>(lo-input);
uint16_t newLo = std::clamp(compVal, {}, lo);
This fixes compile error, but hides actual problem when lo < input.
Actual behavior will wrap ar... |
63,175,894 | 63,176,185 | C++ Does pointer of pointer automatically have access to new value? | I am having a hard understanding of how pointers to pointers should work, like in the following example.
let's say I have in a class in a certain file the following
typedef object* objectPtr;
and another file containing
struct RandomStruct
{
RandomStruct( objectPtr* obj = NULL ): ojbOwner( obj ) {}
objectPt... |
typedef object* objectPtr;
Avoid obfuscating pointer types like this.
NULL
NULL shouldn't be used in new C++ programs. It exists for backward compatibility. Use nullptr instead.
my logic tells me that objOwner would be updated as well
is there something I may understand wrong about pointers ?
Yes, there is s... |
63,176,146 | 63,176,363 | C4297 warning in Visual Studio while using function-try-block (function assumed not to throw an exception but does) | #include <exception>
struct FOO
{
~FOO() try
{
throw std::exception();
}
catch (...)
{
return; // Shall prevent the exception from being rethrown?
}
};
Building this code in Visual Studio triggers C4297 warning (function assumed not to throw an exception but does).
Reaching the end of a catch cla... |
Do I interpret this sentence correctly? Does return from the catch statement shall prevent the exception from being rethrown?
I believe you are. For one, it is explicitly stated that in a constructor, the handler of a function-try-block may not include a return statement.
[except.handle]
13 If a return statement app... |
63,176,370 | 63,300,265 | OMNet++ | Simulation Runtime error : Object is currently in (omnetpp::cEventHeap)simulation.scheduled-events | I'm pretty new in using OMNeT++ IDE and I would like to use some "infinite array" to store some data in my message. My code is fine without any error but when I'm launching my simulation, it just stops instantaneously. I've checked in debug mod and it does launch but when I'm supposed to use this message I got the foll... | This has nothing to do with 'infinite' arrays or whatever. The reason for the error message is that you are trying to delete a packet which is already scheduled in the message queue. It means that you created a packet (Masg_event_data) and after sending it out with a send() call, you have kept its pointer and then reus... |
63,176,408 | 63,177,419 | Is bit field a way of aligning data? | From the cppreference
#include <iostream>
struct S {
// will usually occupy 2 bytes:
// 3 bits: value of b1
// 2 bits: unused
// 6 bits: value of b2
// 2 bits: value of b3
// 3 bits: unused
unsigned char b1 : 3, : 2, b2 : 6, b3 : 2;
};
int main()
{
std::cout << sizeof(S) << '\n'; // usua... | The example you quoted is being used to explain that multiple bit-fields are usually (not necessarily) packed together. If you look at it more carefully:
// 3 bits: value of b1 - 3 bits occupied
// 2 bits: unused - 2 bits left unused
// 6 bits: value of b2 - 6 bits occupied (these 6 can'... |
63,177,323 | 63,177,787 | Updating elements in a QAbstractListModel from C++ | I have a simple QML application.
This application contains a class ObjectModel : public QAbstractListModel, which holds a ParesisObjectList* mList containing the data displayed on the GUI.
QML snippet:
ListView {
width: parent.width
height: parent.height
model: ObjectModel {
list: paresisObjectLi... | QAbstractListModel gives you a helper function index() that creates a QModelIndex based on the row number. So you should be able to use this signal:
int rowThatChanged = <whatever>
emit dataChanged(index(rowThatChanged), index(rowThatChanged));
|
63,177,517 | 63,181,127 | I built a C++ program on Windows, how can I compile an executable for MacOS? | I have built a little C++ program on Windows, and I'd like to share it with some people, but they are on MacOS. What tools can I use to compile an executable (like .exe for Windows) and share the project to them? If needed, I have a MacOS VM.
| Build your sources with Xcode. Or try to run .exe with WINE (https://www.winehq.org/)
|
63,178,332 | 63,178,539 | trouble connecting signal/slot from QTreeView | I'm new to C++ and qt creator entirely. I want to click on a folder in the treeView and then in response do something with the data inside that directory. For now I'm just trying to get signals/slots connected so I'm only trying to write something inside "testLabel" when a tree item is clicked..
I've been trying for a ... | The SIGNAL() SLOT() syntax is old and uses the C++ preprocessor so often times completely invalid things will be compiling just fine. Read more about the new syntax here.
Switch to the modern syntax, which is like:
QObject::connect(ui.treeView, &QTreeView::doubleClicked,
this, &MainWindow::labelTest_se... |
63,178,823 | 63,178,957 | Initializer-list on 3 levels | How do I properly and easily initialize an instance of a class that contains a std::vector of some other class that in itself contains some data.
I understand that it is really hard to explain it in words, so I will instead write a piece of code that does not work, but it captures my intention.
#include <vector>
struc... | You need 2 pairs of additional braces for this to work:
Geometry instance
{{
{{{0,0}, {6, 0}, {3, 3}}},
{{{5,2}, {6, 6}, {7, 3}}}
}};
Here's a demo.
Explanations for all the braces:
Geometry instance
{ // for the Geometry object - instance
{ // for the vector member - triangles
{ // for the individual Tria... |
63,178,987 | 63,179,053 | Can't apply to_address of unique_ptr of array | In this MCVE:
#include <memory>
int main()
{
std::unique_ptr<char[]> myChars = std::make_unique<char[]>(20);
const char* cs = to_address (myChars);
return 0;
}
g++ can't handle applying to_address to myChars -- it complains that unique_ptr<char[]> has no member named ->. I'm using g++10, but to_ad... | std::to_address() converts a pointer-like type (like a smart pointer) to a raw pointer. By default, for a pointer-like type, std::to_address() uses the type's operator-> to obtain the raw pointer being held by the type. However, the array specialization of unique_ptr has no operator->, hence the error you are seeing.... |
63,179,535 | 63,179,697 | Why can't I use a 'str[0]' to decode an enum in C++? | I'm parsing a string coming from a 'black box' screen controller and thought I'd be able to use enum to interpret the various parameters. I'm trying to understand why my approach won't work and although I know its something to do with types and casts I can't seem to reach a conclusion. I'd like to know if its just fund... | enums are largely a compile-time feature; the fact that it's named Y isn't relevant once the code is compiled (aside from in debugging symbols). You can't convert from a character describing the name of an enum member to the member itself without manually coding a lookup table for it in some way. Even if j[0] contains ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.