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 |
|---|---|---|---|---|
65,021,138 | 65,021,858 | How to split array into n chunks given their sizes in C++? | Say I have an array of 10000 integers, it is to be split into 3 sub-arrays ("num_jobs" in this case). In my code I have found the length for each subarray, and lengths are stored in an array "parts" in the function "split()".
My code:
// Function that prints
// the required sequence
int * split(int x, int n) //x=100... | First of all, try to avoid using raw arrays if you can. std::vector is pretty much the same in terms of performance and internal implementation but at the same time provides robust interface and handles memory for you.
As for C-style arrays, you can't split a single array into parts. Let's say you have
int* arr = new i... |
65,021,655 | 65,022,041 | How to make a static template member function as friend | I would like to define a staitc member funtion to build my class. This staitc function would access private member, and I make it as friend.
Here is the demo code:
#include <memory>
template<typename T>
class Foo
{
public:
static std::unique_ptr<Foo> Create();
friend static std::unique_ptr<Foo> Foo::Create();... | As stated in the comments, you don't need it. Why? Because static member functions are still member functions, meaning they can access private members of the class. I'm assuming that this was the confusion. A small (somewhat contrived) example:
#include <iostream>
#include <memory>
// templated class with private memb... |
65,021,677 | 65,032,524 | How to get Intellisense working on standalone C++ source files in Visual Studio 2019? | Can somebody tell me how to get Intellisense working on standalone C++ source files in Visual Studio 2019 (i.e C++ source files that are not a part of Projects and Solutions). I read online that I need a CppProperties.json file in the directory that my miscellaneous C++ source files and that I can add one by using the ... | First, you could put the relevant files in a folder, click File->Open->Folder and select a folder containing project files. According to the comments above, it is necessary to get rid of vcpkg.
For example:
Then, you will find the Manage Configuration appears in the navigation bar.
Here are the screenshots you reques... |
65,021,731 | 65,021,784 | c++ Klocwork error memory is allocated through the call to 'new[]' | Klocwork 2020.1 Build 20.1.0.97
// Vertices of simplex
auto v = new double*[n + 1]; // this line give the error
// Average coordinates
auto v_ave = new double[n];
// Reflection coordinates
auto v_ref = new double[n];
// Expansion coordinates
auto v_exp = new double[n];
// Contraction coordinates
auto v_con = new double... |
memory is allocated through the call to 'new[]'
I can't find any suggestion for the fix.
To fix the error "memory is allocated through the call to new[]" is to not allocate memory through new[]. Simplest solution is to use std::vector instead.
|
65,021,923 | 65,136,110 | Is there a CGAL function for finding all intersecting points between a 2D line (Line_2) and a set of 2D polygons with holes (Polygon_with_holes_2)? | I have a line from 0, 0 to 1024, 0. Many polygons with holes lie between the two ends of the lines. I would like to know if there is any CGAL function that can tell me all the points of intersection between the line segment and all the polygons with holes.
Alternatively, a function for intersection between a line and a... | The answer is no. Intersection functions for polygons work with two polygons only, and the meaning of the intersection is a piece of plane, consisting of points, lying inside both polygons. If you want to find intersection points for a segment and the polygon boundary - you need to extract all the boundary edges one by... |
65,021,987 | 65,022,175 | set class object array init value at definition of object array in C++ | I have two questions. I run the below code and it sets each array object variable to 20 ın GCC 6.3 version. However, when I try the higher version of GCC, It gives an error.
Why is there this changing?
#include <iostream>
class A{
int a;
public:
A(int);
};
A::A(int init_val){
this -> a = init_val;
}
i... | No, there is no way to initialise an array like that in C++. Neither of your attempts are well-formed.
You can initialise every element explicitly like this:
A a[10]{
{20, 'A'},
{20, 'A'},
{20, 'A'},
{20, 'A'},
{20, 'A'},
{20, 'A'},
{20, 'A'},
{20, 'A'},
{20, 'A'},
{20, 'A'},
};
... |
65,022,760 | 65,022,910 | Declaring concept for method with param | I tried declaring the concept below, but MSVC 16.8 gives a compiler error. I trying to create a concept for a class that contains function: bool Serialize(Archiver&)
Am I declaring the concept wrong, or is MSVC broken?
struct Archiver {};
template<typename T>
concept Serializable = requires(T t) {
{t.Serialize(Arc... | This is not the correct syntax. In the requires-expression, the expression in each compound requirement { expression } -> requirement; should be a valid expression, not just a "syntax description". You probably want something more like this:
template<typename T>
concept Serializable = requires(T t, Archiver a) {
{t... |
65,023,497 | 65,023,934 | Are there completely-generic objects in C++ like in JavaScript? | I'm new to C++, but with some experience in Javascript.
In JavaScript, when I write:
var object = {};
I create an object that is "completely generic" in the sense that it has no members/features, but it can have any member we like by adding that member later.
Can I create or simulate the this kind of an object in C++?... | The answer is mostly-no, you can't.. In JavaScript, Object's can be likened to a dictionary or map from keys to typed values, with both the values and their types settable at run-time.
You can create a dictionary of arbitrary-typed values in C++, using the type-erasure capability of std::any, and strings for keys. With... |
65,023,713 | 65,024,950 | C++ libraries not linking against object files (G++) | Whenever I try linking GLEW against an object file, I get this error:
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: Buffer.o:Buffer.cpp:(.text+0x1d): undefined reference to `_imp____glewGenBuffers'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: Buffer.o:Buffer.cpp:(.text+0... | GLEW_STATIC is used by the pre-processor to determine how to pre-define the functions from the glew API so you need to supply it when compiling the buffer object. Alternatively you could add '#define GLEW_STATIC' in the file that includes glew.h before glew.h is included and you wouldn't need to pass it as an argument ... |
65,023,744 | 65,023,949 | C6001 on using the address of uninitialized value. Why? | This here is my C++ code:
void somefn(char* string){
char *current, *next;
current = strtok_s(string, "a", &next); // next is unitialized -> C6001 in VS 2020
}
int main(){
char buf[] = "foobar";
return 0;
}
which is deemed warning-worthy by a certain compiler with certain flags (should not matter, I ... | The reference documentation for strtok_s shows that the above code is perfectly valid assuming that string is not a NULL pointer. Whether "an address of an uninitialized variable is a compile-time constant" is completely irrelevant and doesn't have anything to do with the diagnostic. The compiler thinks you are using u... |
65,024,442 | 65,149,283 | A QMap esque container that allows for duplicate keys and preserves their insertion order | I have a UI with dynamically created Custom widgets.
Each custom widget has 2 QLineEdits from which user input has to be parsed.
Information from a each one of these Custom Widgets through its 2 QLineEdits has to be read and processed within my application.
Each CustomWidget directs one specific action of a machine for... | Is your goal to have faster-than-O(n) lookup and insertion times? If not, then your QVector solution seems to work pretty well, perhaps just make it a private implementation detail of your own container class, create a pretty public API for the rest of your code to call it with, and then use that.
|
65,024,567 | 65,024,896 | passing static const attribute of class to a function | for an arduino school project where I draw bitmaps to a screen, I want to store said bitmaps as unsigned char arrays in classes.
Currently I'm doing it like this:
class Actor{
public:
static constexpr unsigned char sprite[8] = {0x97, 0xd5, 0xb7, 0x00, 0xe0, 0x4a, 0x44, 0x4a};
};
void setup() {
Actor a;
u8g2... | Notice, you're getting a linker error, not a compile time error. Everything is fine as far as compilation goes, but you have not done quite enough to satisfy the entire toolchain. The issue is, you never gave a definition for the variable, and the linker fails to find it when it brings everything together.
This issue... |
65,025,585 | 65,025,708 | Access method's parameter with dll injection | I have a 64bit process, I figured out one of its statically linked library methods.
Source of this method:
int SSL_connect(SSL *s)
{
if (s->handshake_func == 0)
/* Not properly initialized yet */
SSL_set_connect_state(s);
return (s->method->ssl_connect(s));
}
Actual assembly image: click here.... | If you can find out the address of the SSL_connect function you can detour it. This means that you can write a JMP instruction at the begin of the method to your patched-method.
If your jumped-to method has the same calling convention and signature you can simply access SSL* and do what you want with it afterwards you ... |
65,025,739 | 65,026,352 | template constexpr endian converter (without UB) | I have seen some other answers that propose to use unions for byte swapping (which is UB or can't be done at compile time).
I've wrote mine, and it kind of worked until I have met some case which have shown that my implementation is invalid. I can't spot a mistake, can you help me?
namespace impl
{
... | You are ignoring the third argument passed into the recurrent overload of bitwise_or through the res parameter. It seem to work if
return bitwise_or(tag_s<i - 1>(), original,
original << i * 8 >> sz_minus_one * 8 << i * 8);
is changed to:
return bitwise_or(tag_s<i - 1>(), original,
res | original << i * 8 >> sz_mi... |
65,025,812 | 65,025,942 | C++: does std::invoke need perfect forwarding? | Snippet
template <typename CallableType, typename... Args>
auto invokeTest(CallableType&& fn, Args&&... args)
{
return std::invoke(fn, std::forward<Args>(args)...);
}
Is std::forward<Args> needed here?
Or is it enough to write
template <typename CallableType, typename... Args>
auto invokeTest(CallableType&& fn, Ar... | Well, I'd say yes but it depends on the case.
You don't need forwarding in that case:
void bar(int);
int main() {
int i = 0;
invokeTest(bar, i);
}
But, you'll need forwarding for this case:
void foo(std::unique_ptr<int>);
int main() {
auto p = std::make_unique<int>();
invokeTest(foo, p); // Won't wor... |
65,026,407 | 65,026,504 | Does a class string always gets initialized to empty? | I have this string s and t in class.
class A
{
private:
static string s;
string t;
public:
void printString()
{
cout<<s<<t<<endl;
}
};
I tried printing these string and everytime they were empty if not initialized. So my question is whether a class string is always empty before init... | In both cases, the default string constructor will be called. The default constructor for the std::string class will always initialize it to an empty string.
|
65,026,710 | 65,026,823 | "index "8" is out of valid range ' 0 to 1' for possibly stack overloaded array". How would I fix this? | This is the function, what seems to not be working is probably some syntax that I got wrong in relation to making the array. It also says something about readable bytes being 8 but that 12 may read.
int sum = 0;
std::string total;
std::string space = " ";
cout << "Enter numbers:\n";
int array[2] = { 0, 0 };
int i;
... | You can use std::size(array) since C++17. This returns N, the count of elements in C++ array declared as T array[N]. To get std::size you need to include the header file of any C++ standard container, for example #include <array>. See std::size
|
65,027,043 | 65,040,306 | Passing a std::shared_ptr<T> to a function that takes a std::shared_ptr<const T>? | I have a function that needs to take shared ownership of an argument, but does not modify it.
I have made the argument a shared_ptr<const T> to clearly convey this intent.
template <typename T>
void func(std::shared_ptr<const T> ptr){}
I would like to call this function with a shared_ptr to a non-const T. For example:... | Thanks for the replies.
I ended up solving this a slightly different way. I changed the function parameter to just a shared_ptr to any T so that it would allow const types, then I used std::enable_if to restrict the template to types that I care about. (In my case vector<T> and const vector<T>)
The call sites don't nee... |
65,027,049 | 65,027,196 | std::algorithm to make this more expressive | I'm working on my own blockchain implementation in C++17.
To learn as much as possible, I would like to reduce loops as least as possible, moving to the alternative (and more expressive) loops within the std::algorithm library.
In a nullshell, within the Blockchain algorithm, each block contains it's own hash and the h... | If you have some range v where you want to check each adjacent element for some condition, and return early, you can use std::adjacent_find.
First write a lambda that compares adjacent elements:
auto comp = [](auto left, auto right)
{
return // the Negation of the actual condition
}
Note that the negation is needed,... |
65,027,103 | 67,499,703 | NVM Storage Simulator in Linux/C++ | I am currently working on porting a project to run on Linux, which was storing some data in a NVM external storage. On my hardware I only have at my disposal an eMMC main storage where the Linux rootfs lays. What I would like to do is to simulate the previous NVM external storage in Linux so that my application can sto... | Ended up opening/creating a file on the file system
memFileFd = open(memFilePath.c_str(), O_RDWR | O_CREAT, (mode_t)0600);
Expanding the file to the desired size
// go to the end of the desired size
lseek(memFileFd, memSize, SEEK_SET);
// write termination character to expand it
write(memFileFd, "", 1);
Map the memo... |
65,027,336 | 65,028,151 | How to update multiple fields of a struct simultaneously? | Let's say I have a struct
struct Vector3 {
float x;
float y;
float z;
};
Note that sizeof(Vector3) must remain the same.
EDIT: I am interested in solutions without setters.
Not let's create an instance of that struct Vector3 pos . How can I implement my struct so I can have something like this pos.xy = 10... | Since your type is standard-layout, I think the only legal way to do this, as per the C++ standard, is with a union that contains sub-objects with custom operator= definitions.
With a union, you're allowed to view the common-initial sequence of the active member, provided all types are standard-layout types. So if we c... |
65,027,410 | 65,027,908 | C++ ignore \x inside string, how to make it plain text? | i have a problem with \x inside a string.
how can i make that sprintf_s just accept the single \x (taking it as plain text?, compiler doesnt accept only "\x") with the following code my const char* have a double backslash inside...
sprintf_s(buf, "\\x%02X")
; -> output is \\0xA0, should be only \xA0
thanks
| The Visual Studio debugger on displays the backslashes so there is no ambiguity about what you have escaped. If you copy the value you will have it quoted. If you insert a quote, it will be backslashed in the debugger display.
"\\x7B\""
The two outer quotes are to show the containment of the value. That would show in ... |
65,027,474 | 65,027,504 | 'Use of class template requires template arguments' error with default specified non-type template parameter value | Compiling this:
#include <iostream>
#include <memory>
template <auto val = 42>
struct A
{
A()
{
std::cerr << val << "\n";
}
};
int main(int argc, const char* argv[])
{
std::shared_ptr<A> a_ptr {new A {}};
return 0;
}
gives error: use of class template 'A' requires template arguments. Al... | It's still a template, and it still requires < and >:
std::shared_ptr<A<>> a_ptr {new A<> {}};
Think about this. If you have a function with a default parameter:
int foo(int baz=42);
Do you think you can simply call it without the parenthesis?
int foobar=foo;
Of course not, this won't work. You still need the parent... |
65,027,548 | 65,027,611 | Write Binary file from char buffer on linux | So i am new to linux programming on C++ and i am trying to write the contents of a binary file (.dll, .exe etc) to a .txt to test and see the results of the operation, the code works and writes the .txt file and some of the binary into it, but when i open the .txt file there is not the full binary writed inside and the... | log_file.write(text, sizeof(text));
sizeof is a compile time constant that gives you the size of the object. text is a char *, so this gives you a grand total of 4 or 8, depending on whether you compiled a 32bit or a 64bit binary. It doesn't matter whether text points to just a few bytes, or the entire contents of "H... |
65,027,692 | 65,027,771 | How to suballocate buffers in Vulkan | A recommended approach for memory management in Vulkan is sub-allocation of buffers, for instance see the image below.
I'm trying to implement "the good" approach. I have a system in place that can tell me where within a Memory Allocation is available, so I can bind a sub area of a single large buffer.
However, I can't... |
are the dotted rectangles in the image below just bindings, or are they additional buffers?
They represent the actual data. So the "Index" block is the range of storage that contains vertex indices.
if they are bindings, how do I tell Vulkan (ideally using VMA) to use that subsection of the buffer?
That depends on ... |
65,027,806 | 65,028,495 | cannot create std::vector larger than max_size() for size below max_size | I am running google benchmark for some basic cache testing and I get the following error:
terminate called after throwing an instance of 'std::length_error'
what(): cannot create std::vector larger than max_size()
However, I am printing the max_size and the actual size (see below) and while the max_size equals 2^60-... | The issue here was that the type of bytes was an int.
auto const bytes = (2 << state.range(0)) * 1024;
changing to
auto const bytes = (2 << state.range(0)) * 1024L;
changes it to a long allowing for longer vectors and even better better unsigned long long:
auto const bytes = (2 << state.range(0)) * 1024ULL;
|
65,027,945 | 65,028,043 | My program is working properly but still at the end its showing Segmentation fault |
gdb already Tried :0
void Reverse(struct Array *arr)
{
int i, j;
for (i = 0, j = arr->length - 1; i < j; i++, j--)
{
swap(&arr->arr[i], &arr->arr[j]);
}
}
void Reverse2(struct Array *obj)
{
int *b;
int i, j;
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
... | Your code allocates a single integer, but then treats that integer as an array. Here
b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
should be
b = new int[obj->length];
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
b[j] = obj->arr[i];
|
65,028,303 | 65,052,538 | Pin window to desktop / Glue window to desktop / "Always-on-bottom" window | I'm working on a basic desktop app in C++ / Win32.
My goal right now is to create a basic "sticky note" app that would be pinned / glued to the desktop, i.e always in front of the desktop but always behind of any other application.
Really a personal project there, just to fight my bad memory and have my tasks/notes alw... | As @JonathanPotter pointed out, when hitting Windows + D or the Show Desktop button, the event WM_WINDOWPOSCHANGING gets fired, and the window gets moved to -32 000, -32 000 (its size also gets changed)
NOTE : a window without the style WS_MINIMIZEBOX seems not receiving WINDOWPOSCHANGING event when hitting Windows + D... |
65,028,818 | 65,028,984 | Problem with "No matching constructor for initialization of 'LM35' in "main.cpp", Line: 16, Col: 27" | I'm a student, learning about MBEDs. I'm using Nucleo board and the MBED online compiler.
Here's my code:
LM35.h
#ifndef MBED_LM35
#define MBED_LM35
#include "mbed.h"
class LM35
{
public:
LM35(PinName pin);
void mjerenje();
private:
AnalogIn _pin;
};
#endif
LM35.cpp
#incl... | in LM35.cpp
void LM35::mjerenje()
return a float value, should be -->
float LM35::mjerenje()
in the main.cpp
float temperatura2;
temperatura2 = senzor.mjerenje();
|
65,028,992 | 65,029,051 | How to understand the instructions of an istream function? | I am writing a function to the stream and am on the read function to the istream. My ostream function looks like this:
ostream& Time:: write(ostream& ostr)const {
int hour;
int minutes;
hour = m_min / 60;
minutes = m_min % 60;
// Time::write(ostr);
ostr << setfill('0') << setw(2)... | No; your squashed two steps into one, and are therefore missing one read.
The instructions say:
reads the integer for the hours using istr
reads one character and makes sure it is ':'
Instead, you did this:
reads the integer for the hours using istr and makes sure it is ':'
You'll need to introduce another read... |
65,029,749 | 65,029,834 | Is it possible to mimic polymorphism using concepts with c++20? | The question is pretty much given in the titel. Please considere the following godbolted code:
#include <iostream>
struct Base{};
struct Derived : Base{};
template<typename T>
concept IsDerivedFromBase = std::same_as<T, Base>;
template<typename T>
concept IsNotDerivedFromBase = not IsDerivedFromBase<T>;
template <I... | Everything concept-related is determined and "worked out" at compile time. Setting aside SFINAE for the moment: a failed concept requirement results in an ill-formed program and a compilation failure.
On the other hand, the only part of C++ that could possibly "know" that your c does not "really" point to Base is dynam... |
65,029,968 | 65,030,025 | C++ - Get typename of a template where that class is used as another template | I would like to get the typename of a class template from another class that use a tamplate based on the first class.
I have wrote a class like so:
template<typename T>
class class_a {
...
}
I would like to do something that:
template<class class_a>
class class_b {
std::vector<class_a.T> arr;
...
}
| The easiest way to do this is to have your templates "cooperate" with each other, and for class_a to "help" the other template:
template<typename T>
class class_a {
public:
typename T type_t;
};
And then:
template<class class_a>
class class_b {
std::vector<typename class_a::type_t> arr;
...
};
You will find t... |
65,030,315 | 65,030,386 | What is the different between +[](){}; and (+[](){}); and why the expression is valid | As the title stated. The code is compiled using GNU c++2a
int main(){
(+[](){});
return 0;
}
Compiles fine.
However, the following code generates warning: value computed is not used [-Wunused-value]
int main(){
+[](){};
return 0;
}
Further question is: my understanding about the expression [](){} is, it retur... |
{} is, it returns an r-value object std::function<void()>
No, it creates a lambda/closure which is its own kind of thing. There are cases when that is turned into a std::function, but what you're actually getting is much more similar to a functor (a class that implements operator()) than a std::function - which is ... |
65,030,337 | 65,030,422 | C++ not waiting for an input | so I have been learning C++ and was working on a monkey see monkey do program and i managed to get the first input working but the second input it just skips straight over it, i have no clue why and any help would be apreciated.
#include <iostream>
#include <string>
using namespace std;
char monkey_1;
char monkey_2;
i... | Do you intent to only get a single character from the input as the monkeys are of type char? If not, change them to string, otherwise it will only assign a single character per cin.
If you want to input a sentence, cin also splits on spaces, so if you enter "something else", the first cin will assign something to monke... |
65,030,391 | 65,037,540 | How to build and link Boost.Serialization on MacOS | I'm building a client-server application in C++ using Boost, a colleague of mine is coding the server in Ubuntu and he's using Boost.Serialization but I'm unable to run it because it doesn't find that library, besides I also need the library for the client. To build and link it to the project he's only created a CMAKE ... | Unfortunately, it seems that Homebrew only installs header libraries of Boost. To me, the easiest way to install everything was downloading the complete Boost archive from their website and then follow the instructions from here https://www.boost.org/doc/libs/1_74_0/more/getting_started/unix-variants.html#prepare-to-us... |
65,030,702 | 65,032,098 | How to get Modules to work in VS2019 16.8? | I'm trying to convert my program to modules. I'm using MSVS 19 Community Edition version 16.8 (also tried with MSVS19CE Version 16.9.01 Preview)
Each .ixx IDF I write compiles fine when compiled indiviually, (with "import"'s and its usage commented out),
Build started...
1>------ Build started: Project: myCare, Configu... | This seems to be a bug with the way visual studio currently handles modules imported by other modules. Essentially when each module compiles it creates a <module_file_name>.ixx.ifc file. This is detected perfectly fine when the module is imported into a cpp file but not when importing to a module. removing the .ixx fro... |
65,031,144 | 65,031,749 | Change a text color for the checkbox after mouse click | I am using win32 API (not MFC).
I have a dialog with a checkbox. I want to change the color of the checkbox label.
case WM_COMMAND:
if (LOWORD(wParam) == IDC_CHECKBOX)
{
HWND hCheck = GetDlgItem(hDlg, LOWORD(wParam));
bool checked = (int)SendMessage(hCheck, BM_GETCHECK, 0, 0);
... | You can use WM_CTLCOLORSTATIC to change the color of the checkbox label.
Some code:
bool checked;
HWND hCheck = CreateWindowEx(0, L"BUTTON", L"text", WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, 150, 100, 60, 20, hWnd, (HMENU)IDC_CHECKBOX, (HINSTANCE)GetWindowLong(hWnd, GWLP_HINSTANCE), NULL);
...
case WM_COMMAND:
{
i... |
65,031,216 | 65,031,264 | Can anyone explain to me how do default argument values work in recursive functions in C++? | int factorial ( int n, int a = 1 ) {
if ( n == 0 ) return a;
return factorial ( n-1, a * n );
}
This is a recursive function that calculates factorial of n. I know and fully understand recursive functions, but I do not understand how do these recursive functions with default arguments such as "int a=1" work. For exa... | factorial(3) -> "here a is implicitly considered as 1"
factorial(2, 1 * 3) ->
factorial(1, 3 * 2) ->
factorial(0, 6 * 1)->
return(6) "this is a case where n ==0"
|
65,031,827 | 65,031,865 | Can I use smart pointer with a mutex member? | Say I have a dynamic allocated object foo which have a std::mutex member:
#include <mutex>
#include <memory>
class foo {
public:
foo()=default;
~foo();
private:
std::mutex lock;
};
int main(){
std::unique_ptr<foo> a = std::make_unique<foo>(foo());
return 0;
}
I've tried to use... | You're constructing a temporary object by foo() and passing it to std::make_unique(). std::make_unique() will construct the managed object from the temporary foo, but foo is not copyable nor moveable.
To get a std::unique_ptr managing a default-constructed foo, you can just omit the temporary object:
std::unique_ptr<fo... |
65,033,279 | 65,033,650 | How can third-party libraries do things that the standard library can't do? | I read on multiple StackOverflow answers that C and C++ do not have graphics libraries as part of its Standard Library, then how do third party libraries implement Graphical User Interface?
Suppose I am a developer who wants to create a library that can draw shapes on the screen, how do I even make such a library witho... |
How can third-party libraries do things that the standard library can't do?
At the lowest level, they use APIs provided by the operating system.
In most cases, there is typically a stack of libraries with increasing levels of abstraction. On top of operating system API, there is often a system libraries (such as glib... |
65,033,687 | 65,034,646 | C++ 17: Deduce signature from Callable in a template | If and how is it possible to deduce the signature type from any callable in C++17?
Snippet:
template <typename T>
struct MyFunction;
template <typename R, typename... Args>
struct MyFunction<R(Args...)>
{
};
template <typename Callable>
auto deduceSignature(Callable&& c)
{
// using Signature = ???;
// return ... | std::function can be constructed from any callable, and can deduce the signature (since c++17). We can use this to make a type trait that extracts the signature.
#include <functional>
template <typename T>
struct get_signature;
template <typename R, typename... Args>
struct get_signature<std::function<R(Args...)>> {
... |
65,034,630 | 65,698,937 | Parsing ID3v2 from char* buffer using TagLib | I have a set of audio files (DSDIFF, specification) to which somebody appended an ID3v2 tag. This does not conform to the file's standard, and thus standard ID3v2 parsers (like TagLib) don't recognize the audio file and refuse to parse it. (Why doing non-standard stuff like this seemed like a good idea is beyond me.)
I... | AmigoJack got me on the right track to figuring out a solution. While TagLib::File is an abstract class and can't be instantiated directly, one of the existing file-format specific parsers can be used. It is possible to create a file that only contains the ID3 tag and use the MPEG parser to read it.
Here is the relevan... |
65,034,684 | 65,035,403 | How can I get a two-dimension array that stored in an one-dimension array through overload the function call operator in C++? | I'm writing a small scientific computational library in my free time. And I found some people said that store a two dimension array in an one dimension array is faster and you can do it by overloading the function-all operator. But I don't know how to deal with it.
Now I think the function array should do that:
#includ... | Ok, I shall admit that you want to write a scientific computing library and that (low level) optimization will matter. It is the only reason for me not to just say: do not worry with low level arrays and only use vectors of vectors [of vectors...]
But VLA arrays are not a C++ thing. It is a (documented) gcc extension, ... |
65,034,952 | 65,072,105 | C++: define a function alias which is not a function pointer | I want to write a small LD_PRELOAD library to intercept and log X11 calls (X11 is not significant here: choose any other library you'd like to log calls to). I would like to design a macro GEN_WRAPPER that automatically creates the wrapper for a certain call. This is my current attempt:
#include <iostream>
#include <X1... | For lack of a better answer, I came up with the following solution, which is compiler, architecture and ABI dependent, but gets the job done in my case.
#if defined(__i386__)
#define JUMP_EAX "jmp *%eax"
#elif defined(__x86_64__)
#define JUMP_EAX "jmp *%rax"
#else
#error "Architecture unsupported"
#endif
#define GEN_W... |
65,034,985 | 65,035,116 | lower_bound and upper_bound in Map of Pairs | I am trying to understand the lower_bound and upper_bound in map of pairs from here.
The definitions are like below:
lower_bound:
In map of pairs lower_bound() for pair(x, y) will return an iterator pointing to the pair whose first value is greater than or equals x and second value is greater than or equals to y.
If th... | You are storing this by key value in an ordered map. The ordering of the maps' keys will be as follows:
<2, 3> | <2, 5> | <5, 0> | <7, 1> | <9, 3>
See here.
So, the actual std::map::upper_bound reference says the following:
iterator upper_bound( const Key& key );
Returns an iterator pointing to the first element tha... |
65,035,175 | 65,035,385 | Making some kind of reference to objects stored in a vector | I have an std::vector<std::unique_ptr<SomeClass>> variable inside a private section of a class. Other parts of the program uses the methods of that class to add elements to the vector. It works, but now I have got a new requirement to allow users of the class remove some elements from the vector as well.
My problem is:... | Easy and fast solution:
Change std::vector<X>, to std::map<int, X> or std::unordered_map<int, X>
When adding element generate unique id and return it to user. Add element using id as key in map
When user want to access/delete element he should provde id
|
65,035,189 | 65,035,421 | Whether to pass shared pointer or raw pointer to a function | Situation
Some third-party API I use works with raw pointers, but I have smart pointers all over my client code.
Problem
When I want to write a wrapper function around the API, I face a problem: Whether to pass shared pointers or their raw pointers underneath as arguments.
Like this:
The smart pointer version
// my wr... | I would suggest the following approach to looking at code something like this:
There are some other options like weak_ptr, but for this it is probably not worth looking at.
So for your example, we can see that ThirdParty_DoStuff does not take ownership, so we won't either, so you can choose between a reference and a p... |
65,035,356 | 65,035,858 | g++ and clang++ give different results on list initialization | This issue got started while experimenting on a class derived from std::tuple in order to reuse tuple's comparison operators.
The code below is supposed to remove duplicates from lists of 2D or 3D coordinates.
In the beginning of the main function, lines 49 and 50, there are two vectors v2 and v3 initialized with initi... | The problem is with copy ctor. Since user provided copy ctor is absent, compiler default is generated; this copies references from sources that are no more valid. You need copy/move ctors that explicitly initialize those references:
Point2D::Point2D(Point2D const& p)
: P{p}
, x{get<0>(*this)}
, y{get<1>(... |
65,035,750 | 65,043,369 | Cmake Generator expressions with multiple entries (spaces?) | (During writing this question I found a solution, so this just documents it, because I would really have needed it beforehand!)
Im writing a c++ project and use cmake for it.
In my cmake file I have:
set(MY_DEBUG_WARNINGS "-Og -Wall"
)
# Add warnings:
add_compile_options("$<$<CONFIG:DEBUG>:${MY_DEBUG_WARNINGS}>"
"$<$<... | "-Og -Wall" is a string, whereas "-Og;-Wall" is a list (as lists are semicolon separated strings).
So set(my_list -Og -Wall) (no double quotes) also creates a list. Read all about it here.
|
65,036,107 | 65,423,922 | IOPCShutdown::Advise Failed : error 80040202 | I broke my head while looking for the cause of this error (4 days)
I have an OPC DA server running in a remote machine.
The OPC DA client is located in another machine.
in the client implementation I create an external instance via CoCreateInstanceEx()
HRESULT result = ::CoCreateInstanceEx(clsid, NULL, clsctx, sinptr... | It works when I change the authentification level of my OPC DA server in DCOM Config from "Connect" to "None", I don't know why but it works ^^
|
65,036,113 | 65,036,254 | No appropriate default constructor available with template implementation in Cpp | I am trying to implement Stack by hand in C++. I want to use this implementation for many datatypes so that I've tried to implement it by using template in C++. Then I come to an error with my constructor of my Stack class.
Here is my code
#include<iostream>
#include<string>
using namespace std;
template <class T>
cla... | The Stack class should not inherit Node class, it should compose it, you should delete the inheritance relation from stack class, it should look like this:
template <class T>
class Stack
|
65,036,361 | 65,036,418 | Initialize std::vector in a struct | I have a struct with 2 std::vectors as given below. I want to initialize the vector with 2048 elements having initial value 0.0.
struct PixelMaps
{
vector<double> pixelMapX;
vector<double> pixelMapY;
};
I tried the following code. This creates the vector of 2 elements only. How can I initialize the structure w... | std::vector has a constructor using std::initializer_list, so you can't use brace-init-list - it will always end up in that constructor. You need more explicit initialization:
PixelMaps test{ std::vector(2048,0.0), std::vector(2048, 0.0) };
Or (pre C++17)
PixelMaps test{ std::vector<double>(2048,0.0), std::vector<doub... |
65,036,858 | 65,036,948 | (C++) How do you Display a 2D Array with both Char and Int Values? | #include<iostream>
using namespace std;
int main()
{
string display[2][3] = {{"Name","Geometry","English"},{"Larry",90,85}}; //problem is here
for(int row=0;row<2;row++){
for(int col=0;col<3;col++){
cout<<display[row][col]<<" ";
}
cout<<endl;
}
}
//[Error] invalid c... | You can only have array of only one type. In your case array of strings. So if you want to put your integers into this array you can use:
std::to_string(some_int);
so it will be:
string display[2][3] = {{"Name","Geometry","English"},{"Larry",std::to_string(90),std::to_string(85)}}; //problem is here
|
65,036,966 | 65,037,020 | Here in line 81 there is an error that I need to remove by making changes in the class | The error is in line 81 under "str4.length()" that I need to remove. I cannot change a single word of main but I can alter the Class. I am not sure why this is occurring. The function length is supposed to be outside the class as it can be seen how it is being called. But not working with this "const MyString str4;"
Pl... | You cannot call a non-const method on a const instance. Thats the whole point of declaring an isntance as const. A non-const method is allowed to modify (observable) state of the instance, but a const instance is constant.
By default you should declare methods that need not modify members of this as const:
class MyStri... |
65,037,104 | 65,037,461 | grid not showing (it is all black) | I didn't want to go back to the same question from yesterday, however before I am able to use the function to turn on and off the grid, I first need to know if my grid is actually working, I have been making new projects all night trying to display the grid but it isn't showing, the screen is always black and nothing i... | The variables w and h a re not initialized. Initialize the variables by 1:
int w = 1;
int h = 1;
However, if you want to set the vertex coordinates in window space, you have to change the orthographic projection. The projection matrix defines the area (volume) with respect to the observer (viewer) which is projected ... |
65,037,142 | 65,037,402 | How do I make PlaySound load only some parts of the song C++ | I have a 424 mb wav file, which I want to play, but it takes a lot of time to load, and it uses 425.6 mb of ram. Way too much ram for a dos format program. I want to load only a part of the song, then when it's almost at the final, load the second part, when the second part is played, remove from ram the first part, an... | PlaySound is a fairly high-level function, so it's tricky to get behavior like this. In particular, you will likely experience small silent gaps between playing back the different parts. So the best solution would be to go to a lower-level API that allows more sophisticated managing of sound playback buffers. OpenAL is... |
65,037,535 | 65,038,290 | How to access member elements of a std::queue data structure? | Coding in C+, using Visual Studio 2019, I have a structure defined. I am creating a queue of that data structure and have pushed 2 elements into the queue. Now the question is how to access the members of the structure elements inside the queue?? Any guidance is appreciated!
#include <iostream>
#include <sstream>
#inc... | I have modified your code to get it compiling and working: (Note: I have used C++17 standard using g++ to compile this code but it should work for visual studio 2019
#include <iostream>
#include <queue>
typedef struct _myqueuestruct
{
std::string name;
std::string citypin;
int employeeId;
}myqueuestruct;
... |
65,037,551 | 65,037,630 | How to make a constructor with std::initializer_list<double> | I'm currently learning about classes and constructors.
class Container
{
....
public:
// constructors
Container() {
length = 0;
data = nullptr;
print("default constructor");}
Container(int lenght){
data = new double[lenght];
}
// destructor
// operators
v... | Delegating is similar to using the member initializer list.
Example:
#include <algorithm> // std::copy
#include <initializer_list>
// ...
Container(std::initializer_list<double> il) :
Container(il.size()) // delegate to Container(int length)
{
std::copy(il.begin(), il.end(), data); /... |
65,037,779 | 65,038,099 | cast class object to struct object C/C++ | I have two projects one in C and the other in C++ and I try to cast a class object in C++ to a structure object in C. For example, I have an object from myClass which I'm trying to cast to myStru as follows:
In my C++ project I have this class:
class myClass{
myClass();
~myClass();
char *data;
int ... | I am not 100% sure, because it's C++ and you can never be, but I think this is undefined behaviour.
You cannot access the members of a struct via a pointer to a member to another struct. A notable exception of that rule involves accessing the common initial sequence of two structs that are members of a union.
This coul... |
65,038,032 | 65,038,403 | Convert hex string to character array in cpp | I have a hex string in cpp
std::string str = "fe800000000000000cd86d653903694b";
I want to convert it to a char array which stores it like this
unsigned char ch[16] = { 0xfe, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x0c, 0xd8, 0x6d, 0x65,
... | I'm not an expert in C++ and for sure there is something better, but since nobody is answering ...
#include <iostream>
int main()
{
std::string str = "fe800000000000000cd86d653903694b";
unsigned char ch[16];
for (size_t i = 0; i < str.length(); i += 2)
{
// Assign each pair converted to an i... |
65,038,159 | 65,038,211 | get second dimension of the array using std::extent | I'm trying to get the second dimension of a 2D array using std::extent, but getting output as 0.
#include <iostream>
#include <type_traits>
int32_t main(int32_t argc, char *argv[]) {
int32_t arr[10][100];
std::cout << "first dim: " << sizeof(arr) / sizeof(*arr) << std::endl;
std::cout << "second dim:... | To get the second dimension use this:
std::cout << "second dim: " << std::extent<decltype(arr),1>{} << std::endl;
// ^ second dimension !
|
65,038,715 | 65,038,772 | How to sort a two-part linked list using one variable in C++? | I am trying to create a linked list that lists the names of people and their birth years. This list should be sorted in ascending order by their birth years after the input is entered. So far, I've sorted the list by years, which is precisely what I want -- but I can't figure out how to move the names when the sorting ... | You should also swap name when you swap year.
You can use std::swap to swap variables without using temporary variables.
#include <algorithm>
void sort (node *head)
{
while (head)
{
node *min = head;
node *cur = head -> Next;
while (cur)
{
if ((min -> year) > (cur ->... |
65,039,316 | 65,039,548 | Cast between C++ class and C structure -- what to do with the destructor? | Is possible to cast between C++ class and C structure? (the use case here is that I have two different projects one in C++ and the other is in C and I have an interface to connect both projects)
I have tried some examples where both (a C++ class and a C structure) have the same member functions and member variables and... | One way is to not cast at all but to let the C++ class inherit from the C struct.
Example:
#include <iostream>
// #include "the_c_header.h"
class myClass : public myStru {
public:
myClass(int v) : myStru{v} {}
virtual ~myClass() = default;
};
class der : public myClass {
public:
using myClass::myClass;
... |
65,039,340 | 65,068,929 | Change Task Manger title for win32 console app | I am trying to change the name of my win32 console application in task manager. In c# console project I can set the AssemblyTitle in project file and it would work but for some reason when I can't achieve the same result here.
| First, right-click the Resource file to add a .rc file.
Then double-click the .rc file to enter the resource view, right-click the resource file and select Add Resource, and select Version.
In the VS_VERSION_INFO, you can modify the FileDescription to your application name (of course you can also modify other applica... |
65,039,577 | 65,039,617 | What's the accepted way to fill a QComboBox defined in QtQuick QML, from C++? | I want to populate a QComboBox defined in QML from my C++ code. I have seen two possible ways to do this:
Define a list (as a QStringList for example) from the C++ code, and expose it as Q_ELEMENT. Then access that list from the C++, by saying model: backend.qlist assuming the list is defined in backend. Or
Find the Q... | By far the first option!
QML stands for Qt Modeling Language, following the model-view architecture, in which the model (here C++) should not know anything about the view (QML).
|
65,039,723 | 65,040,474 | Calling a c++ function on Rstudio on a MAC and getting (clang: error: unsupported option '-fopenmp') | I know how to code but I really do not know my way around a computer.
I have a program that I have to run for my master thesis. It is a code with multiple collabs and runs perfectly on Linux. However, it is a very complex simulational code and therefore it takes time to run for multiple parameters. I've been using my L... | "Don't do it that way." Read up on R and Rcpp and use the proper tools (especially for packaging and/or compiling) which should pick up OpenMP where possible. In particular,
scan at least the Rcpp Introduction vignette
also look at the Rcpp Attributes vignette
"Just say no" to building the compilation commands by h... |
65,039,747 | 65,039,870 | I detected memory issues with valgrid in the constructors. How do I solve this? | Currently I'm learning about classes and constructors. I modified the following code. When I run the code with valgrid it gives the message that there are memory issues. I don't see where these come from.
#include <iostream>
class Container
{
...
public:
// constructors
Container() {
length = 0;
... |
You are missing the needed destructor to free the memory you manually allocated via new.
You are saving the length in a local variable int lenght = len;, where you probably want to save it in the class member length.
I.e. a minimal example would be:
#include <algorithm>
#include <iostream>
class Container
{
public... |
65,039,766 | 65,039,813 | Segmentation fault after 2-d array allocation | I have this code:
#include <iostream>
#include <math.h>
int main()
{
int n,m,k,hours;
std::cin >> n >> m >> k;
hours = std::ceil(n * k / (float)m);
int* checkers = new int[m];
int** check = new int*[hours];
for(int i(0); i < hours; i++)
check[i] = new int[n];
for(int i(0); i < n; i+... | You allocated m elements for checkers while using n elements.
The number of elements to allocate and use should be matched (allocate n elements or use m elements, according to what you want to do).
Also note that the contents of new int[n] are not automatically initialized, so you cannot rely on the value of check[0][0... |
65,039,858 | 65,112,492 | AWS CPP SDK JsonValue add array of double or Integer to JSON | i wanted to create a JSON using Aws-sdk for C++. this is what i am doing so far.
void convertStructToAwsJSON()
{
Aws::Utils::Json::JsonValue jsonValue = Aws::Utils::Json::JsonValue();
jsonValue.WithDouble("percentage", 93.6);
jsonValue.WithInteger("age", 25);
float grades[3] = {87, 95, 65};
jsonValu... | Alright got a response from the AWS SDK Team. It can be done like this:
Aws::Utils::Array<Aws::Utils::Json::JsonValue> grades(2);
Aws::Utils::Json::JsonValue value1;
Aws::Utils::Json::JsonValue value2;
grades[0] = value1.AsDouble(3.1416);
grades[1] = value2.AsDouble(164635242.4134452);
Source: https://github.com/aws/a... |
65,039,946 | 65,040,050 | Using converting constructor in multiple parameter case | I was looking at this video
CppCon 2018: Dan Saks “Making New Friends” please look here
I this talk, he refers to a (hypothetical) rational number class (which has
numerator and denominator as private members and all of the computation revolves
around this. I'm trying to implement whatever is mentioned in this talk jus... | Implicit conversion won't be considered in template argument deduction. Given 3*r3, template argument deduction for T based on the 1st function argument (i.e. 3) fails; the implicit conversion from int to rational<int> won't be considered.
Type deduction does not consider implicit conversions (other than type adjustme... |
65,040,345 | 65,050,290 | File readable but saved in binary mode | I wrote a very simple function that saves a file in binary mode with the support of qt. The file is saved correctly and the data inside is correct, however if I open the file with a text editor I can read strings that I shouldn't be reading.
void Game::saveRanking() const
{
QFile file(".ranking.dat");
file.open... | The toBinaryData() gives the internal representation data, not text, so it is normal you have binary data in the file.
QByteArray QJsonDocument::toBinaryData() const
From docs:
Returns a binary representation of the document.
Also it is deprecated:
This function is obsolete. It is provided to keep old source code ... |
65,040,455 | 65,040,482 | after setting a member variable value the value is changing inside getter function | I am trying to set two member variable which are float type and also succeed for one(which is nothing but directly assigned inside of a setter function). But another one need some calculation and with static_cast<float> I have configured it after calculation. For the second variable I have checked it inside of the sett... | The line
float res_value_b = static_cast<float>(set_value_b)/b;
is setting the value of not the member variable but a local variable.
Remove the first float to eliminate the local variable and have it set the member variable.
res_value_b = static_cast<float>(set_value_b)/b;
|
65,040,579 | 65,109,767 | QLibrary::load fails, but LD_LIBRARY_PATH just updated correctly before that, why? | I have a library (let's call it mydll.so) that is dependent to an external application, i.e. Matlab. To dynamically load mydll.so, I have written a code like this (Ubuntu, g++ 4.8.5, qt 5.12.6):
// update LD_LIBRARY_PATH with ALL required paths (Matlab, boost, etc.)
bool res = qputenv("LD_LIBRARY_PATH", required_path.t... | The problem is that you change the environment variable LD_LIBRARY_PATH from within the process. However the process still uses the "old" environment variables block with old values. As a result it cannot properly find the dependent libraries and eventually fails.
Therefore your approach will not work. I would propose ... |
65,040,817 | 65,040,860 | main.c:12:25: warning: format ‘%ld’ expects argument of type ‘long int’, | I'm getting this error when trying to compile my code...
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
void powRec(long int firstrNum, long int secondNum)
{
int n;
if (secondNum == 1)
;
{
printf("The result is %ld", firstrNum);
return;
}
n = firstr... | As the message says, you are invoking undefined behavior by passing data having wrong type to printf().
%ld expects long int, but the passed n is int. You should use %d instead of that to print int.
Another choice is changing the type of n to long int to match with the format specifier.
Also note that:
You should use ... |
65,040,909 | 65,041,478 | Minimizing stack allocation by way of temporaries in arithmetic operator overloads : Safe return method | I am working on an implementation of EDDSA digital signatures and as the values used in the calculations can be up to 521 bits in size (scalers) and points have three scalers (projective coordinates), passing values by copy are expensive in terms of stack space and argument copy. To eliminate as many copies as possible... | If you're returning by value from a function you don't have to worry about dangling references, as you're dealing with values and copies are made when necessary. So unless you're returning a reference, you don't have to worry. References passed as a parameter are invalidated at the end of the caller expression, so it... |
65,041,666 | 65,043,053 | Merge sort errors c++ | I'm very new to C++ and only coded in python before, but python is too slow for my purposes now. I did a mergesort algorithm in python and it worked. But now I translated it into C++ and I got a bunch of errors in my IDE. What are my errors?
#include <iostream>
using namespace std;
int *sort(int lenght, int lis[]) {
... | There are some major problems in your code:
comparisons must use == instead of =, which is the assignment operator.
the redundant definitions for buffd, add_l, add_r, prod_l and prod_r should me removed.
variable length array definitions such as int buffd[units] are not supported by many C++ compilers. These are exten... |
65,041,686 | 65,041,863 | Accepting std::array of char of any size as non type template parameter | This is probably a weird use case, but I am trying to hack around the fact string literals can not be used as arguments to templates using std::array<char, N> as non template type parameter.
This works but with extreme limitation that all strings must be of same length(I could use MAX_STR_LEN=100 or whatever and make a... | Sure, why not use a requires requires clause?
template <typename Type, auto val_val>
requires requires { { val_val.data() } -> std::same_as<char const*>; }
struct TypeToValues
{
// ...
Example.
You could also write a constraint that only specifically std::array<char, N> satisfy:
template<class> constexpr bool ... |
65,041,711 | 65,127,093 | Is an implementation required to diagnose ODR-violations of duplicated definitions of the same explicit specialization within the same TU? | Consider a templated entity, say (A) a function template, and (B) a member enum of a class template.
// (A)
template<auto>
int f();
// (B)
template <auto>
struct T { enum class E; };
Is an implementation required to diagnose ODR-violations due to duplicated definitions of the same explicit specialization of such a te... |
Is an implementation required to diagnose ODR-violations due to duplicated definitions of the same explicit specialization of such a template entity?
Yes.
Although [temp.spec]/5.2 specifies that multiple definitions of an explicit specialization in a program is ill-formed (whilst referring to [basic.def.odr]) NDR (no... |
65,041,826 | 65,042,763 | Why can't I print an vector's begin() iterator? | So, i am just learning vectors and i have 2 questions.
First question:
std::vector<int> c{1,2,3};
std::cout << c.begin();
I know that i should put a * before c.begin() to output the 1 ,but why does std::cout give me an error if i don't put the pointer sign? Shouldn't it simply output the address of the first element o... |
know that i should put '*' before c.begin() to output 1 ,but why does cout give me an error if i don't put the pointer sign?
Because the compiler doesn't know how to "print" a value of c.begin()'s type. But let's just read the error (GodBolt; using GCC), which is very important to do:
<source>:10:15: error: invalid o... |
65,042,357 | 65,042,509 | Simple Class with Constructor throws an warning: ISO C++ forbids converting a string constant to 'char*' | So I'm building a Regex class, with a simple constructor:
regex.hpp
#ifndef REGEX_CUSTOM_CLASS
#define REGEX_CUSTOM_CLASS
#include <stdio.h>
using namespace std;
class Regex
{
private:
/* data */
public:
char *regex;
Regex(char str[]);
};
#endif // REGEX_CUSTOM_CLASS
regex.cpp
#include <iostream>
#in... | You cannot pass arrays by value. When you write:
Regex::Regex(char str[])
this actually is
Regex::Regex(char* str)
Moreover string literals are of type const char [N] (where N is length of the string including the null terminator) and when passed to functions they decay to const char*. Getting a char* from a const ch... |
65,042,478 | 65,042,536 | value of a variable can't be stored | the compiler says this code has no error but when i enter students total, the value of jlh it isn't stored and it won't loop jlh times. how should i change the code?
using std::string;
int main(){
int jlh,x,y;
string abs;
char **mhs=new char*[100];
cout<<"enter students total: ";
cin>>jlh;
... | You must allocate place to store what are read before reading things:
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main(){
int jlh,x,y;
string abs;
char **mhs=new char*[100];
cout<<"enter students total: ";
cin>>jlh;
abs.resiz... |
65,042,717 | 65,042,845 | How to find element in vector from right to left | there is in standart library find function, but it searches first match from left to right, how I can find element from right to left with using standart library?
std::vector<T> values;
std::find(values.begin(), values.end(), x); // searching from left to right
| If I'm understanding your question correctly, you're trying to find not the first instance of a value in your vector, but the last?
std::find takes all kinds of iterators (so far as I'm aware), so you could use rbegin() and rend() to reverse iterate through your vector instead. That is:
std::vector<T> values;
auto it ... |
65,042,854 | 65,042,930 | Issue in accessing a structure inside a union in C++ | union hello
{
struct hi
{
uint8_t trees;
uint8_t plants[6];
};
uint8_t forest[1 + 6];
};
struct world
{
hello a;
};
typedef std::vector<world> universe;
universe alpha;
if I want to access the structure hi inside hello, then I am doing something like ... | the struct is not a field of union in your version; it's just nested type name. change it to this:
union hello
{
struct
{
uint8_t trees;
uint8_t plants[6];
} hi;/*<< put the field name here*/
uint8_t forest[1 + 6];
};
|
65,043,170 | 65,049,773 | Can't open a file inside a google test | I have a file in the same directory as the test.
Since I'm using Bazel as the build system (in Linux) I don't have to create the main and initialize the tests (In fact I don't know where the main function resides when using Bazel).
#include <string>
#include <fstream>
//Other include files
#include "gtest/gtest.h"
TES... | The problem is that the glob is relative to the BUILD file like when you refer a file in srcs. The glob is expanding to an empty list because no file is matching. The easiest way to see it is putting the full path explicitly instead of the glob and Bazel will complain.
You have two options, or you move the resources fo... |
65,043,592 | 65,049,073 | C++ - Creating Makefile on Windows | I have a project that make some processing on circular double linked List. I must use this project files in different directories and I made this project but I couldn't create a Makefile for Windows.
My success commands that I use on Command Prompt as shown below;
g++ -c src\Demo.cpp -o lib\Demo.o
g++ -c src\CircularDo... | I found the solution, we can easily use it similar to the Linux environment. I was confused looking at some samples.
makefile
ALL:
g++ -c src\Demo.cpp -o lib\Demo.o
g++ -c src\CircularDoubleLinkedListProcessor.cpp -o lib\CircularDoubleLinkedListProcessor.o
g++ -c src\CircularDoubleLinkedList.cpp -o lib\Circ... |
65,043,622 | 65,051,251 | Taking const pmr::vector<>& not propagating allocator when using conditional operator with rvalue | #include <iostream>
#include <vector>
#include <memory_resource>
class SpecialMemoryResource : public std::pmr::memory_resource
{
public:
void* do_allocate(std::size_t bytes, std::size_t alignment) override { return nullptr; }
void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) override {}
... | true ? vec : std::pmr::vector<int>{&k_SpecialMemoryResource} indeed creates a temporary object copy-initialized from vec:
[expr.cond]/2 If either the second or the third operand has type void... [doesn't apply]
3 Otherwise, if the second and third operand are glvalue bit-fields ... [doesn't apply]
4 Otherwise, if the ... |
65,043,766 | 65,076,433 | How to divide a number into 1-byte chunks to be sent through serial Bluetooth in C++? | I want to send a number through serial Bluetooth from an Arduino to an Android application.
I've managed to send 1 byte using the following code in C++:
int number = 255;
SerialBT.write((uint8_t*)&number,1);
SerialBT.flush();
This works fine, but since Arduino won't admit int16 or any other pointer bigger th... | Something like this:
uint16_t number = 1000;
uint8_t lByte = number & 0b11111111;
uint8_t hByte = number >> 8;
There are also lowByte() and highByte() functions available, but I don't know their exact behaviour.
But why not use SerialBT.print() or SerialBT.println() and convert what you receive into a number?
|
65,043,956 | 65,043,990 | Why do I get a "no operator found" error when overriding the stream insertion operator in this situation? | I have a project with multiple header and source files, which I have shortened to what I believe is important here (though I could be wrong). They look like so:
A.hpp:
#pragma once
struct date_t {
unsigned int day{ 0 };
unsigned int month{ 0 };
unsigned int year{ 0 };
};
A.cpp:
#include <iostream>
#include... | You have defined operator<< in A.cpp but you need to declare it in a header file too, so code in other cpp files knows about it.
Just add
std::ostream& operator<<(std::ostream& output, const date_t& date);
to A.hpp (after the definition of struct date_t). You will need to add #include <iostream> to A.hpp as well.
Do t... |
65,044,085 | 65,044,105 | Using ++ as a prefix to a statement of access through class member not causing an error | I am kind of confused right now, I was running the following code:
std::vector<int> test{1, 5, 10};
++test.at(1); // I'm trying to increment that number 5 to six, which works
std::cout << test.at(1) << std::endl; // Prints out 6 to the console
I was expecting it to give me a compiler error because as I had read from a... | True, postfix increment (a++) and member access (.) have the same precedence.
But you're using prefix increment (++a).
Consult cppreference's precedence chart.
Indeed, test++.at(i) would error for the reasons you give, though as readers of the code we would not be in any way surprised in that case.
|
65,044,319 | 65,048,426 | Pythran "undefined reference to `ATL_caxpby'" error | I've installed pythran as per instruction:
sudo apt-get install libatlas-base-dev
sudo apt-get install python-dev python-ply python-networkx python-numpy
pip install pythran
I have pythran==0.9.7, gast==0.4.0, g++==5.5.0, ubuntu 16.04
Trying to run pythran dprod.py (same file as in their tutorial) throws an error whic... | CFLAGS="-lblas" pythran dprod.py worked.
|
65,045,221 | 65,052,997 | Python.h: No such file or directory, when implementing python into c++, using CLion | I have used "apt-cyg install python3-devel" on my Cygwin terminal.
I have included directories in CMake...
include_directories(C:/Users/{my_user_name}/anaconda3/include)
and importantly in my main.cpp
#include <Python.h>
and have tried "Python.h", and "fullpath/Python.h".
I get back the error "fatal error: Python.h: ... | There are several versions of Python.h, every one for its Cygwin python package
$ cygcheck -l python38-devel|grep Python.h
/usr/include/python3.8/Python.h
$ cygcheck -l python36-devel|grep Python.h
/usr/include/python3.6m/Python.h
Anaconda is NOT a Cygwin python, so mixing will not work well.
apt-cyg is not the stand... |
65,045,789 | 65,045,843 | How to sum up values of occuring chars from a string, make them pairs and sort them in ascending order? | My task is to write a function that gets a vector of strings as an argument, and returns a vector of pair<char,int> containing pairs representing characters and their frequency (how much times the letter has appeared) summed up from all strings passed in vector as an argument of the function. It should also be sorted i... | First you can calculate all the frequency counts with a std::map:
std::map<char,int> m;
for(auto c : vec | std::views::join) // for every char in all strings
m[c]++;
Then you can copy this map into a vector as needed:
vector<pair<char, int>> res;
std::ranges::copy(m, std::back_inserter(res));
And finally... |
65,046,356 | 65,048,274 | Color mouse movement | I am currently working on a GUI Project with Qt C++. A part of my work consists of tracking the mouse movement and marking its position with a green pixel. The tracking should occur only on a certain image, which is stored in a label.
So far, the tracking of the mouse has worked fine and I have been able to extract the... | Where does your image variable come from? It doesn't have the correct contents. You were probably setting some image on the label, but instead you should set that image on the image member variable, and use that to set on the label.
|
65,046,657 | 65,067,732 | NetUserChangePassword() can set a password to Administrator? | When you enable Administrator user to login, the password is empty by default. At least on Windows 10, if you want login in a remote computer (via RDP) with Administrator user, must set a password before.
NetUserChangePassword() will be successful to this? considering that usually remote computer have only 2 users (alr... | Yes, you can use NetUserSetInfo to set the administrator password locally.
Members of the Administrators local group can set any modifiable user
account elements. All users can set the usri2_country_code member of
the USER_INFO_2 structure (and the usri1024_country_code member of the
USER_INFO_1024 structure) for thei... |
65,047,031 | 65,050,854 | C++ import-keyword, module-keyword and, export-keyword | Introduction
In the C++ draft standard in:
5.4 Preprocessing tokens
5.11 Keywords
15.5 Header unit importation
A.3 Lexical conventions
There are mentions of these terms import-keyword, module-keyword and, export-keyword.
Confusion
In the grammer section I'm not really sure how its possible that as per A.1 General
"t... | You have all of the pieces there; you're just not looking at it correctly. Probably because of the term "keyword".
So let's start with pp-import is not part of the grammar. This is not really C++ grammar per-se; it starts with "pp" because it's part of the preprocessor. The preprocessor is a thing that happens before t... |
65,047,500 | 65,050,919 | Why isn't `std::compare_three_way` a `std::strict_weak_order`? | With C++20 concepts and three-way-comparison, I have made my own Map like this:
template<
typename TKey,
typename TValue,
std::strict_weak_order<TKey, TKey> KeyComparer = std::compare_three_way, // Error: template constraint not satisfied
typename PairAllocator = std::allocator<KeyValuePair<TKey, TValue... | std::strict_weak_order<R, T, U> requires R to be a predicate - that invoking R on objects of types T and U gives you bool. But std::compare_three_way does not return bool, it returns one of the comparison categories that are the result of <=> (e.g. std::strong_ordering).
There is currently no concept in the standard li... |
65,047,858 | 65,048,137 | How to verify all correct input digits C++ | I have the following code, this can check if the input is an integer; however, if something like '5o' is input it still flows through, can someone help me make sure all the digits input into x are correct, thank you!
#include <iostream>
using namespace std;
int main() {
cout << "enter x please: ";
int x;
cin >> x... | Read an entire line at once as a string and validate:
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cctype>
int main()
{
std::printf("Enter x: ");
std::string line;
while (true)
{
if (!std::getline(std::cin, line))
{
std::puts(... |
65,048,571 | 65,048,741 | Construct a tuple with arbitrary number of types, all constructable from a single type, and non-default-construcible | I have a tuple
using MyTuple = std::tuple<Foo1, Foo2, Foo3, ... FooN>;
and want to construct MyTuple like this
MyTuple foo{Foo1{x}, Foo2{x}, Foo3{x}, ... FooN{x}};
FooK is not default constructible
N is not known at write-time. Thus I cannot hardcode a list like the one above.
What I have is
Enum::Tuple<EnumType, En... | As I understand, you want something like:
template <typename... Ts> struct tag{};
template <typename Tuple> struct tag_from_tuple;
template <typename Tuple> using tag_from_tuple_t = typename tag_from_tuple<Tuple>::type;
template <typename... Ts> struct tag_from_tuple<std::tuple<Ts...>>
{
using type = tag<Ts...>;
... |
65,048,585 | 65,048,616 | How to set value of an unordered map to number other than 0 | When I declare an unordered map, then by default all the values are assigned to 0. But I want to assign all the values to say -1. Is there any way to do that?
For example see this code
#include <iostream>
#include <unordered_map>
using namespace std;
unordered_map<int, int> umap;
int main()
{
cout<<umap[10]... | You can create a custom type with a default constructor to initialize to -1:
struct MyInt
{
int i = -1;
};
unordered_map<int, MyInt> umap;
You can provide operator int() and other operators to mimic the behavior of a regular int if you don't want to type the .i accessor.
|
65,048,850 | 65,048,851 | Are specializations over a non-type template parameter with an argument of different pointer-to-members guaranteed to be unique specializations? | Consider the following class template:
template <auto>
struct T {};
Are two specializations of T, where the respective template-argument is a pointer-to-member(1) to two different but same-type members, guaranteed to refer to different specializations of T?
(1) pointer to data member or pointer to member function.
... | All standard references below refer to N4659: March 2017 post-Kona working draft/C++17 DIS.
Yes, they are guaranteed to refer to different specializations.
As per [temp.names]/1
[temp.names]/1 A template specialization can be referred to by a template-id: [...]
a template specialization is formally referred to by a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.