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 |
|---|---|---|---|---|
66,372,442 | 66,376,539 | C++ initializer list overload disambiguation | I have a question about C++ initializer list disambiguation which exhibits different behaviors between gcc, clang and Visual Studio.
I wonder if this is "undefined behavior" (incorrect program) or if one of these compilers has a bug. Any idea?
Consider the following declarations:
class Arg
{
public:
Arg(int i);
};
... | {4} to const std::initializer_list<Arg>& is a user-defined conversion.
{4} to int is a standard conversion.
The latter wins. This is a GCC bug.
List-initialization to an initializer_list beats others when the conversion sequences are of the same form. They are not here.
|
66,372,539 | 66,372,817 | How to sort class objects array using the sort() in C++ | I was doing one programming problem where it is required to sort the class objects.
So, i used sort() to sort the array of objects but i couldn't do it, i read somewhere it requires lambda expression to that, but i don't know about them yet.
So, if you can help me with this question with some explanation of lambda expr... | Sorting is about comparing elements and knowing which one is "lower" than other one (ie, if I sort {5,3,1} into {1,3,5}, it is because 1 is lower than 3 and 3 is lower than 5)
So, it depends on what kind of logic you want to follow for your sorting algorithm (you could, for example, sort them by their member int dur). ... |
66,372,563 | 66,372,599 | How do I create a dynamic array with real numbers? | I know the syntax for dynamic arrays with integers, but when I try to create a dynamic array that stores double values, it gives me an error message. (error: expression in new-declarator must have integral or enumeration type)
ifstream f("date.in");
ofstream g("date.out");
double n;
f >> n;
double* v = new double[n];
... | As the error message suggests, double n; cannot be used as the number of elements, which must be an integer. It should be int n;.
|
66,372,656 | 66,627,236 | Is there any way to write non blocking MPI code without using MPI_Wait? | I'm having this code which works fine. My question is that is it possible to have a non-blocking code without MPI_Wait? I am thinking that whether by this way, my code behaves as a blocking mode inadvertently. Also, to confirm that this is a non-blocking code, shall I measure execution time? and if it is faster, I can ... |
My question is that is it possible to have a non-blocking code without
MPI_Wait
Yes, one can have a non-blocking code without the MPI_Wait; the problem is, however, that the data used on the non-blocking communication routines can get into inconsistent states. In other words, one cannot be sure if that data can be sa... |
66,372,916 | 66,372,955 | Google Kickstart 2020 Round A 2020 Wrong Answer | I was trying to solve this problem from Google Kickstart: https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc7/00000000001d3f56#problem
For some reason, it succeeds on the sample set, but fails on test set 1.
I have tried many test Cases and the code works properly for all of them. Whats wrong wit... | The line
while (max < T) {
is wrong. The limit should be the number of horses, which is N. It should be
while (max < N) {
|
66,373,198 | 66,375,136 | Regexp for URL validation | I am writing my own http server. Checking and validating headers and values from requests, oddly enough, is one of its tasks. I found a page
with a table comparing different regular expressions and decided to use one of them:
_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!... | You need to replace all \x{XXXX} with \uXXXX since ECMAScript regex flavor does not support \x{XXXX} notation. Next time you use regex online testers, make sure you select the appropriate regex flavor (C++ uses ECMAScript by default, not PCRE).
Next, you can also replace \/ with / (you only need \/ at the online regex ... |
66,373,206 | 66,373,266 | Array[0] giving different results | Why in the following:
int hashTable[0b11111111111111111111];
int hash = 0;
hashTable[hash]++;
if (hashTable[hash] == 1)
// do stuff
is the condition not necessarily triggered?
| The array
int hashTable[0b11111111111111111111];
is not initialized and have indeterminate value. You have to initialize it like this to have it correctly work:
int hashTable[0b11111111111111111111] = {};
Since the array is very big, using std::vector is better.
std::vector<int> hashTable(0b11... |
66,373,284 | 66,373,977 | Constructor can't infer template argument from concept | Why constructor can't infer template argument from concept in this situation? Also maybe there is a way to not specify concrete template type in serializer concept.
#include <span>
template <class impl_t>
concept stream = requires(impl_t &impl) {
{ impl.write(std::span<const std::byte>{}) };
};
struct any_t {};
tem... | That's just not the way deduction works in C++20.
For class template argument deduction (CTAD), the client class template needs to deduce two types (stream_t and serializer_t) and the constructor you have only uses one of those types, so the language has no idea where the other one could come from.
You can help this by... |
66,373,539 | 66,376,717 | Issue with passing integer vertex attributes with "in" keyword | I'm working on bone animation. I have a vertex struct that basically looks like
struct MeshVertex
{
glm::vec3 pos;
glm::vec3 normal;
glm::vec2 tex;
glm::vec3 tangent;
glm::vec3 bitangent;
uint32_t ids[4] = {};
float weights[4] = {};
void print() const;
};
The mesh is a basic cube with ... | Okay I solved the issue, even though I don't quite understand how this fixes the problem. My preferred graphics processor was on auto but when I forced it to use the NVIDIA processor over my integrated graphics, everything works out fine. image of solution
Update :
I think it is as simple as my Intel processor graphics... |
66,373,606 | 66,374,132 | C++ Using u8 strings as unsigned strings | C++20 introduced char8_t as the type for UTF-8 string and character literals.
char8_t is for the most part equivalent to an unsigned char, therefore, any arithmetic, logic, or bitwise operations will act as if it were unsigned, emitting unsigned operations instead of signed operations.
Consider a base64 conversion algo... | std::u8string base64::encode(std::span<std::byte const> binaryData);
inline std::u8string base64::encode_string(std::u8string_view u8sv) {
//todo call encode
}
inline std::u8string base64::encode_string(std::string_view sv) {
//todo call encode
}
take a span of const bytes. Have helper methods that take u8 and ch... |
66,374,088 | 66,374,501 | Callable class objects in C++ : no matching function for call to ‘std::tuple<T>::tuple(<brace-enclosed initializer list>)’ | My code consists of 2 files: main.cpp and utils.hpp. The contents of those files are given below:
utils.hpp
#ifndef UTILITY_HPP
#define UTILITY_HPP
#include <iostream>
#include <thread>
#include <future>
#include <functional>
#include <chrono>
using std::chrono::milliseconds;
class CallableStoppableTask {
std::p... | This line is fine
(*f.get())(); // COMPILE TIME ERROR: what is the error in this?
but shorter version
(*f)();
is better.
ar_uptr_task.fill(std::move(std::make_unique<CallableSampleTask>()));
doesn't make any sense. fill takes source as const object, how do you want apply move operation on const source object [als... |
66,374,490 | 66,376,131 | Why does std::ifstream not throw an exception even when exceptions are specifically enabled? | So, by default std::ifstream doesn't throw an exception when you open an invalid file path. It rather silently fails and if you don't use the fail() method or similar to check, it will easily go unnoticed which is quite bad.
Since I want to get exceptions on any kind of failures so I can be informed automatically, I tr... | On failure, open() sets failbit, not badbit. You are not asking the ifstream to throwing an exception on failbit.
|
66,374,558 | 66,417,773 | OpenMP atomically update array values | The problem that I am trying to solve is the following:
I have a big point set which I try to split into smaller ones. I know the sizes of the smaller ones, and I am trying to populate the smaller ones using the bigger one in parallel. In order to do that, I have an array of indices per smaller pointset, which will hel... |
Is there a way to enforce the same order of operation as the i
variable?
You try to use the OpenMP ordered clause
#pragma omp parallel num_threads(numberOfThreads) shared(pointsArray, points, currentIndices) default(none)
{
int index;
int currentIndexInCurrentPointSet;
double point[3];
#pragma omp fo... |
66,374,643 | 66,374,864 | Can't pass arguments to Python function while embedding Python in C++ | I'm embedding a Python module in my C++ code and I am using Python/C API.
I need to call a Python module function and get the results.
The function gets an unsigned integer and a double as input arguments and outputs a list.
I use the following to call the function:
unsigned int num_units = 10;
double max_time = 15.12;... | There should be exactly one format string (which may be NULL) followed by any/all inputs. Parenthesis are for specifying tuples of size zero or one, which you don't mention needing. So, just do this:
PyObject *output_list = PyObject_CallMethod(sample_object,
"get_list", "Id", num_units, max_time);
Full exampl... |
66,374,727 | 66,374,811 | How to search a window name for an existence of an element of an array? | I'm very inexperienced with C++. I have a program that runs well. Part of the code relies on identifying some text in the name of a pop up window.
This is the partial part of code (which works fine)
std::string firstNeedle("DX");
std::size_t firstSearch = upperCaseWindowName.find(firstNeedle);
std::string s... | Firstly, it becomes slightly more sustainable if you rewrite it like this:
if (upperCaseWindowName.find("DX" ) != std::string::npos ||
upperCaseWindowName.find("BENJA") != std::string::npos ||
... )
Or you can use a for loop:
std::string patterns[] = {"DX", "BENJA", ...};
bool found = false;
for (const std::... |
66,374,841 | 66,377,245 | Assign function as default parameter using & operator | I was studying an example of setting information inside of a QML table in Qt and I don't understand what is being passed as default parameter:
int rowCount(const QModelIndex & = QModelIndex()) const override
{
return 200;
}
The source of the example can be found here.
My guess is that const QModelIndex & = QModelI... | As stated in comments:
int rowCount(const QModelIndex & = QModelIndex()) const override
defines the overridden member function rowCount, its one unnamed argument has a default value of QModelIndex(). For any type T, T::T() defines its default constructor, so QModelIndex() is a default constructed QModelIndex object. T... |
66,375,096 | 66,375,427 | Creating a vector of char pointers in C++ | I have to make a vector that stores char pointers. Each pointer should only point to a single char like 'a' or 'b'. I don't get any compile errors, but when I run my program, it crashes. I cannot use std::string or any of its functions, they have to just be characters.
std::vector<char*> myVector;
myVector.reserve(10);... | You should use push_back method of vector instead of using at when you have not pushed anything inside vector. Also, you should use new char('a') instead of using bracket, which has other meaning. Look at this minimal code that works just fine:
#include <iostream>
#include <vector>
int main()
{
std::vector<char*> ... |
66,375,554 | 66,375,600 | Why does the While Loop keeps executing infinitely in C++ even when the condition is met? | I made Rolling Dice Program in C++,
it's working well except for that the While Loop doesn't break (attempt != 6).
It keeps filling random numbers (1-6) infinitely, it's supposed to stop when attempt == 6 but it doesn't.
Can you adjust my code and tell me what's wrong with? I'm a beginner in C++.
#include <iostream>
#i... | You have two attempts. The attempt inside the loop body is not visible from the outside of the loop body. while (attempt != 6 ) is outside the loop body (before the loop body), so it sees the first attempt, which is not changed in the loop.
To fix, remove the declaration of attempt inside the loop body and overwrite th... |
66,375,981 | 66,379,036 | Explanation on additional dependency libs when creating dll project in Visual Studio | when creating dll project in visual studio (2017 in my case) there are quite a lot of libs out into additional dependencies
kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;
Is there somewhere a descriptions why so many are nee... | These are the libraries that interface with Windows.
For more details about what they are for, I suggest you could refer to the link: https://stackoverflow.com/a/36018689/11872808
kernel32 : Process and thread management, file and device I/O, memory allocation (keep this, the C and C++ runtime libraries and compiler-ge... |
66,376,138 | 66,378,473 | Big-O time complexity of 4sum problem. Brute force approach | I am doing this problem called 4sum. Link to problem.
Given an array of n numbers and an integer(this is the target
element). Calculate the total number of quads (collection of 4
distinct numbers chosen from these n numbers) are there for which the
sum of quad elements will add up to the target element.
I wrote this ... | if (a[i]+a[j]+a[k]+a[l]==target) {
s.insert({a[i], a[j], a[k], a[l]});
}
This gets executed O(N^4) times, indeed.
to get the upper bound we assume that every quad that we check satisfies the condition.
Correct.
For N^4 insertions --- complexity is N^4 log(N^4).
Not so, because N^4 insertions do not necessa... |
66,376,188 | 66,376,635 | CMake cant find instance of Visual Studio 15 2017 generator, but works fine with Visual Studio 16 2019 | Similar to CMake: Visual Studio 15 2017 could not find any instance of Visual Studio but in my case I've got my main installations version of MSVC generator working. It's the 2017 generator that doesn't seem to be working for me. Here is my installation setup:
My understanding is that this should work, I should have t... | I think this is a case of unfortunate naming. Installing the "VS 2017 C++ x64/x86 build tools" only installs the compiler, linker and standard libraries and not actually the entire "Visual Studio Build Tools 2017" which include MSBuild. But you need the latter to use the "Visual Studio 15 2017" generator. You can find ... |
66,376,296 | 66,376,523 | How do I find the average of a column in a list? | I have a list of vectors currently, stored as a std::list<Vec3f> unsortedRays;
-4.5 4.5 -8.66025
-3.5 4.5 -8.66025
-2.5 4.5 -8.66025
-1.5 4.5 -8.66025
-0.5 4.5 -8.66025
I'm generating these earlier in the program and can calculate the size beforehand (or after too).
How do I find the average of each column (0, 1, ... | You could do something like this:
std::vector<std::vector<double>> matrix;
double c1, c2, c3;
double sum1=0.0, sum2=0.0, sum3=0.0;
while (my_file >> c1 >> c2 >> c3)
{
std::vector<double> row;
row.push_back(c1);
row.push_back(c2);
row.push_back(c3);
matrix.push_back(row);
sum1 += c1;
sum2 += ... |
66,376,544 | 66,376,779 | deduced conflicting types for parameter '_BIter' ('int*' and 'int') | I was trying to implement a simple reverse array function:
void reverse(int (&arr)[], int n)
{
int start = 0, end = n - 1;
while (start <= end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
In my main() I have this:
int brr[9]{10, 20, 30, 40, 50, 60, ... | In this function declaration:
void reverse(int (&arr)[], int n);
the type of arr is a reference to an array of unknown bound. However, the argument brr is of type int [9], and you cannot bind a reference of an array of unknown bound to an array of known bound.
You have several options:
You could decay the array to a... |
66,376,553 | 66,380,209 | Using {fmt} & source_location to create variadic-template-based logging function | I'd like to create a simple log function in C++ which prepend the code location to the log message. I'd like to avoid macros overall as well as the usage of __FILE__ & __LINE__.
Note that the format string is always a compile-time string, and I'd like to have a much computation as possible on compile time (the target m... | You can do it with a struct that represents the format string and location:
#include <fmt/core.h>
#include <source_location>
struct format_string {
fmt::string_view str;
std::source_location loc;
format_string(
const char* str,
const std::source_location& loc =
std::source_location::current(... |
66,376,976 | 66,377,383 | Does a destructor that left prematurely after throwing an unhandled exception frees member data? | AS I know a Destructor works the reverse order to the Constructor:
Constructor initializes member data (in ctor-init list) then executes its body.
Destructor executes its body then destroys member data (in Destruction phase).
I know that a Destructor shouldn't throw an exception and if it does so then it should itse... |
If a destructor raises an exception without handling it there then should it Destroy member data
Yes.
So does Foo's Dtor frees b after throwing without handling the exception?
b has a trivial type so its "destructor" does nothing. But yes, the member is destroyed. Members aren't "freed".
|
66,377,805 | 66,378,009 | Can I legally reuse fields in aggregate struct initialization? | The program below compiles and runs without warnings with gcc:
#include <iostream>
struct A { int a, b; };
int main() {
A x = {.a = 42, .b = x.a}; // <-- b is initialized from x.a
std::cout << x.a << ' ' << x.b << std::endl;
}
42 42
x is essentially used during its initialization. This is very handy for cases wh... |
[dcl.init.aggr]
The initializations of the elements of the aggregate are evaluated in the element order.
That is, all value computations and side effects associated with a given element are sequenced before those of any element that follows it in order.
Thus, x.a has been initialised before initialisation of x.b. So ... |
66,378,500 | 66,378,561 | Why do the following 2 of 3 versions std::visit not work | I was trying to use a std::visit to access a member in a variant, and throw an error if that member wasn't available.
I was able to get a working solution but I found the errors in for my first two attempts unintelligible.
Does anybody know why "version 1" and "version 2" don't work?
#include <variant>
#include <vector... | Your version 1 and version 2 mean exactly the same thing, so I'll only consider version 2.
When you invoke wacky_visitor, you have two overload choices:
// first overload
template <typename L, typename R>
bool operator()(L const&, R const&);
// second overload
template <typename L, typename R>
???? operator()(const L&... |
66,378,657 | 66,381,088 | Ordering k ordered linked lists? | I was reading the solutions here: https://leetcode.com/problems/merge-k-sorted-lists/solution/
on how to union k sorted linked lists into one linked list.
A trivial solution would be to write a function that does the job for 2 linked lists, call it on first 2 lists then call it again with the previous result and the 3r... | Let's say the length of i-th linked list is l[i], the total length of all linked lists is L. Also I assume you (the reader) knows that 2-way merge of two ordered lists has O(a+b) time complexity, where a is the length of the first list and b is the length of the second.
The second solution (solution 2) has a stable tim... |
66,378,914 | 66,395,782 | MKL example code compiles fine with cmake but crashes when run | I am trying to run following example from MKL website.
#include <stdio.h>
#include "mkl_vsl.h"
int main()
{
double r[1000]; /* buffer for random numbers */
double s; /* average */
VSLStreamStatePtr stream;
int i, j;
/* Initializing */
s = 0.0;
vslNewStream( &stream, VSL_BRNG_MT19937,... | in that case, you may try to relink the test with sequential mkl's library (mkl_sequential.lib instead of mkl_intel_thread.lib ) and try to execute directly in cmd. Or just put libiomp5md.dll into exe file directory.
|
66,378,988 | 66,379,619 | Character missing from output c++ | I was trying to solve a problem from codewars and it seems like I have a problem with my output.
This is the problem I am trying to solve
This is my output and my code
The code works when I run it on codeblocks. There is a missing " in the output and I think that is due to the NULL character that I am adding at the end... | It seems like you're making it way more complicated than it needs to be which is causing simple mistakes to be overlooked. Modern C++ practices tries to alleviate these concerns by doing the work for you, such as iterating over a container and erasing a specified element from that container.
#include <algorithm>
#inclu... |
66,379,272 | 66,388,463 | How to get the substring matched by a boost.spirit numeric parser? | I want to use qi::int_parser<int64_t> to parse an integer value (it's really convenient how it automatically checks for overflows, handles the INT_MIN case, and so on). But, I also want to get the substring that the int_parser matched, because I want to print a warning message if it has extraneous characters (i.e., a p... | I'd simplify using a proper rule - so you don't need to spell out as_string in the parse expression.
There is something wrong with the way it works in this particular case (which should be reported as a bug to the library maintainers). However I could work around it by adding an eps parser inside the raw directive:
r %... |
66,379,414 | 66,379,729 | Im having trouble staying in the loop the total is also supposed to add till the user exits the loop with an input of N || n | I cant seem to get my do while loop right, I am trying to make a program that takes an order asks if there are anymore orders and if there are then it will restart the loop and keep track of the total.
If the user picks N then the program exits and prints the total in full. The tax rate and zip codes will come into pla... | Your code has multiple problems. I'm assuming that you want this behavior:
Show the menu
Ask "your choice?"
Wait for the user to choose one of the options
Ask the user if he wants to order anything else
If the user answers "Y", go to step 2
If the user answers "N", get out of the while loop and proceed with the progra... |
66,379,999 | 66,380,107 | Difference between `import` and `#include`? cpp20 | I don't understand why
I saw import std.core; here
I can't import std;
I can't import std.iostream;
I can #include <iostream>
Can you explain why above is happening? Maybe i guess std.iostream is not a module. Then why 1. works?
@Someprogrammerdue provided this reference, and its says
import <iostream>; // im... |
I don't understand why
I saw import std.core; here
You saw what you did because you read the page and that's what was written there.
I can't import std;
This is because the C++20 standard library doesn't define modules. And because no other library can (or shouldn't) define module std because that module name i... |
66,380,368 | 66,384,015 | Seg fault when using Botan | I'm just getting started with Botan. I have included the botan_all.h in my code file and am linking to the libbotan-2.a library when building.
Here is the relevant part of main.cpp:
#include "botan_all.h"
int main(int argc, char *argv[])
{
const std::vector<uint8_t> key = Botan::hex_decode("2B7E151628AED2A6ABF7158... | This is likely caused by your Botan version not being build with support for the specified algorithm. The method CipherMode::create returns a nullptr if the specified algorithm is not found (reference). You would then have to check the result, e.g.:
if (enc == nullptr) {
throw std::runtime_error{"Cipher not ... |
66,381,610 | 66,382,696 | Avoid QProcess being killed (QProcess: Destroyed while process is still running) | I tried to run this code:
QProcess process;
process.setWorkingDirectory("D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target");
process.setProgram("java.exe");
process.setArguments({"-jar","StackExp-1.0-SNAPSHOT.jar"});
process.start();
and cmd won't open, and doesn't execute. It just shows this message:
QProces... | You are probably calling the destructor of QProcess before it is finished, which kills the process as mentioned in the docs. Note that the destructor is called when process goes out of scope.
Different solutions exists:
Wait for process to finish: waitForFinished
process.waitForFinished (-1); // -1 = no time out
Con... |
66,381,697 | 66,381,750 | C++: No default constructor exists for parent class | I am writing the class file for a binary search tree (BST), which extends from the class (Tree). However, I receive the following error in my IDE for the current file (bst.cpp)
stating:
no default constructor exists for class "Tree"
In compilation, I receive the following error:
no matching function for call to ‘Tr... | You got it there, Tree does not have a default constructor. As a result of that, you cannot default-construct a BST, because the Tree that is inside it will not know how to construct itself.
You have to member-initialize it.
BST::BST() : Tree(1) {}
Are you sure you don't want to pass that value to the constructor of B... |
66,382,186 | 66,388,378 | Possible MSVC compiler bug | Given shared_ptr variable declared in condition clause of for loop and for loop body contains if/continue statement, microsoft compiler (as of version 2015) generates extra destructor call (two total) per loop iteration. This causes destruction of Item objects that should be out of reach of Holder interface users.
See ... |
As far as I can understand, getItem should yield a copy of ItemCPtr and no Items could be modified through Holder interface.
Your understanding is 100% accurate. That is exactly the behavior described for the C++ standard's abstract machine.
Even under the as-if rule, which allows compilers to optimize, the observabl... |
66,382,422 | 66,382,602 | Why is there no clear() function for the inbuilt stack interface in C++? | I have to empty a stack before using it further more. I do understand that it can be done like:
while (!mystack.empty()) { mystack.pop(); }
Is there a specific reason for not having this function? or its just that the first time it was made, no one felt its requirement and has been just left out
Also, the stack interfa... | While it would possibly be more readable to have an explicit .clear(), even without it you can empty a stack like this:
mystack = {};
|
66,382,540 | 66,382,599 | How do i go about developing a facial identification software that identify different users and show their name from an image database using C++ | I'm trying to develop a facial recognition software that holds a database of different images and uses the camera to identify each person and shows their name on screen. I'm more familiar with using C++ and I assume python might be the best language to get the job done but I want to know how I can go about it with C++.... |
OpenCV must be installed on the local machine.
Paths to the classifier XML files must be given before the execution of the program. These XML files can be found in the OpenCV directory “opencv/data/haarcascades”.
Use 0 in capture.open(0) to play webcam feed.
For detection in a local video provide the path to the video... |
66,382,983 | 66,383,231 | How do I enable conversion from one class to another? | I have a situation where I want to allow the conversion from A to B:
A a{4};
B b = a;
This is the setup:
class A
{
public:
explicit A(int value)
: member{value}
{
}
private:
int member;
};
class B : public A
{
public:
explicit B(A a)
: A{a}
{
}
};
int main()
{
A a{4};... |
Clang-Tidy complains that single-argument constructors must be marked explicit to avoid unintentional implicit conversions.
Frankly, I strongly doubt that this is what clang-tidy says ("must be"). Single argument constructors that are not declared explicit are converting constructors. They can be evil, because to som... |
66,383,078 | 66,394,492 | Does the use a simple-template-id in a nested-name-specifier unambiguously mean a class template specialization? | struct A{
template<typename U>
void T(){}
};
struct B{
template<typename U>
struct T{
using type = U;
};
};
struct C:A,B{
};
int main(){
C::T<int>::type d;
}
This example is accepted by neither GCC nor Clang.
As per basic.lookup.qual#1
The name of a class or namespace member or enumera... | The lookahead required to have the lookup for T depend on the :: even as the interpretation of < depends on the meaning of T is considered undesirable. As such, lookup for a name followed by < is not restricted to types and namespaces regardless of any >:: found later. P1787R6 fixed this, restricting the special look... |
66,383,344 | 66,383,833 | Tensor creation and destruction within a while loop in libtorch C++ | I have just started with libtorch and I am having some trouble with while loops and tensors :roll_eyes:
So, my main func looks like so:
int main()
{
auto tensor_create_options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU).requires_grad(false);
torch::Tensor randn_tensor = torch::randn({10}, t... | You have a shadowing issue here, try the loop that way:
while (randn_tensor_size > 5)
{
std::cout << "==> randn_tensor shape: " << randn_tensor.sizes() << std::endl;
randn_tensor.reset(); //reset();
randn_tensor = torch::randn({3}, tensor_create_options);
std::cout << "==> randn_tensor shape 3: " << ran... |
66,384,054 | 66,384,173 | How to feed a shared_ptr to a template function that shall add various data types to a vector? | In this question it was suggested to use std::shared_ptr instead of std::unique_ptr. However I am not able to make this work when feeding this shared pointer to my function:
std::vector<std::unique_ptr<segment>> v3;
//VERSION 5:
auto myLine2 = std::make_shared<Line>(start, end);
add_segment(v3, myLine2);
... | You can't "move" the thing inside a shared_ptr into an instance of a unique_ptr. If you could, all kinds of problems would occur as a result of two different smart pointers trying to delete the thing inside it when they get released.
Instead, just delcare your vector as :
std::vector<std::shared_ptr<segment>> v3;
And ... |
66,384,216 | 66,388,637 | Why doesn't visual studio find soundio.h? | I've been working with visual studio 19 and cmake. The initial objective is to link spdlog and libsoundio libraries to my project, to achieve it the following CMakeFile was created to compile my project.
cmake_minimum_required (VERSION 3.8)
set(APPNAME DrumHero)
project($APPNAME)
#C++ version
set(CMAKE_CXX_STANDARD 1... | If your code has sucessfully compiled, you have two options: Either copy the libsoundio.dll in the same folder as your .exe, or else, copy that DLL into a typical Windows path for DLLs, for example, C:\Windows\System32.
The first method should be easier if you want to deploy your application to another computer. That i... |
66,384,258 | 66,393,243 | sws_scale, YUV to RGB conversion | I need convert YUV to RGB. I also need the RGB values to be in the limited range (16-235).
I try to use sws_scale function for this task.
My code you can see below. But after conversion I got the black pixel is (0, 0, 0) instead of (16, 16, 16).
Maybe there are some options to tell sws_scale function to calculate the l... | You may the source format to "full scale" YUVJ.
As far as I know, sws_scale has no option for selecting Studio RGB as output format.
Changing the input format is the best solution I can think of.
The color conversion formula of "JPEG: YUV -> RGB" is the same as the formula in your post.
Examples for setting the sourc... |
66,384,377 | 66,384,639 | C++ Initialization of member objects which do not have default constructor: | Similar questions have been answered but I still cannot find a solution to my problem. I am indeed not able to call the constructor of class Point inside class Rectangle. After having read some answers, I would approximately do it like this, but it does not work:
class Point {
public:
Point(int x, int y);
private:
... | It is not clear what you expected this line to do:
Rectangle(Point a, Point b) : Point(int x, int y);
The place to initialize members is not the constructors body. And the correct syntax for the member initiazer list is:
Rectangle(Point a, Point b) : a(a), b(b) {}
Note that the initializer list is a place where shado... |
66,384,530 | 66,384,645 | Why does spaceship allow mixed comparisons (different template instantiations) with nonsense results? | EDIT: This has nothing to do with spaceship. It is just that the use of spaceship obfuscated the real issue in my code (see answer for details).
I was surprised by the output of this program:
(If you like puzzles feel free to open the Godbolt link and try to spot the cause yourself)
#include <cstdint>
#include <cassert... | It's allowed because your conversion operator to T is not explicit. This allows both sides of the comparison to undergo a user-defined conversion to their respective T. So you end up with a float and a double. And then those can both be converted to double and a comparison can happen. But that comparison returns an std... |
66,384,758 | 66,386,450 | C++ print alphabet using char type like Excel formula =CHAR(CODE(A1)+1) with value of cell A1 is a | I'm learning char type, and I'm trying to print alphabet the way like I learnt from Excel, if value of cell A1 is a then cell B1 will be b after using the formula =CHAR(CODE(A1)+1). My code:
char test = 'X';
cout<<test+2;
Is there a way to make my code print Z instead of 90? Thank you very much!
| Yes! You need to use type casting. Here is the code:
char character = 'X';
cout<<char(character +1);
The code prints 'Y' instead of 89.
|
66,385,267 | 66,388,686 | DCMTK library says tag not found while dcmdump displays it | My program, for a Ubuntu 20 system using DCMTK 3.6.4-2, reads a dicom file (series) and gets the scale slopes from the corresponding tags, testing first whether they exist:
tmpfile.loadFile ( filename );
tmpdata = tmpfile.getDataset();
tmpdata -> findAndGetOFString ( DCM_RescaleSlope, tmpstring );
if ( !tmpstring.empt... | The tag you are looking for is inside a sequence (RealWorldValueMappingSequence). To get to the tag, you first have to get the sequence, something like this:
DcmSequenceOfItems* sequence;
OFResult result = tmpData->findAndGetSequence(DCM_RealWorldValueMappingSequence, sequence);
if (result.good() && sequence && !sequen... |
66,385,346 | 66,386,001 | Accessing an array using a pointer in a struct | I wanted to access the array elements using the struct attributes. I am able to print 1st and the 2nd element using the struct pointer (nameptr) while the remaining 3 elements has to be accessed using the (uint8_t ptr) which itself is a attribute of the 'struct name'.
#include <iostream>
struct name{
uint8_t b0;
... | This answer is based on the modified code as in revision 6 of the question.
If you have a structure of type name, not only a pointer, you can assign the array address to the pointer element ptr like this.
#include <cstdio>
#include <cstdint>
struct name{
uint8_t b0;
uint8_t b1;
uint8_t* ptr;
}*nameptr;
... |
66,385,592 | 66,387,615 | error LNK2001: unresolved external symbol (every static member of SFML library can't be loaded) | So, I have problem, when try to use any of static members of SFML Library like sf::RenderState::Default or sf::Color::Blue.
error LNK2001: unresolved external symbol "public: static class sf::RenderStates const sf::RenderStates::Default" (?Default@RenderStates@sf@@2V12@B)
But when I comment lines, I have access to sf::... | The troubleshooting steps I would undertake in this situation go from easiest to the inverse of that.
If I check the declaration of sf::RenderState::Default, can it be found?
If I create a new project with just this feature used, does the error persist?
If I redo my linking and directory searches, is the problem fixed... |
66,385,905 | 66,386,978 | Problem with Reversing Large Integers On Leetcode? | I was working on this problem from Leetcode where it has this requirement of reversing numbers whilst staying within the +/-2^31 range. I checked out other solutions made for this problem, and from there created my own solution to it. It worked successfully for numbers ranging from 10 to less than 99,999,999. Going mor... | Problem statement asks to return 0 if reversed number does not belong to integer range :
If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
In your code you checked if input fits in integer range but their arises a corner case when the integer has 10 digits... |
66,385,927 | 66,386,113 | Why does the definition of constructor make different value | I'm testing the piece of code below:
#include <iostream>
struct foo
{
foo() {}
int a;
};
struct bar
{
bar();
int b;
};
bar::bar() = default;
int main()
{
foo f{};
bar b{};
std::cout << f.a << '\t' << b.b << std::endl;
}
The output is 0 21946.
Well, it seems that the object f is i... | From cppreference:
Defaulted default constructor outside of class definition (the class must contain a declaration (1)). Such constructor is treated as user-provided
Therefore, none of the statements are value-initializations.
Both are default initialization because they have user-provided constructors. And the value... |
66,386,491 | 66,386,822 | How does a `cout` function actually works in c++? | Note:The code works fine and the o/p is desired too I just wanna know does cout displays into the screen or writes to ostream,and if it writes to ostream when does the ostream gets displayed .
I have following c++ code
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main()
{
string str... | Here is what you code does
Is there already an error/eof on cin? if yes get out
read something
if it is Quit IMMEDIATELY GET OUT
other operations
So when you type Quit it is not printed, simply because you never ask for this.
But that is not all. On an eof condition here is what happens:
Is there already an error/eof ... |
66,386,585 | 66,386,940 | Is it legal to have multiple const qualifiers? | As a result of some discussion about placement of const, I started to wonder if you can have multiple const qualifiers to the same type:
#include <iostream>
int main()
{
const const int a = 5;
std::cout << a;
}
Don't worry, I'm not going to write code like this
Turns out, clang and MSVC accept the code with a... | I think this is ill-formed. [dcl.type]/2
As a general rule, at most one defining-type-specifier is allowed in
the complete decl-specifier-seq of a declaration or in a
defining-type-specifier-seq, and at most one type-specifier is allowed
in a type-specifier-seq. The only exceptions to this rule are the
following:
con... |
66,387,387 | 66,388,405 | Int to ASCII char and char to ASCII number | C++ | I must write short script which will change int to ASCII char and char to ASCII int. But i don't know how. I wrote this short code but something is wrong. I'm programming for half-year. Can someone write it working? It is my first time to use functions in c++
#include <iostream>
#include <conio.h>
using namespace std;... | you could also use printf, so you don't need to create other function for converting the number.
int i = 64;
char c = 'a';
printf("number to ascii corresponding to %d is %c\n", i, i);
printf("ascii to number corresponding to %c is %d\n", c, c);
the output is gonna be
number to ascii corresponding to 64 is A
ascii to ... |
66,387,683 | 66,389,677 | How to open cmd when exec jar file (qt QProcess) | I use Windows. I want to use QProcess in a running jar app (java/javaw). After starting that, open the cmd to show me information about working my jar app.
My problem is: when I exec my qt code, the Java app starts (in the background), but cmd doesn't open with the Java runtime.
My code:
QProcess process;
process.setWo... | You can use system() command to run visible command prompt window. Replace you code with a oneliner:
system(QString("java.exe -jar D:\\Programs\\Qt\\Units\\MyJavaProjects\\StackExp\\target\\StackExp-1.0-SNAPSHOT.jar").toStdString().c_str());
If you see just a flashing of the window you can add timeout call after your ... |
66,388,124 | 66,388,194 | clang, gcc, and ignored qualifiers: who is right? | I found a difference in behavior between gcc and clang when compiling BoringSSL, and was able to whittle it down to the following test case to illustrate:
typedef char *OPENSSL_STRING;
#if USE_TYPEDEF
#define constptr const OPENSSL_STRING
#else
#define constptr const char *
#endif
int
foo (const void **ap)
{
const... | Given const OPENSSL_STRING, const is qualified on the typedef OPENSSL_STRING itself, so the type would be char * const, i.e. const pointer to non-const char (note that it's not const char *). Gcc is just trying to tell you that as the cast result the const part is ignored. i.e. (char * const) *ap; has the same effect a... |
66,388,280 | 66,388,525 | Why do empty structs in C++20 do not have implicit spaceship operator? | Motivation: sometimes I use std::variant to implement "fancy" enum where some enum states can carry state.
Now if I want to use the <=> for my variant it requires that my empty structs have defined <=>.
That seems a bit weird to me since if type has 0 bits of state all instances of that type are same.
Full example:
#in... | The defaulted comparison operator is opt-in, not opt-out.
If it was opt-out, then it could turn code that would not compile into code that compiles with some unknown meaning. The standard committee tries to maintain backwards compatibility as much as possible.
|
66,388,288 | 66,388,713 | What is the difference between conversion, casting and coercion? | I have been reviewing this for a long time without finding an answer, so I decide to ask: What is the difference between conversion, casting and coercion?
I'm a bit clumsy with this, I really appreciate the use of a code example.
|
[C++] What is the difference between conversion, casting and coercion?
Conversion is the creation of a value from an expression, potentially changing the type of the resulting value.
A cast is an explicit way to convert a value. Some conversions do not require a cast. Those are called implicit conversions. Example ... |
66,388,664 | 66,389,653 | How to tell if the directory_entry is the end of directory_iterator in C++ | using std::filesystem, how can I tell that the directory_entry is the end of a directory_iterator?
here's an example of what I'm trying to do:
auto it = fs::directory_iterator(path);
for (const auto &i : it) {
if (i == it.back()) { // this works with `vector`s but not with `directory_iterator`
doSomethingWith(i);... | From docs -
If the directory_iterator reports an error or is advanced past the last directory entry, it becomes equal to the default-constructed iterator, also known as the end iterator. Two end iterators are always equal, dereferencing or incrementing the end iterator is undefined behavior.
However, the issue is inc... |
66,388,689 | 66,404,233 | How to read a rotary encoder with interrupts on ESP32 and global flags | When using interrupts, any kind of digitalRead should be obsolete, or so i think. Let me explain my understanding of this to show my problem:
Say, a quadrature incremental rotary encoder (RE) is pulled up on both signal pins and is therefore idle HIGH. If i configure an interrupt service routine (ISR) on the falling ed... | Even if the pin is assigned as interrupt, you can still use digitalRead() to determine the direction. For example:
const uint8_t pinA = 25;
const uint8_t pinB = 26;
volatile int counter;
void IRAM_ATTR isr(){
if(digitalRead(pinA) == digitalRead(pinB)) {
//Clockwise
counter++;
} else {
//Counter Clockwi... |
66,388,731 | 66,388,758 | Why does explicitly calling a destructor cause double freeing? | The code below ends up with free(): double free detected in tcache 2. I want to know the inner process the error happens through.
#include <string>
class test
{
private:
std::string member;
public:
test(const std::string & arg) { member = arg; };
};
int main()
{
test T = test("test test test test");
T... | std::string has an internal buffer for short strings to avoid memory allocations. If the string is short, then there is no memory to free and it works. If the string is long it tries to free the buffer each time you call the destructor.
Here is more information on the Short String Optimization:
Meaning of acronym SSO i... |
66,388,805 | 66,389,795 | Why is std::declval not constexpr? | As in question - why is code like this illegal in cpp?
static_assert(std::declval<std::array<int, 4>>().size() == 4);
Is it an overlook in standard or there is some deeper rationale why std::declval is not constexpr?
| This line:
static_assert(std::declval<std::array<int, 4>>().size() == 4);
fails to compile, because you are using declval in an evaluated context. This is not allowed, and if you do that your program is ill-formed. declval can only be called in unevaluated contexts such as in a decltype or sizeof.
Making a function co... |
66,388,835 | 66,457,742 | Compile Virtual Keyboard for Qt WebAssembly | I'm trying to compile the virtual keyboard project example from QtCreator in WebAssembly.
To compile for wasm library have to be linked statically. According to the docs:
Static builds
The virtual keyboard can be built and linked statically against the
application. This implies that Qt is also built statically (using ... | You can use -s TOTAL_MEMORY=32MB compiler flag to preset a size at emcc link time.
Related question: wasm-ld: error: initial memory too small, 18317952 bytes needed
There is a default limit setting, set to: 16777216
https://github.com/emscripten-core/emscripten/blob/master/src/settings.js#L171
|
66,388,902 | 66,389,167 | Are unpacked struct in packed struct automatically packed? | Are unpacked struct in packed struct automatically packed by GCC?
In other words, do __packed__ attribute automatically propagates to nested structures?
That is to say:
struct unpackedStruct{
int16_t field1;
int32_t field2;
// etc...
}
struct packedStruct{
int16_t field1;
struct unpackedStruct stru... | No, the inner structure is not packed. In this Godbolt example, we can see that struct foo is not packed inside struct bar, which has the packed attribute; the struct bar object created contains three bytes of padding (visible as .zero 3) inside its struct foo member, between the struct foo members c and i.
Current d... |
66,389,007 | 66,389,994 | Are the "defaults" for the type alises in std::iterator_traits always correct? | I've read on cppreference that with C++20, it's possible to omit specifying the type aliases reference, pointer and iterator_category when defining a new iterator.
In this case, the corresponding aliases in std::iterator_traits will have "default" values.
The details of this are a bit confusing to me, so I'm trying to ... | Define "correct". The point of having defaults is to cover the most common cases adequately, while still allowing them to be overridden manually when needed. This implies that, in those cases, the defaults wouldn't be appropriate.
Can you write a type where the defaults are not valid? reference is by default whatever *... |
66,389,150 | 66,390,512 | Using SWIG for std::vector members in C++ structs | I am trying to use SWIG to wrap a C++ struct containing vector members, and provide an interface with Python. I have a small test case using the following three files (Ubuntu-16.04):
A Makefile that looks like this:
FLAGS = -fPIC
PYTHONI = -I /usr/include/python3.5/
PYTHONL = -Xlinker -export-dynamic
all:
swig -W... | Using using in a header file is a bad idea. SwigPyObject type indicates type typemaps weren't matched properly. For example, this works:
test.i:
%module test
%include <std_vector.i>
%template(FloatVector) std::vector<float>;
%naturalvar myStruct::arr1;
%naturalvar myStruct::arr2;
%inline %{
#include <vector>
struct... |
66,389,269 | 66,390,597 | Qt C++ Overload resolution selected deleted operator '=' | So I've just started with c++ as I need to make a game with QT for school. But I still haven't got my head around pointers and so I'm running into a bit of trouble. I think this problem is to do with pointers but it could actually be to do with QT.
I've numerous scenes in this project and so I want to keep track of whi... | You cannot return QObjects by value. In OOP parlance, anything that derives from QObject is-a QObject (just like, say, a Volvo is-a car).
You can return the QGraphicsScene either by reference (preferred) or by a pointer. Since you also intend to set the scene of a room, you have to decide who owns the scene - are you p... |
66,389,457 | 66,389,751 | how can i make some install command run before compile process? | I will use install command in my CMakeLists like this:
install(DIRECTORY lib-mmm/src/infra/ DESTINATION /home/nick/infra FILES_MATCHING PATTERN "*.h")
this is command to install some directory to some place.
I want this run before other compile process.
but i found when i define it as install, it will be called only w... | Afaik there is no way to do this by using the same project. The install target depends on the targets being build and any dependency of building on the install target would result in a circular dependency.
There are alternatives though:
Use file(COPY)
Use execute_process to set up, build & install another cmake projec... |
66,389,908 | 66,416,072 | Download URL File from Direct Download URL? | C++ | So basically i'm trying to Download a File from a URL (NOT FROM A HTML/PHP) from a direct download link, example: https://cdn.discordapp.com/attachments/0/0/file.txt. I want my program to download a certain file from a direct download link in the same directory where the application was ran, i know this is possible in ... | In my opinion, you could use URLDownloadToFile to download files from the url.
I opened the link you gave but the webpage reported an error and did not find any txt. Therefore, you could refer to the following example:
#include <iostream>
#include <urlmon.h>
#pragma comment(lib,"urlmon.lib")
using namespace std;
int ... |
66,390,007 | 66,390,327 | Adding instances of a template class to a vector (C++) | In the code below, I get a compiler error when trying to push fooBaz onto v. This surpises me since Baz is a derived class of Bar.
Why is this not allowed, and what can I do if want to put several Foo instances, templated on classes derived from the same base class, into a vector?
#include <iostream>
#include <vector>
... | As mentioned in a comment, templates are like recipes. You need to instantiate a class template to get a class, before it is just a template. There is no implicit relation between different instantiations (other than being instantiations of the same template). Maybe this gets more clear when you consider following exam... |
66,390,175 | 66,390,303 | How to write destructor for deleting a tree where each node is a dynamically allocated structure containing several arrays? | I have a class that contains a structure called Node and memory for this is dynamically allocated. Using the add function I am creating more Node and connectin them through the next array pointers. I am only saving my head pointer, which points to my first node. I am trying to write a destructor like below. Is it ok?
s... | ~ClassName(){
free(head);
}
This frees the head node. It doesn't also free any of the nodes referred to by head->next[0..29]. So no, it's not OK if you actually allocated those nodes - you will have a memory leak.
Next problem, your next array is uninitialized, so unless it's always all populated (which is obvious... |
66,390,437 | 66,872,057 | Subsetting Eigen vectors and matrices with a vector of indices | I'm trying to port a working Armadillo function to Eigen and am having an issue with RcppEigen vector and matrix subsetting.
Here's my function:
//[[Rcpp::depends(RcppEigen)]]
#include <RcppEigen.h>
using namespace Eigen;
// [[Rcpp::export]]
Eigen::VectorXd fastnnls_eigen(const Eigen::MatrixXd& a, const Eigen::VectorX... | Apparently this is a much-requested feature in Eigen and is coming in 4.0 (yay!)
As Dirk pointed out, there is no way to do this without copying data to a new matrix, but my microbenchmarking suggests the below Eigen functions do so about 20% faster than Armadillo .submat() and .subvec().
Here is the function for subse... |
66,390,503 | 66,461,700 | No module named 'pyexpat' error when embedding Python in C++ | I linked Python 3.8.7 dynamically to a Visual Studio C++ console application TestPython.exe with the following code to try plistlib library (which is necessary in my real application):
#include <iostream>
#include "Python.h"
int main()
{
std::string name;
std::cout << "Write name: ";
std::cin >> name;
... | Solution: place ALL files found in the Python 3.8.7 Windows embeddable package in the same directory (not just the .dll and .zip). In particular, there is file pyexpat.pyd which was missing.
|
66,390,537 | 66,393,462 | Missing braces around initializer - Valid warning? | Let's consider this code:
#include <vector>
#include <array>
int main()
{
std::vector<std::array<int, 3>> arr;
arr.push_back({ 1,2,3}); // WARNING
arr.push_back({{4,5,6}}); // All good
std::array<int, 3> a1 {1,1,1}; // WARNING
std::array<int, 3> a2 {{2,2,2}}; // All g... | Those bug reports are about unhelpfully issuing the warning for the special case {0}, which is valid for initializing any struct type in C and thus sometimes must be used because such a type is left unspecified.
This code is correct as given; the warning is just the usual result of std::array<T,N> having to contain a m... |
66,390,595 | 66,390,772 | Calling Functor in pair in array (C++) | I have defined an array as:
std::array<std::pair<std::shared_ptr<OpCode>, std::shared_ptr<Argument>>, 256> opcodes;
where Opcode and Argument are base classes for functors for interpreting data in Metafont GF files. A typical implementation looks like:
class skip: public OpCode {
public:
using OpCode::OpCode;
... |
Is there a different/better way to manage my data structure so I don't have to explicitly call operator() like the above?
Well, if you don't store pointers, you don't need to dereference them. For example, if your functors are flyweights, you don't need to store owning pointers everywhere, and can just use
array<pa... |
66,390,645 | 66,391,130 | Why are local static variables part of the BSS segment? | The BSS section of the static memory layout is [supposed to be] for "Uninitialized global variables" or "Global variables set to 0".
I was running some tests and suddenly noticed that local static variables are also increasing the size of the BSS segment.
Example :-
Before any static variables
int main (int argc, char ... |
The BSS section of the static memory layout is [supposed to be] for
"Uninitialized global variables" or "Global variables set to 0".
It's unclear where you got that impression, but it is at best misleading. Most people using the term "global variable" in C context mean an object identifier with external linkage, whi... |
66,390,742 | 66,392,261 | Conditional constexpr on non-dependent condition | Suppose I have a configuration function to be defined by the user of the library which may or may not be constexpr.
constexpr int iterations() { return 10; }
// Or maybe:
int iterations() { return std::atoi(std::getenv("ITERATIONS")); }
// I'm okay with requiring the constexpr version to be:
constexpr auto iterations(... | You can silence the compiler diagnostics by ensuring that there is some set of template parameters and function arguments for which a call to your function is a constant expression even if ::iterations() is not a constant expression. For example:
template <bool True = true>
constexpr std::uint32_t algorithm(std::uint32... |
66,390,815 | 66,391,164 | QtConcurrent::mapped return type issues | I want to use QtConcurrent::mapped to process a std::vector of data in parallel. Everything seems to work fine when I use a free function as the MapFunctor argument to QtConcurrent::mapped. However, when I use a lambda or a member pointer, the future returned is a QFuture<void>, not a QFuture of the result type. Below ... | Version with S::func doesn't work because func has wrong signature.
If you have a collection C, mapped function iterates over all elements in this collection calling passed member function for each instance of C.
vector<S> C{S(1),S(2),..};
by
mapped(C,&S::func)
will be performed:
C[0].func();
C[1].func();
..... |
66,391,686 | 66,391,789 | Is there a clean way to turn an overload set into a visitor suitable for use with std::visit? | Suppose I have an overload set, like so:
class C
{
public:
static void f(const A &);
static void f(const B &);
};
I'd like to do something like
std::variant<A, B> v;
// ...
std::visit(C::f, v);
but this doesn't compile. Is there some way of taking an overload set and regarding it as, or converting it t... | Actually, after playing around with this further I've realized that I can do
std::visit([](const auto & t) { C::f(t); }, v);
so I'll leave this here as a potential solution for anyone else with the same problem.
|
66,392,172 | 66,393,552 | Using semantic actions in boost spirit to set fields | Assuming you have a parser using boost spirit that sets this field with the exception of the id field. Is it possible to use semantic actions to generate and set the id field? Or is there a better way to achieve this.
struct employee
{
std::string id;
int age;
std::string surname;
std::string forename;... | Yes it's possible.
One pitfall is that presence of semantic actions usually supresses automatic attribute propagation. Since you'd like to have both, you will want to assign the parser expression using %= instead of = (see docs).
Alternatively you can generate a value on the fly and use the adaptation that you showed.
... |
66,392,256 | 66,392,363 | Using a subclass object as a parameter in a class inheriting from an abstract class | I'm creating two classes. The first is an abstract base class, and the second inherits from the first.
struct Animal
{
bool is_multicellular;
int children;
Animal() {
this->is_multicellular = true;
this->children = 0;
}
virtual Animal& attempt_to_mate(Animal&) = 0;
};
struct Be... | You are using the cast wrong.
Animal& attempt_to_mate(Animal &bear) override {
bear = dynamic_cast<Bear&>(bear);
if (bear.wants_to_mate) {
this->children ++;
}
return bear;
}
bear is reference to an animal. You can assign a reference to a Bear to it, but that wont turn it into a reference to a ... |
66,392,357 | 66,392,420 | C++ iostream encoding? | I have an input.txt and an output.txt, obviously I generate the output.txt, which for now is to write the exact same thing out, but it does not do that because of a possible encoding(?) error.
Here are pictures of the input and output:
My code looks like this:
Menu.cpp:
void Menu::kiir(){
ofstream myfile("output.... | I don't see where you're ingesting, but you seem to be:
reading character input such as the character '2';
converting that to integer input, i.e. the integer 2;
outputting that integer, here producing an ASCII character with value 2.
Possibly the confusion is that std::string::operator+= doesn't do any sort of conver... |
66,392,542 | 66,394,668 | ICC not recognizing stream move semantics | I have the following piece of code that works with -std=c++0x under recent GCC (9.3.1) and clang (7.0.1). It does not work under older GCC (4.8.5), but that's OK. I am now trying to get it to work under ICC (19.0.5.281 20190815).
inline std::istringstream setup_extraction_stream(const std::string buffer, const std::s... | Thanks to @AlanBirtles for pointing me in the right direction. The issue was that ICC does not ship its own version of the standard library, it just uses the headers that GCC ships. This will default to your system GCC (which I already knew did not work). The solution is to use the -cxxlib=/path/to/new/gcc/usr flag ... |
66,392,572 | 66,393,077 | What could possibly go wrong adopting this trivial class to handle optional values? | In certain applications I am stuck with a c++98 compiler.
I like the idea to handle certain errors returning an optional, so I crafted this trivial class to handle them:
template<class T> class Optional
{
public:
Optional<T>() : i_Assigned(false) {}
explicit Optional<T>(const T& v) : i_Value(v), i_Assigned(tru... | One basic issue with your implementation is that it isn't able to accommodate types that lack a default constructor. Similarly, if the default constructor of T has any side effects, those side effects will occur when Optional<T> is constructed. The std::optional<T> is not supposed to have any side effects when default-... |
66,392,932 | 66,393,999 | get packet number in libpcap callback | I'm using libpcap to process the WS output.
My question is: can I have access in the packet number in the pcap_loop callback? Or I will have to use a static variable?
EDIT:
As requested:
long Foo:Main()
{
handle = pcap_open_dead( DLT_EN10MB, MAX_PACKET_SIZE );
if( !handle )
{
}
dumper = pcap_dump_op... | libpcap does not keep track of the ordinal numbers of packets, so you'll have to maintain a packet count in your code.
|
66,392,958 | 66,394,973 | Should I inline operators == and != in case when operator!=() uses negation of operator==() | I am using this simple example to illustrate a problem in which I am trying to optimize stack usage. Let's say I have a struct like this:
// Something.h
struct Something {
int val;
bool operator==(const Something& rhs);
bool operator!=(const Something& rhs);
};
// Something.cpp
bool Something::operator==(const ... | You should use link-time optimization (LTO) so either of them can fully inline into the call-site, especially when it's near-trivial like this.
But if you don't want to use LTO for cross-file inlining, then yes it would be a good idea to put the operator != return !(*this == rhs); definition inside the class definition... |
66,393,205 | 66,393,468 | Parse string and replace | How i could convert this javascript code to c++
key = {"|1|":"A","|2|":"B","|4|":"C","|3|":"D"}
y = "|1||2||3||4|"
for (i in key)
y = y.replace(i,key[i])
console.log(y)
output: ABDC
I got the "decoding key" in a std::string like:
std::string key = "{\"|1|\":\"A\",\"|2|\":\"B\",\"|3|\":\"D\",\"|4|\":\"C\"}";
B... | Equivalents of java dictionnary is map or unordered_map
As for your json question, you need a library to parse json, I recommend the excellent one from Professor Lemire (github lemire)
I just wrote you a simple json parser for you. Note that you will need to compile with c++1z or you will get the warning: decomposition... |
66,393,445 | 66,393,480 | Error: constructor must explicitly initialize reference member | I have the following files:
car.h
#include <iostream>
using namespace std;
namespace CarLibrary {
class Car {
private:
string& _producer;
string& _model;
string& _color;
public:
Car(const string& producer,
const string& model,
const string& color);
... | A reference must be initialized to reference something.
Here you try to assign to the references after they have already been created. That's not legal:
Car::Car(const string& producer,
const string& model,
const string& color)
{
_producer = producer;
_model = model;
_color = color;
}
T... |
66,393,470 | 66,393,710 | Detect if a type is a specialization from the primary template or a user-provided specialization | Let's say I have this:
template<typename T>
class my_template {...};
Now, users are expected to be able to specialize my_template for their own types. And they will pass those types to some API functions of mine, which will use properties of my_template<T> to do stuff.
So at some point in my code, I have a my_template... |
The most obvious solution is to shove a private member alias, or some other concept-detectable private declaration, into the primary my_template definition, and rely on that not being present in user-provided specializations. However, a user could forge an explicit specialization by providing an appropriate definition... |
66,394,505 | 66,394,706 | Pass pointer to function and change it after function returns | This might be trivial but I am having a hard time making it work. It's for a game engine, but the rules apply for C++, I guess.
I have an object, let's call it Car, and then I have a Bike.
From a function in Car, I am passing a pointer to a function in Bike:
void Car::MyFunction(){
int32* MyPointer = nullptr;
... | If I understand correctly, the behavior you are expecting is to give Bike ownership of an object that you can edit from different places. In this case, given the ownership semantics, I recommend using std::shared_ptr<Foo>. If the bike owns this object alone, then you should use a std::unique_ptr<Foo>.
As for your quest... |
66,394,999 | 66,395,115 | Computing rotated rectangle intersection area using C++ | I am trying to calculate the intersection area of two arbitrarily sized and rotated rectangles using C++. I have found some information on non-rotated rectangles but very little on rotated and different sized rectangles. I would like to create a C/C++ program to do this.
Does anyone out there have any information/hints... | I think the easiest way to do this is to clip one rectangle against the other using the Sutherland-Hodgman algorithm: https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm
Then you find the area of the resulting polygon using the shoelace formula: https://en.wikipedia.org/wiki/Shoelace_formula
|
66,395,016 | 66,395,154 | Does RAII support resource ownership transfer? | I mainly used to think about RAII as being about using object lifetime to avoid leaking resources and that served me well enough in practice. But I recently had some discussions about what exactly constitutes an RAII pattern and what does not, which made me search for more definitions and commentaries online, which end... |
Does RAII support resource ownership transfer?
It can, yes.
But then it seems that resource ownership transfer also leads to breaking those very 2 properties that seem to define RAII.
Depends a bit on details of how one defines RAII.
The solution is to extend the definition of RAII shown in the question to allow t... |
66,395,389 | 66,395,433 | C++: How to iterate through a double pointer pointing to an array of pointers | In the following piece of code, I am iterating through a pointer to an array of pointers to TreeNode objects. Below is my code where I iterate through the array:
TreeNode* childListPointer = *currNode->children;
for (TreeNode* currChild = childListPointer; currChild != NULL; currChild = ++childListPointer) {
std:... | Your array is a size and count.
int num_children;
TreeNode **children;
Based off that, you can make a simple range adapter for for(:) loops:
template<class It>
struct range {
It s, f;
It begin() const { return s; }
It end() const { return f; }
range(It b, It e):s(b),f(e) {}
range(It b, std::ptrdiff_t count):... |
66,395,524 | 66,404,060 | difftime is returning a wrong number | #include <iostream>
#include <ctime>
using namespace std;
int main()
{
double seconds;
struct tm birth = {0}; //10-28-1955
birth.tm_year = 55;
birth.tm_mon = 9;
birth.tm_mday = 28;
birth.tm_sec = 0;
struct tm present = {0}; //2-10-2021
present.tm_year = 121;
present.tm_mon = 1... |
When it reaches line 22, b1 becomes -1.
Sorry, but your C standard library is not enough to handle your dates. Use (or write) a different library that will allow to represent time before year 1970.
While at it, you are using C++ - no need to use C functions. Try using chrono library that is part of C++ standard libra... |
66,395,548 | 66,395,651 | Header File: From Namespaces to Classes to Functions | I am struggling a little bit with a project I have and am in need of some serious help. For now, I just want to be led on the right path and will follow up with any more questions I have regarding the project. Also, I am using Visual Studios. :)
Alright, so I am supposed to implement a list class within a namespace lib... | In C, to dynamically allocate memory use malloc and then free the memory after you are done with it.
_data = (double*) malloc(n * sizeof(double));
When and why to use malloc?
How do free and malloc work in C?
You can free the data in the list deconstructor
~list() { free(_data); }
In c++ you also have access to new a... |
66,395,682 | 66,396,098 | What is different between these two ways to store string in C++ | I have a question about C++ string storing.
Wish to know why I got different answers between these two ways.
This is a Leetcode problem #22 Generate Parentheses:
The first one is my final modified answer and finally got the correct answer which accepted on leetcode compiler.
Two ways inputs are same as "2"
And answer m... | This question might be an object lesson on why an open mind is important when debugging. Do not focus too much on what you think the problem is. Be open to being wrong and looking for other explanations.
I desire to know why the first solution parameter in recursion
matchParenthesis(result,thisResult+"(",n,left+1,righ... |
66,396,007 | 66,396,048 | C++ provide only undeducable template types | Assume we have class that depends on two template types one of we specialize in constructor, can we not specialize deducable type?
template <typename T, typename I>
class A {
public:
A(I i) {
}
};
int main() {
A<float, int> a(42); // this works, but we can deduce int from 42
A<float> aa(42); // doesn... | In C++20, you can use alias template deduction like this:
template <typename I>
using A_float = A<float, I>;
int main() {
A_float a(42);
auto aa = A_float(42);
}
Try it on godbolt.org: Demo.
Alternatively, you can define a make function and deduce I from the function parameter. Because of copy elision, this i... |
66,396,120 | 66,396,160 | Why does the filename extension make a difference to compiling? | I compile this code under CentOs8 with the GNU compiler:
#include <stdlib.h>
int main() {
int *a = malloc(3 * sizeof(int));
return 0;
}
When I name it a.cpp, both of the compile commands failed:
g++ -o a a.cpp
gcc -o a a.cpp
But after I rename it to a.c, this compile command succeeds:
gcc -o a a.c
This is C... | C++ is going to error on your implicit cast from the void* returned by malloc() to int*. Whereas C allows implicit casts from void* to other pointer types.
Most compilers will default to looking at the file extension to determine language to compile to.
A man gcc reveals that all .c files default to being compiled as ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.