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 |
|---|---|---|---|---|
67,394,404 | 67,394,519 | How am I supposed to use SFINAE overload resolution here? | I guess any use of SFINAE could be considered a hack, but here I tried for a long time and the best I could manage was to use a default void* argument in one of the overloads:
struct Dog
{
Dog() {}
void makeNull() {}
};
// If no .makeNull() function this is eliminated
template <typename T>
constexpr auto... | Before C++20 concepts, it was typical to define a struct that conditionally derived from either std::true_type or std::false_type in <type_traits>:
#include <type_traits>
template <class, class = void>
struct HasMakeNullFunction : std::false_type {};
template <class T>
struct HasMakeNullFunction<T, std::void_t<declty... |
67,394,957 | 67,400,974 | Getting error: fatal error: curl/curl.h: No such file or directory #include <curl/curl.h> | I'm trying to use cURL but every time I try to compile a project with it, I get the same error mentioned in the title. I am aware of the dozen or so post about similar issues. However, most of the solutions I've read so far either don't work or I can't seem to find an analog for me as I'm using mingw32 on a windows 10 ... | Mingw is gcc for windows. Practically everything that applies to gcc applies to mingw.
It's better to use relative paths in your Makefile and with gnu make (which is part of mingw/msys) always use '/' as path separator. If you have to use absolute path like C:\dev\projects\mylib use it this way: C:/dev/projects/mylib.
... |
67,395,093 | 67,395,345 | modified after being freed - returning a C array of `c_str` (const char*) within a struct | How do I get a c_str array from a std::vector (inside a struct) for C users to use?
Attempt:
#include <vector>
#include <algorithm>
typedef struct { size_t size; const char** arr; } CStrStrArray;
CStrStrArray f() {
const std::vector<const char*> cStrVec {"foo", "bar"};
/* pretend ^this is huge^ with size + c... | If you need to convert std::vector<std::string>> into CStrStrArray you do not need intermediate step and create additional std::vector<const char *>:
CStrStrArray f( const std::vector<std::string> &v ) {
CStrStrArray r{ v.size(),
reinterpret_cast<const char **>( malloc( sizeof( char * ) * v.size() ) };
... |
67,396,054 | 67,397,281 | parameterized constructor with dynamic array of object | In the below program i have used two classes , and i am trying to relate the with aggregation, i have declare class A as private in class B, and with the help of constructor i am initizing base address of class A object to private member of class B object that is (A object). i am trying to pass the class A values to c... | In create, you fully replace the previous B objects with brand new ones using the 2 parameters constructor... which just leaves the A object member default initialized.
What could be done to fix?
Pass the parameters of B to A ctor:
B::B (int a, string b): object(a, b)
{
bbb = a;
name = b;
}
That way you ... |
67,396,557 | 67,396,811 | Adding space after // in clang format | I have a clang-format based off of LLVM but I found it surprisingly hard to find a setting to add space after comment start. Basically, I'd like to have:
// This is a comment
instead of:
//This is a comment
Here's the .clang-format I'm using at the moment:
# Generated from CLion C/C++ Code Style settings
BasedOnStyle... | There seems to be a SpacesInLineCommentPrefix option in Clang 13, see docs. However, as far as I can see, there's no such option in older versions.
If you have access to Clang 13 on your system, this is how you'd use it:
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: 1
|
67,396,566 | 67,397,379 | QT 5.11.3 - QDomNode : can't print value of dom element | I'm trying to create a very function to read a very simple XML file and print its content on the QTCreator console.
I created the following XML file :
<SCANNERS>
<SCANNER>
<NAME>Test scanner</NAME>
<SERIAL>10102030</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 2</NAME>
<SE... | Found out what's wrong.
Actually, the actual node value seems to be one node deeper than the child itself.
The solution is simply to "dig" one layer deeper :
QDomNode n2 = e.firstChild();
std::cout << n2.nodeName().toStdString() << " " << n2.firstChild().nodeValue().toStdString() << std::endl;
n2 = n2.nextSibling();
st... |
67,396,632 | 67,400,596 | Program not building on Visual studio | The above shows the error I am getting when I build main.cpp from Microsoft Visual Studio
main.cpp file
#include <iostream>
#include "catalan.h"
using namespace std;
int main()
{
int selection;
int number;
}
return 0;
}
This is the catalan.h file :
#incl... | Don't include .cpp files like you do in #include "implementation.cpp". Include header files and compile .cpp files.
When you've removed #include "implementation.cpp you may be required to add missing #includes to the .cpp file if it currently relies on that you've done #include <iostream> for example.
Compiling:
In g++... |
67,396,646 | 67,396,833 | Removing code duplicate with if constexpr | I have some code as follows:
Matrix<T, N> res = zeros<T, N>(dims);
if constexpr (N1 == 1) {
MatrixView<U, 2> m1_view ({1, m1.dims[0]}, m1.dataView(), {m1.dims[0], 1});
if constexpr (N2 == 1) {
MatrixView<V, 2> m2_view ({m2.dims[0], 1}, m2.dataView(), {1, 1});
// duplicate... | you might do:
auto m1_view = [&](){
if constexpr (N1 == 1) {
return MatrixView<U, 2>({1, m1.dims[0]}, m1.dataView(), {m1.dims[0], 1});
} else {
return MatrixView<U, N1>(m1);
}
}(); // notice extra () to immediate call
auto m2_view = [&](){
if constexpr (N2 == 1) {
return MatrixVi... |
67,396,719 | 67,396,850 | Command terminated right after vector input | I created this program:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n;
cin>>n;
vector<int> m(n);
for(int i=0;i<n;i++){
cin>>m[i];
}
sort(m.begin(),m.end());
vector<bool> used(n,false);
for(int i=n;i>0;i--){
for(i... | You access the vectors m and used out of bounds since you start iterating with i == n (the size of the vectors). This causes your program to have undefined behavior and a crash is one possible outcome of that.
Suggested fix:
for(int i = n - 1; i >= 0; i--) { // start with n-1 and ...
for(int j = i; j >= 0; j--) { /... |
67,397,460 | 67,397,890 | Does STLR(B) provide sequential consistency on ARM64? | For stores performed on an object of an atomic data type (say, std::atomic<uint8_t>), GCC generates:
MOV instruction in case of release-store (std::memory_order_release),
XCHG instruction in case of sequential-consistent-store (std::memory_order_seq_cst).
when target architecture is x86_64. However, when it is ARM64 ... | Yup, stlr is store-release on its own, and ldar can't pass an earlier stlr (i.e. no StoreLoad reordering) - that interaction between them satisfies that part of the seq_cst requirements which acq / rel doesn't have. (ARMv8.3 ldapr is like ldar without that interaction, being only a plain acquire load, allowing more ef... |
67,397,486 | 67,397,545 | Ambiguity between function and function in namespace with same argument | Can anybody explain why there is an ambiguity between A::f(const B& b) and f(const A::B& b). I consider the code to be quite explicit about the intention.
#include <iostream>
namespace A
{
class B
{
protected:
double value_;
public:
B() : value_(15.0) {}
double getValue() const {return value_;}
}... | This is an example of argument-dependent lookup.
Even though ::main is in global namespace, A::f is callable without using the fully-qualified name, because it is looked up in the namespace A of its argument, A::B. As a result, there is an ambiguity between ::f and A::f.
To resolve the ambiguity, you would need to call... |
67,397,840 | 67,398,066 | How to declare a C++ constructor depending on user input? | I'm learning C++ and stumbled upon an issue I don't know how to solve. I have a class hierarchy of probability distributions. I'm asking the user to input the name of a probability distribution (e.g. "uniform") and its associated parameters, which I'm storing as a tuple of the form
std::tuple<std::string, double, doubl... | If you really wanted to use dynamic class hierarchies here, a simple factory function would do the trick.
#include <string_view>
#include <memory>
struct distribution {
virtual float generate() = 0;
virtual ~distribution() = default;
};
struct uniform : distribution {
uniform(float, float);
float gene... |
67,398,121 | 67,430,971 | SCONS: Run target always, not only if updated | Based on SCONS run target I created a basic SCONS script to build and then run my unit tests:
test = env.Program(
target='artifacts/unittest',
source= sources + tests
)
Alias(
'test',
test,
test[0].abspath
)
After I modified the code, this works great:
> scons test
scons: Reading SConscript files ... | Fixed it now by Creating a PseudoBuilder using AddMethod to concat a Builder and a Command:
env.AddMethod(
lambda env, target, source:
[
env.Program(
target=target,
source=source
)[0],
env.Command(
target,
so... |
67,398,436 | 67,407,033 | Proper memory freeing of vector of Base class pointers, which is a member of a derived class | Let's say I have the following classes:
Base.hpp:
class Derived;
class Base {
protected:
Derived *boss;
//other things
public:
Base(); constuctor with irrellevant parameters
virtual ~Base(); // after confirmation from the comments,
//I made the destructor virtual but I still experience crashes due ... | Remove delete this->boss; in your Base::~Base() definition. Assuming Base models employees and Derived models bosses, this is equivalent to a boss losing their job when any of their employees leave; it doesn't make sense, and if a Derived object has employees, a segmentation fault will inevitably occur upon destruction... |
67,398,750 | 67,398,957 | Passing defaulted/'optional' parameters to C++ functions by name | I am new to c++ and trying to learn how to use the optional parameters in functions.
Right now I know that you can make a function with optional parameters like this:
void X_plus_Y(int x=10, y=20) {return x + y;}
int main() {
X_plus_Y(); // returns 30
X_plus_Y(20); // set x to 20 so return 40
X_plus_Y(20, 30); ... | Named parameters are not in the language. So X_plus_Y(y=30); doesn't mean anything. The closest you can get is with the following: (works with clang 11 and GCC 10.3)
#include <iostream>
struct Args_f
{
int x = 1;
int y = 2;
};
int f(Args_f args)
{
return args.x + args.y;
}
int main()
{
... |
67,398,921 | 67,399,259 | Smallest size of bit field | I have some problems with understanding results returned by sizeof.
Let assume that I have two structs:
typedef struct{
unsigned int age : 4;
unsigned char gender : 1;
unsigned int size : 2;
} child_t;
typedef struct{
unsigned int age : 4;
unsigned char gender : 1;
unsigned int size... | In standard C++, the smallest possible size of a struct is 1 char (which is at least 8 bits). So even an extension like __attribute__((packed)) is forced to yield a struct of size 1.
Furthermore, almost everything about the layout of bit-fields is implementation-defined.
In this example it seems GCC simply picks the al... |
67,399,227 | 67,399,625 | I need some support with my piece of code (c++) | I have a school task that I need to complete. I'm an entry level programmer, really just for some school stuff so it isn't that complicated. I just need to find out, what's the easiest way to cover all of the answers. Here is my code.
float e,d, m,n,d, no;
cout << "Enter the numerator of the first radian or if it does... | How to read number or some text from stream.
When you read a number, but something else is encounter, stream is set int invalid state (failbit flag is set). So to handle case first you have to clear error flag and then read a string.
Since you are expecting "no" text so if something else is encounter then failbit flag ... |
67,399,300 | 67,401,426 | Qt C++ equivalent to C# toString with custom format | I am trying to find a Qt/C++ equivalent of C# toString("00.00##") (or different) custom formats.
Just some links to explain what do I want to achieve, in case if it's not clear enough:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
Format double type with minimum number of de... | I'm not quite sure 0.535353 -> 00.5353 is correct, do you want a value to be truncated (floored) to set precision before formatting or rounded to precision?
double floorWithPrec(double value, int prec) {
return floor(abs(value) * pow(10.0, prec)) / pow(10.0, prec) * (value < 0 ? -1.0 : 1.0);
}
int countIntDigits(... |
67,400,140 | 67,430,844 | (C++/Python) Capture window screenshot without caret indicator | I want to capture the screenshot of the existing running window via Python.
Following is my sample code for capture Notepad window:
import time
import win32gui
import win32ui
import win32con
import pyautogui
def getWindowScreenshot(hwnd, output_file):
r = win32gui.GetWindowRect(hwnd)
width = r[2] - r[0]
h... | After my test, I can use SendMessageW to send WM_KILLFOCUS to make the caret disappear.
This is the code that worked for me:
import time
import win32gui
import win32ui
import win32con
import pyautogui
from ctypes import windll
def getWindowScreenshot(hwnd, output_file):
r = win32gui.GetWindowRect(hwnd)
width =... |
67,400,448 | 67,411,096 | symbols visibility - shared library vs dll | I have a C++ dynamic library which defines global symbols - functions. When I compile the library using gcc those symbols are by default visible. It may leads to symbol collisions when an application links to a few libraries. I can put functions in the namespace and hide private functions using the compilation flag -fv... | Both POSIX and Windows provide different means to control symbol visibility. Source-code annotations (__attribute__((visibility("default"))) and __declspec(dllexport)) are the most common way to do this. Windows __declspec(dllexport) is indeed absolutely equivalent to POSIX -fvisibility=hidden + __attribute__((visibili... |
67,400,482 | 67,400,483 | Access violation executing location 0x0000000000000000. OpenGL with GLAD and GLFW | I have been trying to create an OpenGL window making use of GLAD and GLFW, following the instructions found at learnopengl.com and glfw.org. At first glance according to the documentation, this is enough to get a window working:
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
using namespace std;
/... | Why am I getting this error?
From learnopengl.com
Because OpenGL is only really a standard/specification it is up to the driver manufacturer to implement the specification to a driver that the specific graphics card supports. Since there are many different versions of OpenGL drivers, the location of most of its functi... |
67,401,019 | 67,401,314 | How to overload [] in vector of std::map's | I am getting these compiler errors:
1>results.cpp
1>results.cpp(28,44): error C2676: binary '[': '_Ty' does not define this operator or a conversion to a type acceptable to the predefined operator
1> with
1> [
1> _Ty=std::multimap<std::string,sqlite_data_type,std::less<std::string>,std::allocat... | There are two fundamental problems that are preventing you from doing this.
First, a std::multimap doesn't even have an overloaded [] operator. A std::multimap, by definition, can have multiple values for the same key. Therefore, if your multimap has two values for a "name", then which ["name"] do you want? You don't k... |
67,401,506 | 69,053,030 | Expected primary-expression before '[' token .. and more | I've been trying to learn dynamic programming on c++, and this is my first project on that (knapsack problem)
Please help me understand why I'm getting these errors.
This is my code:
#include<bits/stdc++.h>
using namespace std;
#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int knap(int n, int... | Replace the return statement
return max((price[n-1] + knap(n-1, wt[], price[], W - wt[n-1])), knap(n-1, wt[], price[], W));
with the following
return max((price[n-1] + knap(n-1, wt, price, W - wt[n-1])), knap(n-1, wt, price, W));
In C++ when we are passing an array to the function we use only the name of the array no... |
67,401,626 | 67,402,018 | How to wait child process with QProcess? | I am try to wait child process with this code:
auto child = new QProcess;
child->start("cmd.exe");
child->waitForFinished();
But cmd.exe doesn't open and the main program runs. What is the error?
And how I should wait correctly? waitForFinished waits 30000 msecs by default. What if I want to wait infinitely?
| I suggest checking the return value to see if the program is started successfully using the waitForStarted (doc) and try to use the full path of CMD: "C:/windows/system32/cmd.exe".
Also, check online, the question is already been asked here.
To wait infinitely you need to call waitForFinished with -1 (doc):
child->wait... |
67,401,703 | 67,402,042 | Get string of temp file and add custom folder | I'm new to C++ and I have been thinking how to get string of the user's temp folder on Windows and append to it a custom folder name.
e.g "\Users\user\AppData\Local\Temp\NameOfCustomFolder"
I've tried this:
std::string szOutput{};
TCHAR path_buf[MAX_PATH];
DWORD ret_val = GetTempPath(MAX_PATH, path_buf);
... | This does not perform the string concatenation you want
szOutput = path_buf, "NameOfCustomFolder\\file.exe";
Rather do
szOutput = std::string{path_buf} + "NameOfCustomFolder\\file.exe";
|
67,402,954 | 67,403,107 | Link to a dynamic link library in a cmake project | In a first step I created a test.dll library with the corresponding import library test.dll.a and the header file test.h. I build a new "client" project where I want to use this created library.
I have the following file structure:
client
│ └── CMakeLists.txt
|── src
│ ├── main.cpp
│ └── CMakeLists.txt
├── lib
│ ├── te... | The property INTERFACE_INCLUDE_DIRECTORIES need to be added to the test target.
set_target_properties(
test
PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES /path/client/lib
IMPORTED_LOCATION /path/client/lib/test.dll
IMPORTED_IMPLIB /path/client/lib/libtest.dll.a
)
NB: The add_... |
67,403,020 | 67,404,642 | Why virtual function's address of virtual table and virtual function's address on class are different? | below is my code
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <unordered_set>
#include <deque>
#include <Windows.h>
class B {
private:
int memB;
public:
B() :memB(0x11111111) {}
virtual void f1() { puts("B::f1"); }
virtual void f2() { puts("B::f2"); }
virtua... | In x86 (32-bit) Debug mode, MSVC vtable entries point to function trampolines, which contain JMP instructions to the actual virtual functions.
You can easily see it if you open the disassembly window and enter the address from the vtable (e.g. 0xb61276):
B::f1:
00B61276 jmp B::f1 (0B61970h)
It's probably to... |
67,403,067 | 67,444,362 | Issue in function without errors | Recently I've tried to challenge myself by trying to make a quiz game, however, as expected I've stumbled upon a error already and I can't resolve it. Well, there's no errors, but it's not working as intended, any suggestions on what to modify ?
Also, I'm a very beginner to C++ (still learning), so this might seem very... | Solution: sleep() function was actually running in seconds and not milliseconds as i've previously assumed, so i impatiently assumed that the program was not working at all and would always terminate process without waiting so when i changed it to 2, "Quiz starting in a few seconds..." appeared after 2 seconds, so when... |
67,403,382 | 67,403,602 | C++: Disadvatages of using std::uint_fastn_t | So I stumbled upon When should I use the C++ fixed-width integer types and how do they impact performance? and Should I use cstdint? where the advantages and disadvantages of fixed width integer types as defined in <cstdint> are listed.
I kinda do like to encode the intended range of a variable into its type but I also... |
are there any disadvantages of using std::uint_fast16_t instead of say unsigned int.
One disadvantage: uncertain type due do the usual promotions. Does uint16_fast_t convert to a signed or unsigned?
uint16_fast_t fa = 1;
unsigned un = 1;
int i;
fa some_operator i --> may result in an `int` or `uint16_fast_t`
un som... |
67,403,725 | 67,404,211 | Given a list of random numbers [0, 1]: can I use the standard library to convert to a specific distribution? | I have an std::vector<double> or random numbers [0, 1]. (How) Can I use the standard library to convert it to a specific (e.g. Weibull) distribution (using the distribution's cumulative distribution)?
To be clear: I don't have what the standard library considers a "generator" (I don't have a class whose operator() retu... | No you can't, not without iterative techniques.
The standard library is not quite a mathematics package. You need the quantile function for the desired distribution in order to convert a uniform drawing in [0, 1) (perhaps [0, 1] if you're lucky) to your distribution, and the standard library doesn't specify those funct... |
67,404,388 | 67,406,134 | Can a (member) function defined in a header have different definition depending on where it is included? Is this well defined? | Let's say I have something like this in a library header:
// ExampleLib.h
#ifndef DEFAULT_OPTION_VALUE
# define DEFAULT_OPTION_VALUE 1
#endif
class Example {
public:
void doSomething ();
private:
static bool getDefaultOptionValue () {
return (0 != DEFAULT_OPTION_VALUE);
}
};
And something like ... |
[basic.def.odr]/6 There can be more than one definition of a class type ... in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then
(6.1) — each defi... |
67,404,475 | 67,404,513 | C++ random srand code-if else does not give correct result | I am not receiving correct response to my code. It should give 'Excellent' when I type in correct number; however, it always outputs 'Incorrect' - Please suggest.
#include <iostream>
#include <ctime>
using namespace std;
int guess()
{
int x = 0;
x = 1 + rand() % 1000;
return x;
}
int main()
{
int inpu... | You are calling twice the function guess(), so it will give you probably different values at each run. You must store the value and then compare it with the original one.
|
67,404,662 | 67,406,541 | How to make CMakelists.txt to include some *.c and *.h files only for one OS? | I want to include some *.c and *.h files only for Windows OS. But I can't find the way how to do it without creating another target, what entails a mistake
I want to do something like this:
add_executable(${TARGET}
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
if (WIN32)
test.c
test.h... | The modern CMake solution is to use target_sources.
# common sources
add_executable(${TARGET}
main.cpp
mainwindow.cpp
mainwindow.h
mainwindow.ui
)
# Stuff only for WIN32
if (WIN32)
target_sources(${TARGET}
PRIVATE test.c
PUBLIC test.h
)
endif()
This should make your CMakeLi... |
67,404,716 | 67,405,009 | Why is this simple CUDA kernel getting a wrong result? | I am a newbie with CUDA. I'm learning some basic things because I want to use CUDA in other project. I have wrote this code in order to add all the elements from a squared matrix 8x8 which has been filled with 1's so the result must be 64.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
const int SIZE = 64;... | There are a number of issues:
You are creating a 1-D grid (grid configuration, block configuration) so your 2-D indexing in kernel code (i,j, or x,y) doesn't make any sense
You are passing sum by value. You cannot retrieve a result that way. Changes in the kernel to sum won't be reflected in the calling environment.... |
67,404,952 | 67,405,343 | Nested libcurl request c++ | My question would be how would I do a nested curl request because my current code is this and does not work. I does not work as I can see the requests going to my server and there is only one which is a GET request.
#include <curl/curl.h>
#include <iostream>
int rad = rand() % 100000;
std::string agent_name = "https:/... | Your curl_easy_perform(hnd) returns 3:
Via cURL:
CURLE_URL_MALFORMAT (3)
The URL was not properly formatted.
You will have to pass a char * instead of a std::string (see here):
curl_easy_setopt(hnd, CURLOPT_URL, agent_name.c_str());
|
67,405,073 | 67,405,131 | Input operator overloading not working properly // segmentation fault after input from user | I have this class and I'm trying to overload the input operator but i can't get it to work.
Ex2 outputs exactly what it is supposed to output but ex13 give me segmentation fault after entering 2 values.
I'm not allowed to change the type of variables from "private:" access specifier
As input I need to write this(or sim... | Disclaimer: The code in the quesiton reads like it was written to demonstrate how broken code can be while it still compiles. If the class definition was given to OP with the request to add an operator<<, there is no way to solve the exercise in any meaningful way but to throw away the code and start from scratch. Anyh... |
67,405,155 | 67,405,312 | Use int-templated function with non-constexpr values | I have some function
template<int N>
auto foo();
I want to call this function with template parameters that are unknown at compile time, but they can only be numbers 1 to c (where c is a fixed constant, e.g. 10). Is there a better general solution to this problem than the following?
auto foo(int n)
{
switch(n) {
... | Sure:
template <int... Ns>
decltype(auto) dispatch_foo(int const n, std::integer_sequence<int, Ns...>) {
static constexpr void (*_foos[])() { &foo<Ns>... };
return _foos[n]();
}
template <int Nmax>
decltype(auto) dispatch_foo(int const n) {
return dispatch_foo(n, std::make_integer_sequence<int, Nmax>{});
}... |
67,405,389 | 67,407,150 | Is there a clean way to split comma-and-space--separated words using ranges? | I'm actually adapting this one from a deleted question from yesterday.
Input: a string containing comma separated words with space after the commas.
Output: the words.
By "clean" I mean something that doesn't rely on storing temporaries into variables which wouldn't have a reason to exist, based on the intent of the co... | split can split on a pattern that is longer than one element. The one caveat is that ", ", considered as a range, is a pattern of three elements (including the terminating null character) - and in any event the adapter decays it to a pointer, which makes it not-a-range. So:
auto result = input | rv::split(", "sv);
|
67,405,395 | 67,405,607 | Can someone tell me where I went wrong. I am getting a runtime error when I submit the code, but runs for given test cases? | Here is the given question:
Given a string S you have to sort the characters of the string in lexicographically decreasing order.
Note - Do not use the inbuilt sorting function.
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
//write your code here
int t;
cin>>t;
wh... | For starters the variable t should be declared as having an unsigned integer type. Otherwise the user can enter a negative number.
Variable length arrays like this array declared in your program
int arr[n];
is not a standard C++ feature.
This for loop
for(int l=0;l<n;l++)
{
text[l]=arr[l];
cout<<text[l];
... |
67,405,688 | 67,405,861 | Why is my file being overwritten when it is not supposed to? | I am making a routine manager app in C++. I have created a start function which check if a file is already created for that date and if it isn't, it lets you plan your routine. If a routine is already created I want my program to read it out...but my .txt file is being overwritten and so nothing is being printed out an... | If I understand correctly, you want to check if a file already exists. In your code, you create an std::ofstream object which creates a new file:
std::ofstream routine(fileName);
If you want to read from an existing file, try std::ifstream (explained here).
|
67,405,804 | 67,406,295 | parsing the ip/mac adrs from a QStringList | I'm trying to parse and show the MAC addresses of my machine for a license program I'm making, but show only those with a valid IP address. I already got the IPs/MACs but I'm unable to see which one is valid and which one is not.
Here's my code:
void FormSerial::PopCB(QStringList CB){
for (int i = 0; i<CB.size(); i++){... | Try this instead:
void FormSerial::PopCB(const QStringList &CB){
for (int i = 0; i < CB.size(); i += 2){
if (CB.at(i) != "0.0.0.0"){
const QString &mac = CB.at(i+1);
Log("verdadero " + mac);
widget.Mac_ComboBox->addItem(mac);
}
}
}
Just be aware that this cod... |
67,406,329 | 67,406,380 | Does delete [] run in O(N) time? | When you deallocate an array using delete [] name, does this take O(N) time by looping through the array and deleting everything inside, or does this just delete the array itself?
| Depends.
If there is a destructor for the type stored in name, then yes, each of those destructors are run, then the memory is deallocated. Assuming that destructor runs in O(1) time, this would be an O(N) process.
If it's a type that doesn't have a destructor (primitive types, for example) the memory will just be deal... |
67,406,902 | 67,407,126 | How to test if a class satisfies a concept in C++? | In rust one explicitly types impl Trait for Object which guarantees that Object will have this trait. Now C++20 concepts are of course a bit more general as they are not associated to just one type but possibly multiple types. Nevertheless this begs the question how one would go about veryfing that some type(s) you imp... | A concept
is a predicate, evaluated at compile time
So that, given OP's example we can write
static_assert(MyConcept<MyClass1, MyClass2>);
|
67,406,943 | 67,407,244 | Why do I get a memory error only for std::string? | I am trying to create my own vector class. It seems to work fine for the built-in types, but when using std::string as a parameter, the program shows me the error below after entering two strings. I have no experience with debuggers yet. Can someone point me in the right direction?
a.out(21360,0x109f1de00) malloc: *** ... | You should delete[] what you new[] (everywhere).
Both your destructor and push_back causes undefined behavior.
Your push_back should look something like this:
template<class T>
void vector<T>::push_back(T x) {
T* old_ptr = ptr;
ptr = new T[sz + 1];
for (std::size_t i = 0; i < sz; ++i) // corrected loop cond... |
67,407,274 | 67,407,844 | Extremely inefficient code written in C++ | The computation time for the following function is very high. Is there any room for improvement? Should I be accessing the elements of matrix X differently? I appreciate any comments or suggestions.
#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::e... | It might be helpful if you provide at least some explanation of what it is you are doing.
First, I recommend breaking up the code into very small chunks, microbenchmarking each chunk, and finding bottleneck operations. This is better than throwing the whole function at the wall all at once.
row vs. column access
join_r... |
67,407,692 | 67,407,767 | GTK compiling works with gcc but not with g++. g++ does not recognize -rdynamic command | This is my code for both main.c and main.cpp
#include <gtk/gtk.h>
void quitButtonClicked(__attribute__((unused)) GtkWidget *widget,
__attribute__((unused)) gpointer data)
{
g_print("Quit Clicked\n");
gtk_main_quit();
}
// Handle the user trying to close the window
gboolean windowD... | You have to surround the functions with
extern "C" {
}
Otherwise the function/symbol names are C++ mangeled, which GTK cannot look up.
|
67,407,807 | 67,407,914 | Static member definition of complex type of a template class with SFINAE | It is fairly standard way to declare and define a static const member of a complex type of a template class. However, I would to use SFINAE patter in my class. And that leads to this error: template definition of non-template 'const std::array<unsigned int, 2ul> Message<Self>::kData'. Removing SFINAE resolves the error... |
What is the proper syntax to still use SFINAE and properly define the static constant?
Simply using a generic type T
// ............................V
template <class Self, typename T>
const std::array<uint32_t, 2> Message<Self, T>::kData = { 12, 13 };
// .......................................^^^
Template default ty... |
67,408,332 | 67,408,362 | Texture is uncentered | So, I'm trying to do a very basic program in OpenGL. Everything went fine, had issues with texturing but now it's all solved.
But now, I have a little issue. The texture shows, but it isn't "centered". I tried changing the vertex positions, but nope, it doesn't work.
Here's an image showing what's happening:
Here's so... | The texture coordinates need to be in range [0.0, 1.0]:
glTexCoord2f(0.0f, 1.0f); glVertex2f(-.5, .5); //A
glTexCoord2f(1.0f, 1.0f); glVertex2f(.5, .5); //B
glTexCoord2f(1.0f, 0.0f); glVertex2f(.5, -.5); //C
glTexCoord2f(0.0f, 0.0f); glVertex2f(-.5, -.5); //D
(0, 0) is the bottom left and (1, 1) is the top right coord... |
67,408,357 | 67,408,474 | How to avoid update checks with CMake FetchContent? | all.
I decided to use the new cmake macro to download external dependencies.
I took the sample code from the documentation for the Catch2 library.
include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v2.13.4
)
FetchContent_GetProperties(Cat... | The documentation for FetchContent_Populate says you can get exactly what you want with the FETCHCONTENT_UPDATES_DISCONNECTED cache variable:
FETCHCONTENT_UPDATES_DISCONNECTED
... This ... disables the
update stage. Therefore, if content has not been downloaded
previously, it will still be downloaded when this option ... |
67,408,571 | 67,427,706 | My RegSetValueA function is returning ERROR_SUCCESS but not working | My code:
HKEY hKey;
char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardware Profiles\\0001";
LONG result1 = RegOpenKeyExA(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS, &hKey);
QString q = QString::number(result1);
if (result1 == ERROR_SUCCESS) {
char buffer[39];
DWORD... | You need to use RegSetValueExA and call:
BYTE* p = (BYTE*)l.c_str();
result13 = RegSetValueExA(hKey, "HwProfileGuid",0, REG_SZ, p, l.size() + 1);.
And it works for me.
|
67,408,619 | 67,408,772 | Compiler is unable to resolve a matching class method passed via std::mem_fn | Consider the following code:
struct A {
int& getAttribute();
const int& getAttribute() const;
};
std::vector<int> foo(const std::vector<A>& as) {
std::vector<int> ints;
std::transform(as.begin(), as.end(), std::back_inserter(ints),
std::mem_fn(&A::getAttribute));
return ints;
}
... | The compiler should choose pointer of the function at the moment of mem_fn creation. It can only look at the std::mem_fn(&A::getAttribute) expression, but cannot look up how it's used. It's possible to work around with user-defined conversion operators, but is generally not done.
So, your reasoning about future uses of... |
67,409,098 | 67,409,188 | QML label inflate background rect | Okay, I give up. How do I draw backing rectangle around Label?
Here's what I do
import QtQuick 2.0
import QtQuick.Controls 2.15
Label {
id: label
text: root.text
font {
pointSize: 24
bold: true
}
wrapMode: Text.WordWrap
background: Rectangle{
radius: 20
color: "l... | I think what you're looking for is padding. Don't add anything to the height/width of the background. Just add padding.
Label {
id: label
text: root.text
font {
pointSize: 24
bold: true
}
wrapMode: Text.WordWrap
padding: 15
background: Rectangle{
radius: 20
co... |
67,409,129 | 67,409,238 | How to convert a string into three integers | I'm currently trying to convert a string into three integers. I need to do some math with "11", "5" and "2". At least in this example. I tryed to convert the string using stoi() into integers, but I couldn't do the part where I take only a part of the string, like in my second example down below. Is there a simple solu... | stoi(time[3]) won't work, as that is passing a single char to stoi(), which wants a null-terminated char* string instead. You can use stoi(&time[3]) instead (since string's inner buffer is guaranteed to be null-terminated in C++11 and later), or better stoi(time.c_str()+3), eg:
string time = "01:50"; // mm:ss format
... |
67,409,166 | 67,409,314 | How to make a pointer member data's constness vary with the parent instance's constness? | I have a class like this one:
struct Example
{
std::unique_ptr<int> pointer_member;
};
I'd like the type of pointer_member to be std::unique_ptr<int const> const when manipulating instances of Example const, and std::unique_ptr<int> when manipulating instances of Example.
The best solution I could think of so far ... | Encapsulation allows to control modifiable-ness (aka constness) of members:
#include <memory>
struct Example {
const int& get() const {
return *pointer_member;
}
int& get() {
return *pointer_member;
}
private:
std::unique_ptr<int> pointer_member = std::make_unique<int>(42);
};
int ... |
67,409,337 | 67,409,339 | What variations of vector-like containers already widely established? Do I have to write my own? | In my program, I often need an owning array-like container - i.e. for data stored contiguously in memory, but vector is too flexible and less practical or efficient than it could be.
The requirements differ from std::vector in one or more aspects such as:
Elements can only be inserted at the end, without moving other ... | Here are the ones I know of:
Traditional a.k.a. plain a.k.a. C array
vector
unique_ptr with an array-type template argument
array
valarray
dynarray
static_vector (see also here)
small_vector
stable_vector
There are also "variable-length arrays" and "arrays with runtime bounds", which do not exist in C++; the former e... |
67,409,442 | 67,409,648 | C++ treats macro as a class | In visual studio I've set configuration type as .dll instead of .exe and because of that sometimes I need to use __declspec(dllexport) or __declspec(dllimport) . So I've created macros for them inside header file called "Core"
#pragma once
#ifdef B5_PLATFORM_WINDOWS
#ifdef B5_BUILD_DLL
#define B5_API __dec... | Okay I've fixed it. turns out problem was completely different thing. My preprocessor didn't save some of the definitions so in second project B5_API wasn't getting defined
|
67,409,492 | 67,409,660 | Is there any way to tell C++11 to use std::string instead of const char*? | Im trying to migrate code from another language that allows concatonation of strings with the '+' operator.
//defintion
void print(std::string s) {
std::cout << s;
}
//call
print("Foo " + "Bar");
The issue I'm having is that c++ sees "Foo " and "Bar" as const char* and cannot add them, is there any way to fix thi... | In c++14 and later:
using namespace std::literals;
print("Foo "s + "Bar");
In c++11:
std::string operator "" _s(const char* str, std::size_t len) {
return std::string(str, len);
}
print("Foo "_s + "Bar");
Or, in all versions:
print(std::string("Foo ") + "Bar");
|
67,409,539 | 67,409,562 | unique_ptr and failed memory allocation | I want to create a unique pointer using unique_ptr<A>(new A) (not make_unique()).
The unique_ptr constructor is noexcept, however new may throw bad_alloc.
So my question is, whether I should expect an exception calling unique_ptr<A>(new A) in case new fails or not?
I tried to check that and I'm getting 'abort' in the c... |
So my question is, whether I should expect an exception calling unique_ptr<A>(new A) in case new fails or not?
Yes. If new fails, it will throw a std::bad_alloc exception, and the std::unique_ptr object will not even be constructed at all.
I tried to check that and I'm getting 'abort' in the code below, whereas I ex... |
67,409,714 | 67,409,822 | C++ : Possible Concepts-related bug yields "multiple dispatch" | What's going on here? It seems the ability to declare testGeneric with an auto& parameter creates a weird situation where the function can be used to implement multiple dispatch.
Tested on gcc 10.1 or newer with "-fconcepts-ts" flag, also works on x86-64 clang (old concepts branch) via Compiler Explorer.
#include <iost... | testGeneric is an abbreviated function template. It is functionally equivalent to the template declaration
template <class T>
void testGeneric(T &g)
{
g.print();
};
Your code will have 3 different testGeneric functions, one for each type that you call it with.
|
67,409,737 | 67,409,908 | fstream cannot be referenced - dead function | void isRegistered(std::list<User>* usersList, std::list<User>::iterator& v, std::string username, std::string password){
std::fstream userfile = openFile("users.csv");
readUsers(userfile, usersList); // this line
readUsers(std::fstream file, std::list<User>* usersList) and reads whatever is in the csv file in... | As noted in comments, you cannot pass C++ streams to functions by value. The error message tells you that. To fix that, pass by reference:
readUsers(std::fstream& file, std::list* usersList);
// changed here: ^
|
67,409,792 | 67,409,877 | C++ primer 5th edition: operator new and operator delete overloading | can someone explain to me this paragraph from C++ primer 5th edition:
Terminology: new Expression versus operator new Function
The library functions operator new and operator delete are
misleadingly named. Unlike other operator functions, such as operator=,
these functions do not overload the new or delete expressions... | Most operators in C++ aren't bound by any explicit semantics or requirements. The only real exceptions are operator new and operator delete due to its specialized use, which is what this is referring to.
For example, lets consider operator==.
Even though it's conventional (and wise) to have this operator perform some k... |
67,409,837 | 67,409,939 | Overriding protected variable c++ | Suppose I have the following code:
class Board
{
protected:
std::vector<Piece*> pieces;
}
class ChessBoard : public Board
{
protected:
std::vector<ChessPiece*> pieces;
}
I am wanting the derived class to override the protected variable pieces with this new vector, however I am having difficulty with it, ... | There is no such thing as "overriding a variable", whether protected or otherwise.
In your example program, the class ChessBoard contains a member sub object pieces and a base sub object Board that contains the member Board::pieces. Thus, there are two vectors inside the object.
Object oriented programming is achieved ... |
67,410,319 | 67,410,415 | How do I get the exact length of an array without using subscripted values within a template function in C++? | I'm trying to find the length of any given array and the methods I've tried so far won't work. This is my sizeOf function (not to be confused with sizeof):
template <typename T>
size_t sizeOf(T val) {
size_t sz = (size_t)0;
if (typeid(val).name()[0] == 'c') {
sz = (int)sizeof(val);
} else if (typei... | Here's a solution that might work for you. It uses if constexpr to ensure that the first template only tries to compile valid branches in the code (you can add more if you need them) and a template overload to handle arrays of arbitrary type. Note: needs C++17 or later.
#include <iostream>
#include <cstring>
#include... |
67,410,887 | 67,410,909 | My pre increment is working fine but not the post increment | I have implemented the following class and tried to overload the pre and post-increment operator along with the extraction '>>' operator. The programs runs fine till 'cout << ++num1;' but prints junk values for the last line 'cout << num1++;'. I cannot figure out that why is it working fine for pre-increment
but not fo... | Your post-increment operator is returning reference to local object, which will be destroyed when function ends, the returned reference is always dangling and dereference on it leads to UB.
Post-increment operator is supposed to return-by-value, e.g.
ComplexNumber ComplexNumber::operator++(int x) // postincrement
{
... |
67,411,013 | 67,411,245 | cannot convert ‘std::vector<double>*’ to ‘__gnu_cxx::__alloc_traits<std::allocator<double*>, double*>::value_type’ {aka ‘double*’} | I can't convert the double to double here
in main.h I have :
std::vector<std::vector<double>> *m_va;
std::vector<std::vector<double> > *get_ptr() { return m_va; }
in main.cpp I want to have :
std::vector<double *> F(n);
F[i] = this->get_ptr()[j].data();
but I got :
cannot convert ‘std::vector’ to ‘__gnu_cxx::__allo... | Be careful when mixing C and C++ approaches.
A std::vector is an object and you cannot treat the pointer to that object as if it was the pointer to the underlying buffer.
Your get_ptr() method returns a pointer to a vector not a vector itself or a reference to it, as a consequence the brackets are not mapped as a call ... |
67,411,020 | 67,411,256 | C++ Visual Studio release build is not working (OpenCV 4.5.2) | Now, I tried to build release mode from C++ source code with OpenCV.
This source code is built on debug mode, but it is not built on release mode.
The below images are my OpenCV library setting.
Please give me your help
1>------ Build started: Project: OpenCVServer, Configuration: Release x64 ------
1>StreamServer.... | The error is most probably happening because you provided OpenCV library named ...d.lib to your release linker configuration.
d suffix in library file name means that it is debug library. All .lib files are usually shipped as two files, one for release (without d) and one for debug (with d).
Try to find release .lib an... |
67,411,390 | 67,411,477 | Returning a reference to the calling object (C++) | Having a bit of a hard time understanding this code:
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
... | If setX were changed to
Test setX(int a) { x = a; return *this; }
then it returns a copy of *this instead of a reference to it. So in
obj1.setX(10).setY(20);
the setY is called on the copy, and not on obj1 itself. The copy is discarded and obj1.y is never modified from its initial value of 5.
|
67,411,632 | 67,411,806 | Write unformatted data to file with fstream | I'm trying to transfer a file over between sockets. I use a 1MB file created through /dev/urandom on linux. With this file, I am able to transmit data through the client successfully but when I write the data into a file, the output is incomplete. The command I am using is:
myFile << data;
I think what may be happeni... | Use std::ofstream::write (std::fstream and std::ofstream inherit the write function from std::basic_ostream).
myFile.write(reinterpret_cast<const char*>(&data), sizeof(data));
For raw binary data vector<uint8_t> data you can write the whole vector at once:
std::vector<uint8_t> data{};
//Fill data...
myFile.write(rei... |
67,412,167 | 67,412,275 | Constructor Initializer List vs Constructor Body | Let's say someString initialization is a tad complicated, hence we write a simple member function stringInitialization() with which to initialize someString in the body of the constructor:
class DemoL {
private:
int someNumber;
std::string someString;
void stringInitialization() {
if (someNumber =... | Your assumption is correct. The constructor DemoL(int rNumber) needs to be able to default construct the member someString and this is no problem because std::string is default constructible.
One obvious point is that one member could be not default-constructible, in which case you would have to initialize it.
But even... |
67,412,182 | 67,412,689 | How to loop through a multidimenional array through pointers in C++ | Looping through a simple array is no problem, but what is the correct way to loop through the multidimentional array by using pointers?
#include <iostream>
int main(int argc, char* argv[])
{
int data1[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
for(auto *p = data1; p!=data1+9; ++p)
{
std::cout << (*p) << '... | Given: int mdArray[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
mdArray is a pointer to a 3 element array
each element in that array is a pointer to a 3 element array
each element in those arrays is an integer
So just nest your original syntax inside itself substituting the de-referenced var instead of the name of the... |
67,412,520 | 67,412,648 | i am trying to understand how formal parameters work in c++ | I am new to programming, trying to understand what formal parameters are. I am reading this book called "the complete c++ reference", there is an example provided in the book about formal parameters which I am attaching in the code below. when I try to execute the program a list of errors is being displayed can anyone ... | The issue is at
while(s)
if(s==c)return 1;
s is a char pointer, in order to get the value stored at the memory to which the pointer s is pointing, you must de-reference it by using a * operator as shown in the example
while(*s)
if(*s==c) return 1;
#include <iostream>
int
is_in(char * s, char c) {
w... |
67,412,534 | 67,415,597 | Recursive function to check all pairs in an array | an int vector is given, and I need to find the maximum sum of number sequences that are more than 3 positions away from each other. So an example:
Input: 10, 5, 6, 7, 16, 18, 12
Output: 29
Explanation:
candidate "routes":
10-7-12 = 29
10-16 = 26
10-18 = 28
5-16 = 21
5-18 = 23
5-12 = 17
...
16
18
1... | There are 3 problems here:
Based on your output:
10 9 7
8
8
⋮
Your code actually loops through all the possible routes. Instead of thinking your second line 8 and third line 8 as two complete routes, they were actually derived from your first rout 10 9 7. So really think of it like this:
10 --- 9 --- 7
`- 8
`... |
67,412,726 | 67,413,382 | Program to convert given number of days in terms of Weeks and Days | First I want to the week start with day1 and end with day7, but the problem is when entering day15 the output is weeks: 2, days: 8, but I want the output to be weeks: 3, days: 1, also when entering day22 the output is weeks: 3, days: 8, but I want the output to be weeks: 4, days: 1 and when entering day23 the output is... | You can produce the expected output with
#include <iostream>
using namespace std;
int main()
{
int week, day;
cout << "Enter No. of days:";
cin >> day;
week = (day - 1) / 7 + 1;
day = (day - 1) % 7 + 1;
cout <<"\nWeeks: "<<week<<"\nDays: "<<day << endl;
}
|
67,413,840 | 67,413,929 | Instantiate class inside a Constructor (c++) | Is the use of new/delete appropriate here? Or any way to avoid them?
The point: class myOptions need an instance of Submarine. The Parameter are known at the time the myOptions-Construcor is called.
#include <iostream>
#include <string>
class Submarine
{
public:
Submarine(std::string o)
{
std::cout << ... | You don't need to use dynamic memory here:
class myOptions
{
public:
myOptions(std::string o):option(o), submarine(o)
{
std::cout << "create class myOption: " << option << "\n";
}
private:
std::string option{};
Submarine submarine;
};
If you really need to use dynamic memory allocation (an... |
67,413,924 | 67,415,195 | glReadPixels() is not accurate | I want to do mouse picking based on colors. Here is my code:
bool Geometry::IsObjectClicked(int x, int y, float color[4])
{
glFlush();
glFinish();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
struct { GLubyte red, green, blue; } pixel;
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pixel);
float clicke... | The first commenter was right, you have to change y to height-y.
As for the color comparison, I noticed that there is a slight difference between the two colors which makes the comparison false. So I added a 0.01f tolerance:
if ((clickedColor[0] == color[0] || abs(clickedColor[0]-color[0]) < 0.01f) && (clickedColor[1] ... |
67,413,973 | 67,414,054 | No matching constructor for class initialization | I have this class :
class instaStalkPanel : public wxPanel {
private:
public:
instaStalkPanel(wxWindow *parent, wxWindowID id, wxPoint &pos, wxSize &size, long style, const wxString &name);
wxDECLARE_EVENT_TABLE();
};
Now I'm trying to initialize a pointer variable of this class like this, in another... | You're trying to bind non-const references (pos and size) to const objects.
Make the parameters const wxPoint& and const wxSize&.
|
67,414,094 | 67,414,354 | Create a "file.dat" from the windows CMD | When running the following C ++ script I obtain the necessary data to work in Gnuplot.
#include "stdio.h"
double TT;/* Imaginary part of T matrix */
double x;/* Real part of Energy */
double y;/* Imaginary part of Energy */
double G;/*Resonance Peak width */
double ER;/* Resonance Peak Energy */
main()
{
G = 120.;
ER... | Well, the code you use looks more like C and not C++.
(which is fine too)
In C, you can use fprinf instead of printf .. have a look here:
#include <stdio.h>
int main () {
FILE *file;
const double G = 120.;
const double ER=180.;
file = fopen("file.dat","w+");//create or overwrites a file
for(int x=1... |
67,414,559 | 67,473,340 | hidding symbols from a static library | I have a c++ shared library - libA.so. I hide symbols using -fvisibility=hidden flag. The symbols which should be visible have the following attribute: __attribute__ ((visibility ("default"))). That library links to the static library - libB.a. All symbols from that static library (libB.a) should be visible only for th... | Visibility feature has been added to support limiting interfaces of shared libraries i.e. reducing number of exported functions. By default (without -fvisibility=hidden) linker will export all functions in library which is, in most cases, not what you want.
Visibility is ignored during static library link i.e. when li... |
67,414,701 | 67,457,625 | Initializing static variables in ue4 c++ | I have a actor class ANodeBase. Each node must have a unique id. To realize that, i create static variable id_counter.
Code:
//ANodeBase.h
static int id_counter;
//ANodeBase.cpp
#include "NodeBase.h"
int ANodeBase::id_counter = 0;
ANodeBase::ANodeBase()
{
PrimaryActorTick.bCanEverTick = false;
id = id_counter... | As we found out, unreal creates CDO (class default object), which call constructor. Accordingly, I transfer my code to BeginPlay() and now it's work.
|
67,415,240 | 67,461,746 | Intel C++ compiler and Wnon-virtual-dtor flag gives (wrong?) warning | I was trying to compile some code of mine which, in g++ (with the --Wnon-virtual-dtor Flag) compiled just fine. Also, my IDE and clang-tidy didn't warn me (I see that this might be false of course).
When I tried to compile the same code with Intel's icpc (actually this one icpc (ICC) 19.1.2.254 20200623) I got a warnin... | Ok, so after also posting this question on the Intel forum - seems to be (a very much non critical) bug in the compiler - the workaround would be writing both, virtual and override.
This is discouraged by the item C.128 in the cpp core guidelines (same link as in the comments) but not problematic.
|
67,415,578 | 67,415,748 | String marshalling and memory management | Suppose I have the following C++ function that is exported in a library:
void foo(const wchar_t* text);
and C# code that uses that function:
[DllImport("bla.dll")]
static extern void foo([MarshalAs(UnmanagedType.LPWStr)] string text);
void Bar()
{
string s = "hello";
foo(s);
}
Does the .net marshaller copy ... |
Does the .net marshaller copy the string when I call foo or does the pointer point to the buffer of s?
The specific case of an LPWSTR being passed by value means that the managed string gets pinned and used directly by native code, see here. In all other cases, the string is copied, see here.
If the value is copi... |
67,415,656 | 67,437,948 | DDS QoS: Is it possible to send data without specifying a key? | I am currently using Eclipse Cyclone DDS C++ and I am wondering if it is possible to send data without any key specified with #pragma keylist in an IDL.
Is it possible to achive this through QoS-Settings? If so, how?
| If you do #pragma keylist TYPE without listing any key fields, the IDL compiler will generate everything you need for creating a topic that doesn't have any key fields. So
struct S {
long something;
string orother;
};
#pragma keylist S
is perfectly valid, and then you can create a topic for S.
I am not entirely su... |
67,415,672 | 67,436,858 | Sum signed 32-bit int with unsigned 64bit int | On my application, I receive two signed 32-bit int and I have to store them. I have to create a sort of counter and I don't know when it will be reset, but I'll receive big values and frequently. Beacause of that, in order to store these values, I decided to use two unsigned 64-bit int.
The following could be a simple ... | A little background, just for reference: binary operators such arithmetic addition work on operands of the same type (the specific CPU instruction to which is translated depends on the number representation that must be the same for both instruction operands).
When you write something like this (using fixed width integ... |
67,415,820 | 67,417,039 | New allocates the same memory with each iteration | I am trying to build a list-like heap storage of C-strings.
This is a simplified part of the program.
However, with each iteration new brings up the same address.
#include <iostream>
class listStringContainer {
public:
listStringContainer(const char* c);//constructor
};
int main(){
listStringContainer lsc1 ("... | You need to cast the static_cast<void*>(Memory_Address) to get the value stored in Memory_Address.
Lets consider:
char * p;
p= new char[16];
strcpy(p, "Hello");
cout << *p << endl; // Prints 'H'
cout << &p << endl; // Prints address of p
cout << p << endl; // Prints "Hello"
cout << static_cast<void*>(p) << endl; // Pr... |
67,416,019 | 67,416,433 | Get either a single object or list of objects from an argument of PYBIND11 binded c++ function | I'm trying to bind a function that accepts multiple arguments and keyword arguments with PYBIND.
The function looks something like this:
{
OutputSP output;
InputSP input;
if (args.size() == 1)
{
input = py::cast<InputSP>(args[0]);
} else if (args.size() == 2)
{
query = py::cast<O... | Found it.
py::cast throws py::cast_error when casting fails, so I can treat the two options with try-catch:
else if (key_name == "status")
{
try
{
status = py::cast<std::vector<MultiFlags> >(kv.second);
} catch (py::cast_error&)
{
status = { py::cast<MultiFlags>(kv.second) };
}
}
|
67,416,074 | 67,416,292 | Writing interface for Matrix | I am writing an Interface for Matrix class in C++ So all functions need to be virtual
Now in the below code I have defined a virtual function virtual Matrix add(Matrix A, Matrix B) const = 0;
The problem I see is the class Matrix is not defined. So I am confused should I define the
class Matrix in the interface ? Or... | Return the interface type from the add method in your interface class, then in the subclass, you can override the virtual method and change the return type to Matrix (or any narrower type).
class MatrixInterface
{
public:
virtual MatrixInterface* add(MatrixInterface* A, MatrixInterface* B) const = 0;
};
Derived cl... |
67,416,245 | 67,418,146 | How to read .rodata from linked object files? | I am trying to access an externally linked data segment in a C/C++ program.
#include <iostream>
extern void *__foo;
int main(int argc, char **argv)
{
const char *foo = reinterpret_cast<const char *>(__foo);
std::cout << std::addressof(foo) << std::endl;
std::cout << foo[0] << std::endl;
return 0;
}
T... | It appears that whatever __foo contains, it is not a valid pointer. If you are interested in the contents of __foo itself, declare it as extern char __foo[] and dump that.
|
67,416,925 | 67,418,627 | C++ variadic template empty argument specialization | What's the correct way to write a specialization for an empty argument variadic template. Take bellow code as an example:
#include <iostream>
#include <memory>
#include <tuple>
#include <functional>
#include <cassert>
using namespace std;
struct message {
int type;
};
struct X: message {
int payload;
X()... | In C++17, you don't need to split parameter packs into head and tail in most cases. Thanks to fold expressions, many operations on packs become much easier.
// Some generic predicate.
template <typename T>
bool condition_hold(T) {
return true;
}
// Make this whatever you want.
void do_something_with(int);
templat... |
67,417,502 | 67,417,726 | Code terminates after single iteration in member function which is assigning values to pointer in loop | I'm creating an abstract datatype. The code is as follows
#include <iostream>
using namespace std;
template <class T>
class cArray
{
int size;
T* p;
public:
cArray(int size)
{
this -> size = size;
T* p = new T[size];
}
void setval(void)
{
for (int i=0; i<size; i++)... | It is close to a typo, but my Clang compiler directly stopped on the error with a warning
unused variable 'p'
in cArray ctor.
Let us look at it:
cArray(int size)
{
this -> size = size; // ok this correctly assign to the member
T* p = new T[size]; // Oops, this assigns to a local variable...
}
Th... |
67,417,863 | 67,417,916 | How to convert nlohmann json to uint8_t array? | I would like convert my created json object to array of uint8_t[1000]. I tried something like this:
nlohmann::json j_file;
j_file["number"] = 2;
j_file["example"] = "dog";
uint8_t parsed_json[1000] ={0};
auto str = j_file.dump();
std::vector<std::uint8_t> v (str.begin(), str.end());
std::co... | You can copy contents of std::string to the array without using std::vector as proxy.
uint8_t parsed_json[1000] ={0};
auto str = j_file.dump();
std::copy(str.begin(), str.end(), parsed_json);
|
67,418,029 | 67,418,387 | Why does C++17 if statement with initializer not work as expected? | struct A
{
auto g1()
{
return true;
}
void f()
{
if (auto b = g1(); b) // ok
{
return;
}
if (auto b = g2(); b) // error: use of 'auto A::g2()' before deduction of 'auto'
{
return;
}
}
auto g2()
{
... | Because the standard says so (quote from latest draft):
[dcl.spec.auto.general]
If a variable or function with an undeduced placeholder type is named
by an expression ([basic.def.odr]), the program is ill-formed. Once a
non-discarded return statement has been seen in a function, however,
the return type deduced from t... |
67,418,633 | 67,419,134 | Simple way to execute two parallel tasks in TBB | I need to execute two parallel tasks using Intel Threading Building Blocks, and wait till both are finished.
I can do it as follows:
tbb::parallel_for( tbb::blocked_range<int>( 0, 2, 1 ), [&] ( const tbb::blocked_range<int>& range )
{
for ( int i = range.begin(); i < range.end(); ++i )
... | For a small number of tasks, you can use tbb::task_group:
tbb::task_group g;
g.run([&] { task0(); });
g.run([&] { task1(); });
// do other work while tasks run ...
g.wait(); // wait for all tasks to finish
As a small optimization, can run one of the tasks in the current thread:
tbb::task_group g;
g.run([&] { task1... |
67,418,801 | 67,421,232 | C++ Can't Print Values from Array of Strings | I am having trouble with an assignment for my freshman Computer Science class.
I am trying to have PrintAllConcepts print each item of an array, once per line.
For some reason all I get is the last line printed from LIST.txt and a bunch of extra empty lines that usually end up nearly crashing the program. There appears... | As you commented, the errors are in the ReadConcepts function.
To begin with you should not increment Number in the loop, as it's already the number of elements in the array. Because you increment Number you will pass the value 200 to PrintAllConcepts which will make it go out of bounds of the array.
Secondly you put a... |
67,418,826 | 72,588,121 | Possibility of converting a C++/Qt threads using event loops to C# (or java) threads with Dispatchers | Is it possible to convert a Qt/C++ code that uses threads executing an event loop and using the signal/slot mechanism with queued connections to communicate between 2 threads ?
I saw that there is this class called Dispatcher in C#/WPF (or WinForms), and I don't know if it exists apart from the UI context (can it be us... | I posted a similar question here : Implementing a permanent thread that manages a resource and other threads that requests this thread to do some task and return a result and it has interesting resources and a final answer to my question.
|
67,418,867 | 67,419,112 | C++ map of string to custom class with generics | I have tried for the past days to solve this issue I have with C++. It may be trivial, but I could not find a solution and searching on the Internet got me nowhere, so I'll ask here.
I have a C++ wrapper Singleton class, a superclass and a number of subclasses. I need the the instances of the subclasses to be singleton... | template <class T : public MySuperclass>
std::unordered_map s_classes<std::string, Singleton<T>> s_classes;
is not valid C++.
But you could simply make a std::unordered_map<std::string, MySuperclass*> s_classes.
It's not necessary for our lookup map to know about the Singleton pattern, it just needs to map onto a poin... |
67,418,907 | 67,419,305 | Call a variadic template functor in a variadic template parameter pack if it satisfies a condition | I have a variadic template functor class:
template <typename Result, typename... Arguments>
class Functor
{
public:
using FunctionType = std::function<Result(Arguments...)>;
Result operator() (const Arguments&... arguments) { return Function(arguments); }
std::string GetName() { return Name; }
Functor(c... | In C++17, this is easily solvable using fold expressions.
#include <functional>
#include <string>
template <typename Result, typename... Arguments>
class Functor
{
public:
using FunctionType = std::function<Result(Arguments...)>;
Result operator() (const Arguments&... args) {
return this->Function(argu... |
67,418,928 | 67,422,281 | avoid member access for shared base state | Suppose I have a base class that is an abstract interface, and two derived classes, which inherit a certain state from the base class. I want to change which derived class I'm using at run-time, but I want to preserve the shared state.
class Base{
public:
virtual void abstract() = 0;
SharedState ss;
};
class Der1 : pu... | This is an ugly answer, but is an answer, solves the "ss" problem and can be usefull.
I overloaded the operator [] to directly return the values of your struct
struct SharedState{
int x,y,z;
float x1,y1,z1;
//etc...
};
class Base{
public:
virtual void abstract() = 0;
SharedState ss;
public:
int& operator[](const s... |
67,419,306 | 67,419,387 | How do I fix this class issue? | I've been getting 2 errors for this code:
'totalCost' is not a type
'cout' was not declared in this scope
What am I missing?
#include <iostream>
class License{
public:
int vat, totalCost;
int calculateVat();
};
class PurchasedLicense :public License{
calculateVat(totalCost){ //the first error se... | The first error can be fixed by adding type names for the return type and argument of calculateVat().
The second error can be fixed by adding std:: before cout (and cin).
Also, there is another error that the calculateVat variable used in the main() function is not declared. Declare that variable to fix this error.
#in... |
67,419,517 | 67,430,621 | Writing 00 in hex char array | I have to send commands to some device with the hexadecimal format.
I have succeeded to send hex commands with "\xAA\xBB\xCC\xDD\xEE" and "\xAA\xBB\xCC%c\xEE" with %c containing a certain decimal value.
But I can't send 00 value like "\xAA\xBB\xCC0x00\xEE".
I've seen many topic on this, but no solution fits my need. I ... | As @MikeCAT and @Remy Lebeau said : sprintf(char_array, "\xAA\xBB\xCC%c\xEE", '0');
work.
The issue was that later in my code I have a strlen(char_array) which returned :
6 for sprintf(char_array, "\xAA\xBB\xCC\xDD\xEE", 22); and
4 for sprintf(char_array, "\xAA\xBB\xCC%c\xEE", 0);
So for now i will fix the size at 6.
T... |
67,419,770 | 67,423,946 | Is there a way to profile a MPI program with detailed cache/CPU efficiency information? | OS: Ubuntu 18.04
Question: How to profile a multi-process program?
I usually use GNU perf tool to profile a program as follows:
perf stat -d ./main [args], and this command will return a detailed performance counter as follows:
47,455.09 msec task-clock # 8.602 CPUs utilized
... | Basic profilers like gperf or gprof don't work well with MPI programs, but there are many profiling tools specifically designed to work with MPI that collect and report data for each MPI rank. Virtually all of them can collect hardware performance counters for cache misses. Here are a few options:
HPCToolkit for sampl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.