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 |
|---|---|---|---|---|
69,097,842 | 69,098,234 | compile dependencies into a library itself | I want to provide a large library I programmed (further called "my lib") to another developer who is building a larger application (further called "target application"). My lib is under very experimental development and I may change dependencies, versions of those, etc. quite often. To call the developer of the target ... | The real answer is this: use a proper dependency manager.
Ensure you have a proper build system setup where no matter the usage requirement change, no changes are required for projects down the line. Coupled with a dependency manager, it won't matter how your usage requirement are: the user will only update the library... |
69,098,362 | 69,098,580 | Why allocate_at_least() in C++23? | According to cppref:
std::allocator<T>::allocate_at_least
Allocates count * sizeof(T) bytes of uninitialized storage, where
count is an unspecified integer value not less than n, by calling
::operator new (an additional std::align_val_t argument might be
provided), but it is unspecified when and how this function is c... | allocate_at_least does not do the same thing as allocate. Compare (allocate):
Allocates n * sizeof(T) bytes of uninitialized storage...
with (allocate_at_least):
Allocates count * sizeof(T) bytes of uninitialized storage, where count is an unspecified integer value not less than n...
Moreover, allocate returns:
Po... |
69,098,424 | 69,098,838 | Is this the right way? How to get Hex value into a char array? | I need following char packet[] = {0x00,0x14}; to send over a TCP/IP, this is the only way I got it to work. With that char I would send the number 20, another possible example would be char packet[] = {0x4e,0x20}; that would be 20000. I am Starting to think that I am approaching this completely wrong.
With this code I ... | If you just want to convert a number than can be expressed in 16-bits into an array of 2 bytes using network byte order as you imply.
int num = 20000; // or any number for that matter
char packet[2];
packet[0] = (num & 0xff00)>>8; // 0x4E
packet[1] = (num & 0x00ff); // 0x20
Done.
Alternatively, most network prog... |
69,098,501 | 69,101,333 | C++. How to sort by module with saving the original order of elements | I'm trying to sort element in vector by module with the condition that the initial order of equal (by module) elements does not change. Logic tells me that the comparator should take less than or equal to save the original order.
std::sort(v.begin(), v.end(), [](int a, int b) {
return abs(a) <= abs(b);
});
But wit... |
What am I wrong about?
Your programs had undefined behaviour, because std::sort and std::stable_sort require a strict weak order, which <= isn't. Importantly when you compare an element to itself, the comparison must return (a value that converts to) false.
If you want a stable sort, use std::stable_sort with a valid... |
69,098,826 | 69,115,911 | Signed integer overflow undefined behavior | In this question, there is this answer stating
Signed integer overflow is undefined behaviour
but it gives no reference to the C++ standard, so I tried to look it up myself in ISO/IEC 14882 (sixth edition 2020-12). In § 7.7 on page 148 I found (5.7)
an operation that would have undefined behavior as specified in Cla... | Since a pull request was opened for this case, it seems that the reference to chapter 7.2 was wrong and it should have been 7.1 instead.
|
69,098,916 | 69,104,400 | Range-v3, how to access a range of a range value individually (group_by function) | I'm using range-v3 by Eric Niebler and using the ranges::views::group_by function.
In the documentation for group_by it says: "Given a source range and a binary predicate, return a range of ranges where each range contains contiguous elements from the source range such that the following condition holds: for each eleme... | p isn't a random access range (it can't be), so there isn't going to be support for indexing (i.e. [0]). And then p isn't a range of pairs, it's a range of range of pairs.
All views have a front() member function that they inherit from view_interface so if you want to print the first and second members of the first sub... |
69,099,783 | 69,099,981 | How to encapsulate a memory-mapped file into a std::vector? | In C++, on Linux, after I open a file with open() and then memory-map it with mmap(), I am given a void* that I can typecast to e.g. char* and read as desired.
But, suppose I want to use std::vector to access that data. How could I accomplish that?
At first I thought I could make a custom allocator for my std::vector.... |
Is there perhaps some other standard-library class that would serve my purpose?
Yes: std::span is a wrapper that provides container like access without ownership.
|
69,100,088 | 69,107,442 | Want to put binary data of images into RocksDB in C++ |
I'm trying to save binary data of images in Key-Value Store
1st, read data using "fread" function. 2nd, save it into RocksDB. 3rd, Get the data from RocksDB and restore the data into form of image.
Now I don't know whether I have problem in 2nd step of 3rd step.
2nd step Put
#include <iostream>
#include <string.h>
#... | char* buffer = ...
db->Put(WriteOptions(), file_key, buffer);
How is RocksDB supposed to know the length of the buffer? When passing in a char* here, it is assumed to be a nul-terminated C string using the Slice(char *) implicit conversion. Nul-terminated C strings cannot be used for binary data because the data will ... |
69,100,233 | 69,104,124 | Can't find 'Show Call Hierarchy' in VSCode | When I right click a function, there's no 'Show Call Hierarchy' or 'Peek Call Hierarchy'
option whatsoever. My popup menu looks like this
Then I tried Typing 'Show All Hierarchy' in command palette. This command does exist, but only gives a 'No Result' window after hitting enter.
So I went to Keyboard Shortcuts page, ... | When a feature like that is added to VSCode release notes or any other documentation, you should assume that it is initially only available for JavaScript/TypeScript,
Visual Studio Code show call hierarchy
That's very commmon because VSCode is just an editor providing the infrastructure (context menus and other visual ... |
69,100,444 | 69,100,665 | Raw pointer to shared_ptr bug | I'm working on a image treating application.
In summary, I have a byte buffer which stores the image data, so I can use this array to handle the image easily in wx widgets and OpenCV. I planned to store this byte buffer in a shared_ptr as it will be used in other instances of the same class along the execution.
With ra... | _originalData.get() is a void**, not a void*.
To share ownership of that allocation, you need std::shared_ptr<void>, not std::shared_ptr<void*>. You also need to set the deallocation function, as it is undefined behaviour to delete a pointer that was malloced.
_originalData = std::shared_ptr<void>{ malloc(len), free };... |
69,100,593 | 69,100,700 | memcpy - taking the address of temporary array error | I am working on Arduino and trying to change the elements of an array. Before setup, I initialized the array like this:
bool updateArea[5] = { false };
And then I wanted to change the array like this:
updateArea[0] => false,
updateArea[1] => true,
updateArea[2] => false,
updateArea[3] => false,
updateArea[4] => true
... | This sort of syntax is valid in C, but not in C++ - which is the language underlying the Arduino IDE.
But you have a few easy solutions:
Since you're willing to write out the array anyways, why not just:
bool updateArea[5] = {false, true, false, false, true};
You can declare the array as a non-temporary array and th... |
69,100,653 | 69,102,524 | const inline std::map in header causes heap corruption at exit | I want to have const std::map in header as a global constant that will be used in other cpp-s. So I declared it as:
// header.h
const inline std::map<int, int> GlobalMap = { {1, 2}, {3, 4} };
However, if I include this header in multiple cpp-s, heap corruption happens at exit time because multiple destructors are run ... | This looks like a Visual Studio bug: https://developercommunity.visualstudio.com/t/static-inline-variable-gets-destroyed-multiple-tim/297876
At the time of posting, the bug has status "Closed - Lower Priority", i.e. it is not fixed.
From the comment of the Microsoft representative:
If you still face this issue in our ... |
69,100,704 | 69,104,561 | Unexpected/Incorrect Results while running SYCL/DPC++ code | I am a beginner in SYCl/DPC++. I want to print multiples of 10 but, instead of that, I am getting 0's in place of that.
I am using the USM (Unified Shared Memory) and I am checking the data movement in the shared memory and host memory implicitly. So I have created two Arrays and I have initialized and performing the o... | You are missing a barrier between the submission of the queue and the for loop in the host code.
Although it is true that an USM shared memory allocation is visible on the host and the device, there is no guarantees that the command group you have submitted to the queue will execute before the for loop in the host: Sub... |
69,100,745 | 69,106,103 | How to adjust source code highlighting in GDB cli? | I am using basic GDB CLI tool, no any TUI frontends. It highlights some parts of code with the same color as my terminal background making them indistinguishable. I know it is possible to disable source code highlighting but I would like to have it.
I didn't find much about this in documentation besides the fact that e... | Edit esc.style in /usr/share/source-highlight/esc.style
GDB uses source-highlight which should not be confused with similar tool called just 'highlight' and provided by some distributions including Debian and Ubuntu. It is possilbe to check if GDB is actually linked with it: there should be --enable-source-highlight li... |
69,101,123 | 69,101,170 | Using the !(not) operator when referring to a variable in a different class | I have created an object from the class HapticDevice and would like to use the !(not) operator when referring to device, but this leads it to change the variable name. What to do guys
Example code:
HapticsDevice haptic_device;
if (haptic_device.!device.get()) return;
| If you want to get haptic_device.device, NOT it, and then call get on the result of the not, it is (!haptic_device.device).get(). This is the same as (!(haptic_device.device)).get() since . has precedence over !. In fact, . has very high precedence.
I suspect you actually want !haptic_device.device.get() though which i... |
69,101,279 | 69,101,467 | operator== in C++ struct | I'm trying to define an == operator in a structure:
typedef struct _tBScan {
QString strQuadpackNumbers;
uint uintBegin, uintEnd;
bool operator==(const struct _tBScan& a, const struct _tBScan& b) {
return (a.strQuadpackNumbers.compare(b.strQuadpackNumbers) == 0 &&
a.uintBegin == b.ui... | When overloading an binary operator as a member function, the first parameter is this pointer. In the signature you have defined the operator==, it will take 3 arguments. However, it can only take two.
In you case I would recommend making it a non-member function.
typedef struct _tBScan {
QString strQuadpackNumbers... |
69,101,302 | 69,101,336 | Why does the below expression turn out to be true, asking for C++ specifically | #include <iostream>
using namespace std;
int main()
{
if(sizeof(int)> -1)
cout<<"ok";
else
cout<<"not ok";
return 0;
}
Isn't size of int supposed to be 4, which should be greater than -1.
| Two things:
sizeof(int) can be any positive integral value. (I've worked on a system where sizeof(char), sizeof(int) and sizeof(long) were all 1 and were all 64 bit types.)
The type returned by sizeof is an unsigned type. When comparing with -1, -1 is converted to an unsigned value, with a high magnitude. Almost cert... |
69,101,696 | 69,102,195 | How to get Version.Code in Android using C++? | I use native C++ with my Android project.
In Java or Kotlin we can use BuildVersion.Code to get the Android code from the Gradle file. How can I get this version code in C++?
| This is working for me:
jclass build_config_class = env->FindClass("com/example/app/BuildConfig");
jfieldID version_code_id = env->GetStaticFieldID(build_config_class, "VERSION_CODE", "I");
jfieldID version_name_id = env->GetStaticFieldID(build_config_class, "VERSION_NAME",
... |
69,102,009 | 69,102,207 | Can't compile ftpupload.c | I'm trying to compile ftpupload.c with command g++ -o program ftpupload.c, but I get the following error:
ftpupload.c: In function ‘size_t read_callback(char*, size_t, size_t, void*)’:
ftpupload.c:57:50: error: invalid conversion from ‘void*’ to ‘FILE* {aka _IO_FILE*}’ [-fpermissive]
size_t retcode = fread(ptr, size... | This is compiling a C source file as C++. C++ is stricter when it comes to implicit conversions and does not allow an implicit conversion from a void* to any other pointer (source):
Pointer to object of any type can be implicitly converted to pointer to void (optionally cv-qualified); the pointer value is unchanged. T... |
69,102,287 | 69,102,469 | Access class from another C++ file | So I have a "main.cpp" file which I have declared an object of my class player:
main.cpp:
#include "player.h"
Player player;
int main() {
//
player.update();
}
I would like to access this object from multiple different C++ files. However, I would like to do this without using the keyword extern as i'm trying to... | Rather than write functions like
file1.cpp
#include "player.h"
extern Player player;
void doStuffToPlayer() {
player.update();
}
file2.cpp
#include "player.h"
#include "file1.h"
Player player;
int main() {
doStuffToPlayer();
}
You can instead write
file1.cpp
#include "player.h"
void doStuffToPlayer(Playe... |
69,102,611 | 69,102,723 | Why is a narrowing conversion from int to float only needed if I brace-initialise an object? | I ran into what I think is a weird thing:
#include <vector>
int numqueues = 1;
std::vector<float> priorities{numqueues, 1.f };
//^^^ warning: narrowing conversion of numqueues from int to float
//std::vector<float> priorities(numqueues, 1.f );
//^^^ No warning or error. And it's not because it's parsed as a function ... | In this declaration
std::vector<float> priorities{numqueues, 1.f };
the compiler uses the initializer list constructor.
vector(initializer_list<T>, const Allocator& = Allocator());
The narrowing conversion for initializer lists is prohibited.
In this declaration
std::vector<float> priorities(numqueues, 1.f );
the co... |
69,102,939 | 69,103,001 | How can I print the length of words stored in a string array in C++? | I am trying to get the length of the words which I have stored in a string array.First,I specify the number of words in an array using 'n'(input from user), then I take inputs from the user of the 'n' words they want to store. After that, I wish to print the length of a word.
Here is the code....
#include <iostream>
us... | cin>>n;
string A[n];
The size of an array must be known at compile-time. Variable-length arrays (VLA) are not supported in C++ (also some compilers do as an extension). Use a container with dynamic allocation instead, like std::vector.
std::cin >> n;
std::vector<std::string> A(n);
And use A[2].size() instead of s... |
69,103,523 | 69,103,851 | Does gcc-8 on arm64 debian ignores friend operator<? | I want to compare two sets of objects. For the same code I get 2 different outputs on different machines.
The code is compiled with two different compilers. On the x86-64 machine i used gcc-11, on the aarch64 (raspberry pi4) machine i used gcc-8. I have to use the gcc-8 on the raspberry because it's in the official rep... | The problem is here:
bool operator<(const ::std::shared_ptr<ClassA> &lhs, const ::std::shared_ptr<ClassA> &rhs)
The shared pointer has its own comparison operators which compares stored pointers. There is also owner_less which compares owned pointers (a specially constructed shared pointer can own one object but point... |
69,103,714 | 69,103,941 | no viable overloaded '=' and inheritance | I have the following class structure but when I build, I keep getting the error:
error: no viable overloaded '='
p1 = new HumanPlayer();
~~ ^ ~~~~~~~~~~~~~~~~~
../Test.cpp:14:7: note: candidate function (the implicit copy assignment operator) not viable: no known conversi... | as commented above
p1 = new HumanPlayer();
is valid if p1 is declared as pointer, unlike java you can in c++ assign with and without the new keyword...
in your case declaring p1 as pointer will be ok
Player* p1{nullptr};
and later
p1 = new HumanPlayer();
|
69,104,065 | 69,104,116 | c++ set erase function not working properly with iterator | set<int> s = {1, 2, 3, 4};
auto it = s.begin();
while (it != s.end()) {
// this correct
s.erase(it++);
// this incorrect
s.erase(it);
it++;
}
why on top of code can running?
My understand of the order when my code running is:
When the erase function is executed, then iterator was deleted.
T... | The best way would be:
it = s.erase(it);
Your code with post-increment also works, but it is less transparent. To recall, post-increment version is semantically equivalent with the following snippet:
temp = it;
++it;
s.erase(temp);
As for your claims of ill-formed (second version) code "running", the code which has u... |
69,104,492 | 69,105,108 | Is there a simple way to do array differences and approximate array derivatives in C++? (Like the diff() function in matlab) | Matlab code I would like to translate into C++
X = [1 1 2 3 5 8 13 21];
Y = diff(X)
output : 0 1 1 2 3 5 8
https://www.mathworks.com/help/matlab/ref/diff.html
| C++ calls it std::adjacent_difference.
int X[8] = {1, 1, 2, 3, 5, 8, 13, 21};
int Y[8];
std::adjacent_difference( std::begin(X), std::end(X), std::begin(Y) );
Note that the first element of the destination is a direct copy of the source. The remaining elements are differences.
See it work on Compiler Explorer.
|
69,104,539 | 69,104,824 | How to convert string to const unsigned char* without using reinterpret_cast (modern approach) | I have variable input type const std::string&:
const std::string& input
Now I need to convert this to const unsigned char* because this is the input of the function.
Unitl now I have correct code for converting:
reinterpret_cast<const unsigned char*>(input.c_str())
This works well, but in clang I got a warning:
do n... |
What is the correct way to change a string or const char* to const unsigned char*?
The correct way is to use reinterpret_cast.
If you want to avoid reinterpret_cast, then you must avoid the pointer conversion entirely, which is only possible by solving the XY-problem. Some options:
You could use std::basic_string<un... |
69,104,609 | 69,104,777 | std::numbers has not been declared - GCC 11.2 on Windows | I have GCC 11.2.0 installed on my Windows 10 machine (from here: https://winlibs.com/). I have updated the environment variable Path to C:\MinGW\bin
gcc version 11.2.0 (MinGW-W64 x86_64-posix-seh, built by Brecht Sanders)
I'm using VSCode with the C/C++ extension configured to use the correct compiler path.
I want to u... | Default version of c++ standard for this version of gcc is C++17.
See this: https://godbolt.org/z/4Pjzd5r7s
Use
g++ main.cpp -o main -std=c++20
to force C++20
There is some support of C++20 in gcc, but it is simply to early to make it default standard.
|
69,104,959 | 69,108,626 | Missing POSIX and std symbols using MSYS2/MINGW-64 | I tried to port some C/C++ code from Linux to Windows. On Linux I am using GCC-10 for building, on Windows I am trying to use MSYS2/MINGW-64. I have never used MSYS2 before and I have few experience in porting Linux/POSIX code to windows.
Most of the (Qt) code is portable anway so I got non-trivial problems only in a f... | I don't think MinGW ever claimed full POSIX compatibilty, so the lack of O_SYNC and sync() is to be expected.
on_exit has a standard alternative std::atexit.
Judging by the comments under this question, at_quick_exit (and quick_exit itself) aren't provided by msvcrt.dll (the old Microsoft C runtime that MINGW64 uses). ... |
69,105,039 | 69,105,145 | Compile error in full specialisation of function template | In the following program, I am trying to iterate over a list of types using a meta struct of types.
It compiles and works fine unless I specify template<> before the base print template definition.
/* example.cpp */
#include <iostream>
template<typename ...>
struct List{};
template<typename T,typename ...Rest>
void ... | Your primary template is:
template<typename T, typename...Rest> void print(List<T, Rest...> *)
So one T and a pack.
template<> void print(List<> *) simply doesn't match.
You would have to have
template<typename...Ts> void print(List<Ts...> *) to allow your specialization.
Notice than with fold expression of C++17, it w... |
69,105,158 | 69,105,273 | Create variable that contains a string and std::endl, that can be used in output streams to std::cout | Using c++17
I have a header file colors.hpp to help me with colored output to stdout:
#pragma once
#include <string>
namespace Color
{
static const std::string yellow = "\u001b[33m";
static const std::string green = "\u001b[32m";
static const std::string red = "\u001b[31m";
static const std::string end... | std::endl is a function (actually function template), not an object. That means, if you want to replicate it, you need a function as well.
If you add this to Color:
template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os )
{
return os << end << std::end... |
69,106,008 | 69,106,144 | Is it possible to force a class to be passed by reference or pointer (C++)? | I'm not entirely sure what to search for to see if this has been asked, so hopefully it isn't a duplicate.
Supposed I've written a class in C++. Is it possible, by way of constructors or some other internal (to the class) mechanism, to throw a compiler warning when the class is passed to a function not by reference.
Th... | While I was typing this "van dench" gave the short answer.
And what Ted Lyngmo also makes sense.
This is the answer in code if you want to be explicit.
class NonCopyableNonMoveable
{
public:
NonCopyableNonMoveable() = default;
NonCopyableNonMoveable(NonCopyableNonMoveable&&) = delete;
NonCopyableNonMoveable... |
69,106,460 | 69,107,290 | Wrapping 2d grid indices | I have this function which i prototyped in python for navigating grid indexes. It works perfectly in python but due to the way the modulo operator handles negative numbers it falls down in c++. Can anyone suggest a modification that will make this work?
The function fails when coordinates nx and ny are negative.
int wr... | You just need a mod function that will only give you non-negative values. To just do it the straight-forward way is like below (after moving your code around for clarity).
#include <tuple>
#include <iostream>
int grid_coords_to_index(int cols, int rows, int x, int y) {
// wrap the coordinates...
int column = x... |
69,106,519 | 69,118,255 | c++ destructor doesn't delete the object itself, what does? | Firstly, unless I've misunderstood it, a destructor frees up memory taken up by variables inside the object. In the below example it would delete the string pointed to by * str. That's ALL.
class StrPtr {
private:
string * str;
public:
StrPtr() : str(new string()) {}
~StrPtr() { delete str; }
voi... | See option 3 on my question.
There are no memory leaks, there is never more than one StrPtr object in memory.
|
69,107,224 | 69,107,312 | How to convert variadic function arguments to array? | How to convert variadic function arguments to array?
I need something like this:
template <typename T>
struct Colordata
{
public:
T dataFirst;
T dataLast;
template <typename... Ta>
Colordata(Ta... args)
{
constexpr std::size_t n = sizeof...(Ta);
std::cout << n << std::endl;
... | You can't convert a parameter pack into an array. You could create an array from one, but that would copy, and that would be wasteful. Instead, we can "convert" the parameter pack into a tuple of references, and then use get to index into that tuple. That would look like
template <typename... Ta>
Colordata(Ta... arg... |
69,107,280 | 69,107,349 | OpenGL white window while code runs glew/glfw3 | So I am trying to draw two triangles, but at the end I just get the white window without any triangles. I have set up the libraries correctly but I believe there could be a mistake somewhere in the code and since I am fairly new I cannot figure it out. The code complies with no errors or warnings, but the outcome is no... | You have to call glfwSwapBuffers and glfwPollEvents at the end of the application loop:
while (!glfwWindowShouldClose(window))
{
// [...]
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwSwapBuffers swaps the front and back buffers and causes the window to be updated.
glfwPollEvents process the events.
|
69,107,295 | 69,107,537 | How can I show a window with the a name given as parameter in Windows in C++ | I would like to make my software usable for Linux and Windows (Linux already works). Now I still need some functions so I can run the software on Windows, too.
I am currently trying to use the EnumWindows() function to get the window names and then show the window in the foreground (which matches the parameter).
static... | Yes, you can use the LPARAM to pass a string variable into your callback, eg:
static BOOL CALLBACK setWindowFocus(HWND hWnd, LPARAM lparam) {
std::string &programname = *reinterpret_cast<std::string*>(lparam);
int length = GetWindowTextLength(hWnd);
char* buffer = new char[length + 1];
GetWindowText(hW... |
69,107,418 | 69,107,856 | An ugly function finding the maximum std::set element less than a given key | When I write a code that is a bit strange I have a feeling that I probably misunderstand something.
Is there a better implementation of find_less function than provided below?
#include <iostream>
#include <set>
using Set = std::set<int>;
Set set{ 0, 1, 3, 7, 9, 10 };
Set::iterator find_less(int val)
{
auto i = s... | A simple solution that accounts for all potential inputs may be one that returns end() to exclusively mean
No element in the set meets the criteria
auto find_less(const Set& set, int val)
{
auto i = set.lower_bound(val);
return (i == set.begin()) ? set.end() : std::prev(i);
}
I have also changed your functio... |
69,107,694 | 69,123,095 | Why a Widget class uses pointers as data members? | I'm working through "Programming Principles and Practice", and I don't understand why this Widget class uses pointers as data members.
The book's explanations is this:
Note that our Widget keeps track of its FLTK widget and the Window with which it is associated. Note that we need pointers for that because a Widget ca... | First, we need to work out the logical and implementation details. On the logical side, a window contains widgets: just like a mother has children. This is a one to many relationship. Each widget has an implementation entity, in this case an Fl_widget. It could equally be a MS windows Window, a QtWidget or and X-Wi... |
69,108,136 | 69,108,184 | What does "type name[size]" mean in a function argument? | I was analyzing the SKIA source code and found this:
constexpr unsigned kMaxBytesInUTF8Sequence = 4;
// ...
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[kMaxBytesInUTF8Sequence] = nullptr);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I know (pardon me if I'm wrong) that char utf8[kMaxBytesI... | A function parameter having an array type is adjusted by the compiler to pointer to the array element type.
Thus these function declarations
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[kMaxBytesInUTF8Sequence] = nullptr);
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[10] = nullptr);
SK_SPI size_t ToUTF8(SkUnichar uni... |
69,108,401 | 69,108,667 | Is there a difference between a copy constructor with an argument type of `const T &` and of type `const T<U> &`? | As of C++11, std::allocator defines three constructors that are roughly equivalent to those in the following class:
template<typename T>
class allocator {
public:
constexpr allocator() noexcept = default;
constexpr allocator(const allocator &other) noexcept = default;
template<typename U>
constexpr al... |
It [the third constructor] appears to technically be a specialization of the copy constructor?
It is not a copy constructor at all. It is actually a converting constructor instead.
would the second constructor ever even be called?
If an allocator<T> object is used to construct another allocator<T> object, then the... |
69,108,418 | 69,108,525 | Temporary materialization on std::initializer_list<T> | I am reading about Temporarily Materialization, and got stuck on this point:
Temporary materialization occurs:
when initializing an object of type std::initializer_list<T> from a braced-init-list;
Does this mean that in this case:
std::initializer_list<int> x = std::initializer_list<int>{1,3,5};
the initializer_li... | Strictly speaking, it really doesn't matter, because there's no way you could ever observe whether a temporary std::initializer_list object is created.
But I think the answer is that the "materialization" described is the materialization of a temporary object with type int[3] (array of 3 ints) as described in [dcl.init... |
69,108,629 | 69,109,212 | Compiling multiple c++ files doesn't work with certain file names | I am trying to compile multiple .cpp files, using a Makefile with make. I have a .cpp file containing the main function, in the other .cpp file a basic class (for every doubt I'll put all the code i'm using down here).
Example of names used to make it compile or to make it not compile:
-it works by having them named "p... | You can fix this by changing one character.
In this rule:
$(BIN): $(OBJS)
$(CC) $(CFLAGS) $< -o $@
the prerequisite list $(OBJS) expands to a list of object files, such as prova.o pa.o or pa.o ciao.o. You want Make to incorporate that list into the linking command, like this:
g++ -g -Wall prova.o pa.o -o bin/prova... |
69,108,786 | 69,110,125 | Move object within its own destructor | If I have a move-only class which is initially owned by AManager, can be transferred to another owner via obtain, returned back to AManager via release.
class AManager;
class A {
public:
A(const A& other) = delete;
const A& operator=(const A&) = delete;
A(A&& other);
A& operator=(A&& other);
private:... |
is it valid for A to release itself back to its manager when it is destroyed?
"Valid" in what sense? Will it compile? Yes.
Does it make any kind of sense? No.
You are moving an object that is being destroyed. The owner of that object requested and expects the resources managed by this object to no longer exist. By gi... |
69,109,280 | 69,109,591 | C++ re-assignable const member variable | In C++, suppose I have a member variable of type Bar, and I want to make sure only const methods are called on it. So then AFAIK I can declare it as a const Bar member variable like below:
class Foo
{
public:
Foo(const Bar& b) : bar(b) {}
void setBar(Bar& b) {
bar = b; // compiler complains here
}
private:... | The "trick" is to have your member data be a std::shared_ptr<const Bar> instead of const Bar; you can then re-assign the shared_ptr at will, but can't change Bar since the pointer is const.
#include <memory>
struct Bar final {};
struct Foo final
{
//Foo(const Bar& b) : bar(b) {}
Foo(const Bar& b) : pBar(std::m... |
69,109,374 | 69,109,404 | error: ‘_cal_order’ was not declared in this scope - scoping issue | I am starting to learning C++ and am trying some simple examples. However the example below gives me the following error:
main.cpp:20:32: error: ‘_cal_order’ was not declared in this scope
double pos=_cal_order(p,n,l);
I am just trying to pass 3 variables to a function and return a double result. Here is the co... | You must declare the function before using it.
Option 1: Define it first
#include<math.h>
#include <iostream>
using namespace std;
double _cal_order(double p, int n, double l)
{
return static_cast<double>(round(n/(p*l)))*l;
};
int main()
{
int n = 5000;
double p = 45000.0;
double l = 0.001;
... |
69,109,472 | 69,110,634 | How to add a key with a dot in the name to a json file | I am reading some information and I want to write it in json, but the names of some keys contain dots in the name. I want to get something like this:
{
"programs":
{
"tmp.exe" : "D:\\Directory\\Directory",
"foo.exe" : "C:\\Directory"
}
}
This is my code:
ptree pt;
ptree name;
name.put(string_name,... | Although all JSON linters I've tested accepts your target JSON as valid and boost::property_tree::read_json parses it, actually creating it is a bit cumbersome. This is because boost::property_tree uses . as a path separator by default.
To overcome this, you can specify the Key with a different ptree::path_type than th... |
69,109,774 | 69,109,902 | What is the best way to return multiple large objects in C++? | I want to return a tuple containing types like std::vector or std::unordered_map etc. where the objects may be large enough that I care about not copying. I wasn't sure how copy elision / return value optimization will work when the returned objects are wrapped in a tuple. To this end I wrote some test code below and a... |
My main question is why foo() ends up copying? RVO should elide the
tuple from being copied but shouldn't the compiler be smart enough to
not copy the A struct? The tuple constructor could be a move
constructor
No, move constructor could only construct it from another tuple<> object. {a,b} is constructing from the co... |
69,110,253 | 69,110,701 | How can I read and write text files using the windows api | There are many similar questions, but mine is a bit different. Mine involves a Windows GUI. I am using an open file dialog or an "OPENFILENAME". I want to get the dialog result as OK when the user clicks the OK button and then open a text encoded file. I have done it in Java, but the UI looks weird. So I am not sure wh... | The main purpose of the functions GetOpenFileName and GetSaveFileName is to provide you with the filename that the user selected. However, doing the actual File Input and Output is a different issue. You can use the standard C/C++ library for that or you can use the Windows API functions, such as CreateFile, ReadFile a... |
69,110,367 | 69,122,925 | WinUI 3 Desktop XAML Databinding - WinRT originate error - 0x8001010E when the Property is changed | I am following the BookStore data binding example, documented at XAML controls; bind to a C++/WinRT property, up to and including the "Bind the button to the Title property" section.
My starting point is a new "Blank App, Packaged (WinUI 3 in Desktop)" project in Visual Studio.
[EDIT] Starting from a "Blank App (C++/Wi... | This issue #4547 was the key to figuring out the solution. You need to use the Microsoft namespace, not Windows. For documentation purposes this is what the BookSku.idl file should look like:
// BookSku.idl
namespace Bookstore
{
runtimeclass BookSku : Microsoft.UI.Xaml.Data.INotifyPropertyChanged
{
Book... |
69,110,661 | 69,110,699 | Inheritance mess with pure virtual functions, any way to not have to re-define them all? | So I found myself in a bit of a mess of a class hierarchy.
I have code that looks a bit like that, oversimplified:
#include <iostream>
struct Parent {
virtual void pureVirtual() = 0;
};
struct Child : public Parent {
void pureVirtual() override {
std::cout << "Child::pureVirtual()" << std::endl;
}
};
struc... | The issue is that you actually are getting two pureVirtual functions. C++ isn't smart enough to merge the two by default. You can use virtual inheritance to force the behavior.
#include <iostream>
struct Parent {
virtual void pureVirtual() = 0;
};
struct Child : virtual public Parent {
void pureVirtual() override... |
69,110,725 | 69,110,946 | Write a program that reads a string of characters and calls a recursive function to determine if the letters in the string form a palindrome | I'm tasked with a project to write a recursive function that will determine if a user inputted string is a palindrome or not. I think I have a very strong foundation of code for the problem, but it doesn't seem to work how I want it to.
I was doing some troubleshooting to figure out what was wrong and it appears that i... | Assumption : you're being forced to use recursion, character arrays, and not allowed to use the functions in <algorithm> that pretty much do all the work for you.
The bug: lowerPalin was not null terminated. That makes high = strlen(lowerPalin); a fatal mistake. strlen counts characters untill it finds a null, so witho... |
69,111,070 | 69,111,086 | Why the C++ linker doesn't complain about missing definitions of theses functions? | I have written this code:
// print.h
#pragma once
#ifdef __cplusplus
#include <string>
void print(double);
void print(std::string const&);
extern "C"
#endif
void print();
And the source file:
// print.cxx
#include "print.h"
#include <iostream>
void print(double x){
std::cout << x << '\n';
}
void print(std::str... |
I compiled print.cxx using gcc which doesn't define the C++ version...
Not quite. gcc and g++ both invoke the same compiler suite. And the suite has a set of file extensions it automatically recognizes as either C or C++. Your *.cxx files were all compiled as C++, which is the default behavior for that extension.
You... |
69,111,146 | 69,111,482 | How to find the number of chars in a string | I am trying to write a program that will take two inputs: the first a char and the second a string. The program will then search through the string, one place at a time and keep track of how many times the char that the user input occurs in the string.
I cannot seem to find my mistake, but the for loop in my CountChara... | As @user4581301 pointed out, the condition in your for-loop doesn't make sense. If you set the value of i = 0 and then check whether i > userString.length(), the boolean expression will always evaluate to false, since 0 will never be greater than the length of the inputted word. If your condition for your loop evaluate... |
69,111,874 | 69,113,070 | 'Candidate template ignored: couldn't infer template argument' with std::set | I'm writing a function to manipulate a set with it's iterators, and it's giving me the error
candidate template ignored: couldn't infer template argument
The minimum reproducible code is as follows:
#include <bits/stdc++.h>
using namespace std;
template <typename T>
void foo(typename set<T>::iterator it1)
{
// do... | In foo the T in argument typename set<T>::iterator is a non-deduced contexts:
...the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template param... |
69,111,975 | 69,112,050 | how can I not create precompiled header when compile object file? | I use g++ 10.2.0 and try to create a static library, but when I create object file for archiving a static library, object file format always shows precompiled header, it makes the final static library cannot work:
//file static_test.cpp
void fn(){
int temp;
++temp;
}
//file static_test.h
void fn();
build the... | -c is only for a single file, the second static_test.cpp is ignored. You should get the compiler warning about multiple files set to -c. g++ -c static_test.h results the precompiled header in static_test.o and static_test.cpp is ignored. The proper command should be
g++ -c static_test.cpp -o static_test.o
Do not pass ... |
69,112,012 | 69,114,818 | how do I tell an array pointer from a regular pointer | I'm writing a smart pointer like std::shared_ptr since my compiler does not support c++17 and later versions, and I want to support array pointer like:
myptr<char []>(new char[10]);
well, it went actually well, until I got the same problem as old-version std::shared_ptr got:
myptr<char []>(new char);
yeah, it can't t... | You can't. This is one of the many reasons that raw arrays are bad.
What you can do is forbid construction from raw pointer, and rely on make_shared-like construction.
|
69,112,227 | 69,115,147 | Write a recursive function that will write the prime factors of a user inputted number | I have posted about recursion a few times and I now understand it, although this problem has been stuck with me for quite some time now. I am supposed to write a program with two functions:
1. a function that returns the lowest prime factor of a user inputted number
2. a recursive function that calls the first function... | the recursive function can be:
//posInt should greater than 1;
void OutputPrimeFactors(int posInt)
{
if(posInt == 1)
return;
int k = smallFactor(posInt);
cout << k;
if(k < posInt)
{
cout << ", ";
OutputPrimeFactors(posInt / k);
}
}
|
69,112,630 | 69,112,752 | How to convert a data of type LPTSTR to HWND? | How to convert a data of type LPTSTR to HWND?
i tried: example
LPTSTR hwnd = L"0x000511E8";
HWND window_hwnd = (HWND)hwnd;
But the value on window_hwnd is not the same as before, and I cant find the window by utilizing this value.
| I think you mean: How to convert a string to a HWND value?
That can be done like this:
#include <Windows.h>
#include <string>
int main()
{
const std::wstring hwnd_str{ L"0x000511E8" }; // to show std::wstring :)
auto value = std::stoull(hwnd_str, nullptr, 16); // convert from hex (base 16) to unsigned long ... |
69,113,758 | 69,113,832 | undefined reference to `Account::set_balance(double)' ----What does it mean? | Account.h file
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
private:
//attributes
double balance;
public:
//methods
void set_balance(double bal);
double get_balance();
};
#endif
Account.cpp file
#include "Account.h"
void Account::set_balance(double bal){
balance=bal;
}
double Account::... | How did you compile these two files? This error suggests that the "Account.cpp" is not compiled or linked by you. Try this:
gcc Account.cpp main.cpp
|
69,113,785 | 69,113,855 | Is it possible to put my c++ code into a window rather than opening in command prompt? | My code is: Is it possible to put this in a window instead of opening up a command prompt as I feel that would be more user-friendly? And would just look better overall I have Searched online and haven’t found any way to put any code in a window.
#include <iostream>
using namespace std;
int main()
{
while (true) ... | You can follow the microsoft docs tutorial for creating a window.
You won't be able to use std::cout and std::cin as these are console specific.
|
69,113,980 | 69,115,103 | If two functions are in arithmetic operations in recursion, which function will work first? | int count(int S[], int m, int n)
{
if (n == 0)
return 1;
if (n < 0)
return 0;
if (m <= 0 && n >= 1)
return 0;
return count(S, m - 1, n) + count(S, m, n - S[m - 1]);
}
Does it end with count(S, m - 1, n) and then start with the next count(S, m, n - S[m - 1])? Or do two have to b... | See Order of evaluation
in
return count(S, m - 1, n) + count(S, m, n - S[m - 1]);
we just have the guaranty that:
S, m-1 (first one) and n are computed before count(S, m - 1, n)
m-1 (second one) is computed before S[m - 1]
S[m - 1] is computed before n - S[m - 1]
S, m, and n - S[m - 1] are computed before count(S, m,... |
69,114,044 | 69,116,951 | When do you need to explicitly call std::move and when not in cpp? | I'm working through Stroustrup's "Tour of C++ v2". It's certainly not a C++ beginner's book, but enjoyable.
I've had a google and look through SO but no joy on this one.
Now, I thought I understood when the compiler can utilise a move constructor, but clearly I don't. Here I show the move constructor and the function t... |
When do you need to explicitly call std::move and when not in cpp?
In short, and technically precise words: Use std::move when you have an lvalue that you want to be an rvalue. More practically: You would want to do that when there is a copy that you want instead to be a move. Hence the name std::move.
In the example... |
69,114,268 | 69,122,679 | Why the address of entry point doesn't match NT header? | I want to find out the entry of a windows program. as far as MS documents describes "ImageBase":
When the linker creates an executable, it assumes that the file will
be memory-mapped to a specific location in memory. ...
I use dumpbin to show ImageBase in PE header, to find where to map:
>dumpbin /HEADERS my.exe
...
... | Assuming you are using a recent version of Visual Studio your application is probably opted-in to ASLR (Address Space Layout Randomization) by default. This is a security feature that is designed to make it harder for shell code (exploits) to find places to latch on to.
Try adding the /FIXED linker switch, this will pr... |
69,115,373 | 72,677,372 | Case Sensitive Selection of Next Occurrence in Xcode | In Xcode, we can select the next occurrence of a selected sequence of characters by pressing Option + Command + E, but this finds the next occurrence of the selected text case-insensitively. How can we do this case-sensitively?
| Xcode version 13.4.1 has recently fixed this problem and Martin R's comment has become the solution. Now you can select a sequence of characters in your code and then press Option + Command + E to select the following occurrence of the sequence. You can repeatedly press the same key combination to select as many occurr... |
69,115,907 | 69,115,991 | Partially deduce arguments with constructor | Take the following class (C++17)
#include <variant>
template <typename Error, typename T>
class Optional
{
public:
constexpr Optional(T&& value)
: m_variant(std::forward<T>(value))
{}
private:
std::variant<Error, T> m_variant = Error{};
};
template <typename E, typename T>
Optional<E, T> MakeOptional(... | CTAD is a "all or nothing".
See the note
Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.
|
69,116,414 | 69,118,533 | reduce response time while using async cpp boost socket | i've created an async beast server that gets a request from a browser, opens a second socket , writes the request , gets the response and sends it back to the browser. all async . as the "send back to browser" action waits to the read handler completion to trigger
void
on_write(
boost::system::error_code ec,
st... | Depends a lot on the goal. If you really wish to transparently relay request/response without any modification, then read_some will be a better approach (but you won't need anything from Beast, just Asio).
Using Beast, you can read partial requests as well, assuming you might want to modify some things about the messag... |
69,116,441 | 69,116,887 | Can't use glGenBuffers in .h file C++ | I'm trying to learn OpenGL in C++. To clean up my code I was trying to create an header file with all variables, which decribe objects, in it. This header looks something like this:
#pragma once
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.... | Snippet from OP:
namespace data {
class Data {
public:
unsigned int VBO;
glGenBuffers(1, &VBO)
};
}
This is a syntax error. glGenBuffers(1, &VBO) is a function call outside a function body block scope. You have to move it e.g. into the constructor of class Data. At best, y... |
69,116,792 | 69,119,007 | QGridLayout, tight rows and columns without padding or spacing | I am using QGridLayout, the first row has a QLabel which is used to show an icon set to 32x32 pixels. The next row has two QSvgWidgets, each of these is 16x14.
My code:
QGridLayout* pgrdloStatus(new QGridLayout);
if ( mplblStsIcon == nullptr )
{
mplblStsIcon = new QLabel();
}
if ( mpsvgRx... | I create this Example and add Items From the Designer to show you why you see that distance between icons.
I create GridLayout and put 2 labels and set 2 LED SVG image
this is what actually you do too :
But For Fixing this issue you should check this property :
which means this : label->setScaledContents(true);
Which... |
69,117,249 | 69,117,448 | Specifying noexcept function conditionally | Let's say I have such function declared noexcept:
int pow(int base, int exp) noexcept
{
return (exp == 0 ? 1 : base * pow(base, exp - 1));
}
From my very little, but slowly growing knowledge of C++, I can noexcept when I'm certain that function will not throw an exception. I also learned that it can be in some ran... | You can use a condition for noexcept, but that condition must be a constant expression. It cannot depend on the value of parameters passed to the function, becaue they are only known when the function is called.
From cppreference/noexcept:
Every function in C++ is either non-throwing or potentially throwing
It cannot... |
69,117,264 | 69,117,875 | How to use CppFlow library with Visual Studio 2019? | I'm trying to make a system for traffic sign recognition. In order to be fast I decided to code image preprocessing and inference in C++ and training in Python. For training of CNN I use TensorFlow with Keras. I came to the part when I need to classify detected sign and for that I need to load my pretrained model. I wo... | I managed to figure it out. Part that confused me the most was that CppFlow is just a wrapper with headers, so you need CppFlow and TensorFlow C API. Also here is the link that helped me a lot with including dependencies in Visual Studio 2019: https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a... |
69,117,426 | 69,117,519 | Template use without angle brackets - Overloading? | I'm a little confused about the idea of using template with <> brackets and without them. When I compiled the code I got the output I wasn't expecting, and didn't figure out why.
For example, let's say I have 2 functions and a template with the same prototype:
using namespace std;
template<typename T> void copy(T a, T... | You have to remember that literal strings are really (constant) arrays of characters, which decays to (constant) pointers to char, i.e. const char*.
Since your function taking std::string arguments is not a direct match, and the compiler will not do a conversion, the template overload will be used (as copy<const char*>... |
69,118,264 | 69,119,314 | How to combine projections with transform in C++20 ranges | C++20 ranges::sort supports projections, and that is great, but I want to do stuff that is more complex, in particular sort on result of function that operates on projected member.
For function call I tried the transform and then sort that view, but C++20 sort seems to not work on views, this answer explains why(for ra... | Seems like you want function composition:
void my_sort(std::vector<S>& ss) {
std::ranges::sort(ss, std::greater<>{}, compose(Distance, &S::val));
}
Where compose(f, g)(x) does f(g(x)). Boost.Hof has a compose, there's one in range-v3 somewhere too. Not one in the standard library though.
For function call I tried ... |
69,118,947 | 69,118,979 | Why isn't the cout overflow in this situation? | I have the following code patch running on my ubuntu20.04, compiled by gcc-9.
#include <iostream>
int main()
{
uint16_t a = 0xFFFF;
uint16_t b = 1;
uint16_t ret = a + b;
std::cout << a + b << std::endl;
std::cout << ret << std::endl;
}
I expect both of the results are overflowed, but the running... | When you do a + b the operands will undergo arithmetic conversions which will promote the values to int types.
So a + b is really something like static_cast<int>(a) + static_cast<int>(b) and the result will of course be an int.
Promotion only happens with types smaller than int (so short or char). Values that already a... |
69,119,344 | 71,597,396 | Raw output file got damaged | I’m working on oneVPL samples from this GitHub repository (https://github.com/oneapi-src/oneAPI-samples ) and I’m trying to build hello-vpp sample. After running the program with the command in readme.md file, I wanted to increase the video size to 1280x720. While playing the raw output file, I used the below command
f... | Try the below command:
ffplay -video_size 1280x720 -pixel_format bgra -f rawvideo out.raw
|
69,119,418 | 69,122,281 | Issues with SendInput() | I was hoping to get some help with this piece of code.
#include <windows.h>
#include <thread>
void keyPress(WORD keyCode)
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wScan = keyCode;
input.ki.dwFlags = KEYEVENTF_SCANCODE;
SendInput(1, &input, sizeof(INPUT));
}
void keyRelease(WORD keyC... | Since you want the Ctrl key to be released immediately when the right mouse button is released, you really shouldn't be using Sleep() to pause the entire 1sec/3secs intervals on each loop iteration while the mouse button is down, otherwise you risk delaying up to 4secs after the mouse button is released before you can ... |
69,119,585 | 69,119,896 | Couldn't deuce template when I use type trait like technique in argument | I use some type trait like techniques to wrap the pointer and reference to improve its readability. I use ptr<T> to represent T*, and lref<T> to represent T&. I wrote codes below.
template <typename T>
struct ptr_impl {
using type = T*;
};
template <typename T>
using ptr = typename ptr_impl<T>::type;
template <typen... | Your lref<T> is only an alias for a nested type lref_impl<T>::type, and types cannot be deduced from their nested types.
For example, if you have
template <typename T>
struct Identity { using type = T };
then the following will not be compiled:
template <typename T>
void f(typename Identity<T>::type t){}
void g(){f(1... |
69,119,777 | 69,120,315 | Fill two dimensional array with spiral | The task is to fill two dimens array [N][M] in a spiral with numbers starting with 1.
My code doesn't work when one of the elements (N or M) is odd or both are odd.
When I use two different even or two same even numbers it works.
I need help to do it so it would work in any case, with any N and M.
p.s. please keep my c... | To summarise, I managed to solve using two changes:
first, we change the limits of the main call so that we reach the centre everytime, and second, we avoid overwriting of already populated indices. Here, I stop this overwriting by checking by using an if statement before every assignment. But, cleaner solutions might... |
69,120,045 | 69,120,285 | Cast custom struct to another template type | template <typename T>
struct Colordata
{
public:
T *data;
unsigned long size;
unsigned long length;
template <size_t N>
Colordata(T (&arr)[N])
{
length = N;
size = sizeof(arr);
T dataArr[length];
for (int i = 0; i < N; i++)
{
dataArr[i] = arr[... | There are many problems with this code, but the one you asked about is happening because of the signature of the conversion operator:
template <typename TCast>
operator TCast() const
If you try to cast to a Colordata<float> then TCast will be the type Colordata<float>, and not float as the implementation assum... |
69,120,126 | 69,181,401 | How do I pass an array from Swift to MSL parameter (C++) | I want to make this custom CIFilter.
var dummyColors = [
CIVector(x: 0.9, y: 0.3, z: 0.4),
CIVector(x: 0.2, y: 0.5, z: 0.9),
CIVector(x: 0.5, y: 0.9, z: 0.3)
]
var normal = dummyColors.withUnsafeMutableBufferPointer { (buffer) -> UnsafeMutablePointer<CIVector> in
var p = buf... | I adopted this answer to your use case:
https://stackoverflow.com/a/58706038/16896928
Here's what I used for memory allocation:
var dummyColors = [
SIMD3<Float>(x: 1.1, y: 0.1, z: 0.1),
SIMD3<Float>(x: 0.1, y: 1.1, z: 0.1),
SIMD3<Float>(x: 0.1, y: 0.1, z: 1.1)
]
let pointer... |
69,120,164 | 69,120,223 | Why C++ standard split container class into multiple header file? | I've been learning C++ for a while and getting confused about its container usage. If I want to use certain container I have to manually include them one by one. For example, if I want to use "vector" container I have to type #include "vector", and if I need "list" container later I have to add #include "list".
Why wou... |
Why wouldn't C++ standard simply put every container class inside one header file, like #include "container", so that developers could care less about including them one by one?
Performance, specifically compile time performance. If you include everything, there is a lot of code that the compiler is going to have to... |
69,120,221 | 69,120,340 | What conversion happens when we use "while" in C++? | I'm using the Microsoft documentation and cppreference as background. Microsoft's site says that the expression to be evaluated in while must be an integral type, a pointer type or some conversible to these. Cppreference's site although says that while expects a bool type expression.
What does really happen? The expres... | According for example to the C++ 14 Standard (6.4 Selection statements)
2 The rules for conditions apply both to selection-statements and to
the for and while statements
...The value of a condition that is an expression is the value of the
expression, contextually converted to bool for statements other than
switch; i... |
69,120,846 | 69,121,007 | Why am I getting a totally random number when trying to iterate through an array and adding up the sum by using sizeof()? | I am trying to get the size of an array, using that for the expression in my for loop, and getting a random sum when I compile.
#include <iostream>
int main()
{
int prime[5];
prime[0] = 2;
prime[1] = 3;
prime[2] = 5;
prime[3] = 7;
prime[4] = 11;
int holder = 0;
for (int i = 0; i < s... | The error is in your use of sizeof(). It returns the total size of what is passed in. You passed in an array of 5 integers. An int is typically 4 bytes, so your sizeof() should return 20.
The bare minimum fix is to change your for loop Boolean Expression:
i < sizeof(prime) becomes i < sizeof(prime) / sizeof(*prime)
It ... |
69,121,205 | 69,121,264 | C++, i use the function at() from Vector, but i have problem |
cannot convert '__gnu_cxx::__alloc_traits<std::allocator<std::__cxx11::basic_string<char> >, std::__cxx11::basic_string<char> >::value_type' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'gcc
sincerely i don't know why and how to correct this.
#include <stdio.h>
#include <conio.h>
#include <string>
#include... | In this line
printf ( PasswordString.at(Lettere_Scritte) );
The function printf needs a const char* but your are giving it a std::string.
In addition to the type mismatch, you should never ever pass arbitrary data as the first parameter of printf, because it will try to interpret format codes.
If you really want ... |
69,121,541 | 69,121,757 | What is the reason for core dump in my function (detect_duplicates) to be specific? | I have 3 functions here, and the compiler is going through the first 2 functions, but it is not entering the 3rd function(detect_duplicates).
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
};
struct node* head = NULL;
void createLL(int a[], int n)
{
head = (struct nod... | When you want to access the next of temp2 in
temp2 = temp;
while (temp2->next != NULL) {
y = temp2->data;
if (x == y) {
cout << y << " ";
}
temp2 can be a nullptr which may cause a segmentation fault, because it points to nothing and you are trying to access it's member.
|
69,121,575 | 69,121,684 | How to catch std::variant holding wrong type in compile-time? | I have following piece of code:
#include <iostream>
#include <string>
#include <map>
#include <variant>
using namespace std;
template <class... Ts>
struct overloaded : Ts...
{
using Ts::operator()...;
};
template <class... Ts>
overloaded(Ts...)->overloaded<Ts...>;
using element_dict = std::map<string, string>;
u... | The easiest way to get that situation to fail at compile-time is to simply not include the overload lambda that catches non-string and non-element_dict typed items; that is, remove
[](auto /*elements*/) { throw std::runtime_error("wrong type"); }
Then it will fail at compile-time. Basically, by including that case, yo... |
69,121,697 | 69,123,238 | Short question about cin and input buffer | So, after learning a bit about the input stream and how the extraction operator works, is it basically okay to say this about the following code?
string a;
cin >> a;
This will basically extract whatever there is in the input stream, but if the stream is empty it basically asks the user to input something? Like is that... | std::cin is an object instance of the std::istream class, which has a std::streambuf object associated with it.
std::streambuf contains a memory buffer inside of it.
By default, std::cin uses an implementation of std::streambuf that reads from the calling process's STDIN stream.
When operator>> reads from std::cin, std... |
69,121,718 | 69,121,772 | no suitable conversion function from "const std::string" to "char *" exists? | im trying to make a simple program that list all txt file in the directory then append hello world in them but i face an issue while passing the vector into WriteFiles Function
this is the following code i've tried to fix it for a while any oil be grateful for any help
#define _CRT_SECURE_NO_WARNINGS
#include <... | WriteFiles(it->c_str()); will fix the problem. Iterators act a lot like pointers, so that's how you access a method indirectly.
|
69,121,733 | 69,121,894 | How to Understand "Pass By Reference Within a Function" w3schools example? | I'm having a hard time understanding how this example from the w3schools tutorial works.
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum... | Try this
#include <iostream>
void change_val_by_ref(int &x)
{
x=100
}
void change_val_by_val(int x)
{
x=50;
}
int main()
{
int whatever=0;
std::cout<<"Original value: "<<whatever<<"\n";
change_val_by_ref(whatever);
std::cout<<"After change by ref: "<<whatever<<"\n";
change_val_by_val(whate... |
69,121,803 | 69,121,984 | Array of objects being corrupted after using cout | After a few days of my question being closed, and my edits that would answer all of the questions in the comments not being approved, I have decided to re-post with a few changes.
I am new to c++, but I am an experienced programmer. I am trying to create a chess engine, as I have done it in python but I want it faster.... | The objects bq_r etc. defined in your Chess::Chess() constructor have their lifetimes end when the constructor finishes, so the array is full of dangling pointers which can't validly be used.
I'd recommend instead:
#include <memory>
class Chess
{
private:
std::unique_ptr<Piece> board[8][8] = {};
public:
Chess(... |
69,122,019 | 69,122,149 | Downcast with static cast | I have this hierarchy (methods are simplified):
struct BaseExpr {
explicit BaseExpr(ExprType expr_type) : expr_type_(expr_type) {}
virtual ~BaseExpr() = default;
template<typename T>
T const* As() const {
if (expr_type_ == T::expr_type) {
return static_cast<T const*>(this);
}
return nullptr... | You are already paying for the cost of having a vtable, since you're using virtual functions and the like. So unless performance is a real problem (as evidenced by profiling), if you really, really need to do this (and you should definitely reconsider any code where you need to do this), just use dynamic_cast. It makes... |
69,122,226 | 69,123,821 | I want to make a C++ enum of QString formats to display a QTime | I've been working with C++ on a Time class in Qt and I need to write an enum class that contains the formats that I use in showTime(). Because of the nature of the QString formats I've been getting the following error, the value is not convertible to 'int'. I would gladly appreciate any help or suggestions.
P.S: Here's... | I used a switch statement
enum class TimeFormat {
format1,
format2,
format3,
};
class Time {
public:
Time();
~Time();
void setTime(int h, int m, int s);
QString showTime() const{
QString f;
switch (format) {
case TimeFormat::format1:
f="hh:mm:ss";
... |
69,122,354 | 69,122,558 | Convert at::Tensor to double in C++ when using LibTorch (PyTorch) | In the following code, I want to compare the loss (data type at::Tensor) with a lossThreshold (data type double). I want to convert loss to double before making that comparison. How do I do it?
int main() {
auto const input1(torch::randn({28*28});
auto const input2(torch::randn({28*28});
double const lossTh... | Thanks to GitHub CoPilot which recommended this solution. I guess I should leave my job now. :(
The solution is using the item<T>() template function as follows:
int main() {
auto const input1(torch::randn({28*28}); // at::Tensor
auto const input2(torch::randn({28*28}); // at::Tensor
double const lossThresh... |
69,122,441 | 69,124,089 | UIAutomation missing to catch some elements | I'm using the code above to walk through the descendants of a window, however, it's not catching everything like I can see using inspect.exe.
Currently testing in the chrome browser, in this current webpage I'm writing this question, it's catching just current opened pages, bookmarks, and browser buttons, it's missing ... | Testing with Chrome version 93 and Windows 10:
If chrome window is at least partially visible, the first UIA child document in chrome is html page of the active tab, and you can walk the UIA elements in this page.
If chrome window is not visible, you cannot access the page content with UIA. You can only use UIA to acce... |
69,123,321 | 69,225,941 | QWebEngine view loads webpage slowly | I am loading a webpage using the QWebEngineView like
web_engine_view = new QWebEngineView();
QWebChannel* channel = new QWebChannel(web_engine_view->page());
web_engine_view->page()->setWebChannel(channel);
channel->registerObject(QString("my_object"), my_object);
m_web_engine_view->load("path/to/local/html")... | Updating my QT version to QT 5.15.0 made it much faster. Also, I had 3D OpenGLWidgets constantly rendering in parallel in my application. I had to make sure the rendering didn't get updated every frame. This significantly improved the performance of the QWebEngineView.
|
69,123,608 | 69,124,083 | c++ calculate the sum of two array's and output a boolean '0' if result even else '1' if odd |
I was hoping to find an alternative solution/method to mine for solving the above question given the set parameters. Essentially the way I went about it was to loop through the two arrays simultaneous and add the corresponding values. First place would have been to use a conditional operator.
#include <iostream>
#incl... | For starters the function should be declared like
void myLists( const int list1[], const int list2[], int list3[], size_t size ;
because neither the first parameter nor the second parameter are being changed within the function.
The function does not set elements of the third array. As the third array is zero initiali... |
69,123,627 | 69,137,730 | Python ctypes returned c_char_p is corrupted | I have a C++ interface that contains the following:
extern "C"
{
char const* getValForEntry(Entry e)
{
std::string no_val = "__err::no_val";
if (handles.find(e) != handles.end())
{
std::string val = handles[e]->get_value();
return val.c_str();
}
... | See PaulMcKenzie and user4581301 comments above for explaination. The local variable val was going out of scope, which led to undefined behavior.
|
69,123,916 | 69,124,245 | Is there any way to hook insertion and deletion operations for the std containers? | Let's say, we are going to subclass the std::map and we need to catch all insertions and deletions to/from the container. For example, in order to save some application-specific information about the keys present in the container.
What's the easiest way to do this, if at all possible?
Probably, the most obvious way to ... | There is no way to do that in the general case. Inheritance is not a good idea because std::map is not polymorphic and no virtual dispatch will happen when you use a pointer to a map. You might as well use a simple wrapper class at that point and save yourself a lot of hassle:
#include <iostream>
#include <map>
templa... |
69,124,321 | 69,125,644 | (C++) Fastest way possible for reading in matrix files (arbitrary size) | I'm developing a bioinformatic tool, which requires reading in millions of matrix files (average dimension = (20k, 20k)). They are tab-delimited text files, and they look something like:
0.53 0.11
0.24 0.33
Because the software reads the matrix files one at a time, memory is not an issue, but it's very slow. The fo... | The fastest way, by far, is to change the way you write those files: write in binary format, two int first (width, height) then just dump your values.
You will be able to load it in just three read calls.
|
69,124,597 | 69,147,075 | How do I access the member `top` of a BIGNUM in OpenSSL 1.1.x? | I'm currently trying to port an old C++ project over from OpenSSL 1.0.2 to OpenSSL 1.1.1. It's worth noting that this is not my code, but from an open source project, and I can't tell exactly what this part is supposed to do.
One file uses this piece of code (simplified for this post):
BIGNUM *d; //Assume this is a val... | The full example you linked, copies out the bits from a BIGNUM (for the RSA d exponent) into a different structure. It does not only access d->top (which is the number of used chunks), but also d->d (the pointer to the actual chunks) as the source of the memcpy in the next line.
The canonical way to copy out the bits o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.