question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
63,555,135 | 63,555,402 | Can partial template specializations be combined to produce implicitly generated shared code paths? | I was thinking about about template specialization and was wondering if there was a way to use partial specialization to generate two different code paths that are automatically merged.
In this case I have a computational engine where I want an enum to select different functions at compile-time. In this case, depending... | CRTP and multiple inheritance can be your friend. At the core, you can use multiple inheritence to bring functionality in from both classes
template <scheme s, policy p>
struct computational_backend
: scheme_backend<s>
, policy_backend<p>
{ };
This sort of thing will work, as long as the different parts of the comput... |
63,555,303 | 63,555,405 | Confusion on push_back interaction with pair<float,int> | I have no error message instead I only have unexpected behavior.
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
int n = weights.size();
vector<pair<double, int>> valuePerWeight(n);
pair<double,int> x;
for(int i = 0; i < n; i++){
double v = values[i]/weights[i];
x = m... | The confusion here is due to the behavior of the constructor you use
vector<pair<double, int>> valuePerWeight(n);
This actually fills the vector with n default constructed pairs, which as you may surmise, are (0, 0). When you push_back, you push to the end of these, so you a totally get 2n pairs.
.reserve does somethi... |
63,555,415 | 63,556,014 | How do I expand the order when displaying characters? | I need to change the order of the symbol display but without recursion and a second cycle.
the sow code is displayed but I need to get the wos
int test = 119111115; // wos
for (; test > 0; test /= 1000) {
std::cout << (char)(test % 1000);
}
// > sow
do not use a string or anything related to it.
| Picking out thousands groupings from an int to display the ASCII value of is a rather strange task. You have "sow" handled fine. You need to basically do the same thing in reverse for "wos". While there a many, many ways to handle the arithmetic, following on your form of and limiting the algorithm to one-loop and usin... |
63,555,694 | 63,555,909 | Do you need c++ 17 for learning c++ from 2020? | I'm using Window 7 OS, I'm Learning C++ for Competitive Programming. I downloaded a version of CodeBlocks but it does not have C++17 (it only has C++98 and C++0x). Is C++17 really important for Learning C++ [preferably for Competitive Programming] or can I carry with my pre-existing CodeBlocks Version? Also, if C++17 i... | C++17 does not give you access to a new language, it is just an update to an existing language. Most of the competitive programming sites will have c++14 or c++17 running on their servers, so it is preferably good to have one. If you want a pre installed IDE then you can look at the latest version of Visual Studio (pro... |
63,555,723 | 63,555,824 | c++ include header get failed | recently I've started learning c++. When I tried to write my header file, I got include error. Here is my code:
First is the header file(header.h)
#pragma once
void print(int);
and then is its cpp file(header.cpp)
#include "header.h"
#include <iostream>
using namespace std;
void print(int x){
cout << x << endl;
}... | The easiest solution would be to do something like the following
g++ header.cpp main.cpp
This will make sure that the function defined in header.cpp is compiled together with the code that uses it.
|
63,555,899 | 63,555,934 | why 2 times destructor called in this code? | sorry but I cant understand why 2 times destructor called?
#include <iostream>
#include <thread>
class myClass
{
public:
int integer;
void operator()()
{
std::cout << "class: " << integer << "\t" << std::this_thread::get_id() << std::endl;
}
myClass(int h)
: integer{h}
{
}
... | In the line
std::thread one(tempClass);
a copy of tempClass is created. Later on, both instances of myClass are destroyed.
You can pass tempClass by reference by using std::ref, but then you have to guarantee that tempClass remains valid (e.g. does not go out of scope, is brought in an invalid state by the main thread... |
63,555,914 | 63,556,418 | Using curl in C++ to get page that changes after sometime | I was trying to make a webscraper in C++ (I know I could use some other language but I'm just trying to learn). There's a webpage I'm trying to get the html code to but the page changes after a second or two with the links I want. How do I make the program wait until sometime to return the html?
Edit: I want to make a ... | You have three options:
investigate the site and figure out how the javascript code is changing the page, then replicate that in C++ (either by hard-coding a URL or parsing parts of the page),
embed a full browser engine that understands JavaScript and click the link after it changes, or
abandon C++ and use a dedicate... |
63,555,977 | 63,556,769 | Conditionally construct a `boost::optional` member variable on class constructor member initializer list | Suppose I have a non-copyable and non-moveable class Person:
struct Person
{
int m_icNum;
explicit Person(int icNum) : m_icNum(icNum) {}
Person (const Person & other) = delete;
Person (Person && other) = delete;
};
And another class PersonContainer:
struct PersonContainer
{
boost::optional<Person> m_person;... | Inspired by @kabanus' comment, this can be achieved using boost::in_place_init_if:
struct PersonContainer
{
boost::optional<Person> m_person;
explicit PersonContainer(int icNum)
: m_person(boost::in_place_init_if, icNum >= 0, icNum)
{}
};
|
63,556,115 | 63,557,256 | Evaluating sinx using Horner's rule with recursion | Since I have learnt Horner's rule recently. I decided to evaluate sinx using the same with the help of taylor series. I wrote some code, but its showing some great deviation from the original result.
#include<iostream>
using namespace std;
double sin(double x, int n)
{
static double s = x;
if(n==1)
{
... | Based on the comment by @Ted Lyngmo, here is a working version, with minor modifications.
In your original code you can do this:
#include<iostream>
#include <cmath>
using namespace std;
double sin(double x, int n, double s = 1)
{
if(n==1)
{
return s*x;
}
else
{
s = 1 - s*((x*x)/((2... |
63,556,885 | 63,564,638 | Return string from python to C++ | My python code has methods with returning String.
import urllib.request
import ssl
import suds.transport.http
from suds.client import Client
class UnverifiedHttpsTransport(suds.transport.http.HttpTransport):
def __init__(self, *args, **kwargs):
super(UnverifiedHttpsTransport, self).__init__(*args, **kwargs)
d... | The PyObject_GetAttrString returns a PyObject *, handle it properly, here is the code:
pFunc_readtest = PyObject_GetAttrString(pModule, "ReadDataTest");
if (pFunc_readtest && PyCallable_Check(pFunc_readtest)) {
pValue = PyObject_CallObject(pFunc_readtest, NULL);
if(pValue != NULL) {
PyObject * res = PyO... |
63,557,316 | 63,557,379 | Why this object doesn't detect the father class? | I have the following classes:
The Automata Class
#ifndef Automata_H
#define Automata_H
class Automata {
protected:
// ...
public:
virtual DFA* dfaEquivalent() {}
// ....
};
The DFA class that inherits from Automata
#include "Automata.hpp"
#ifndef DFA_H
#define DFA_H
class DFA : public Automata
{
private:
... | You are missing a forward declaration in the base class (i.e. in Automata.h ) header.
The compiler does not know what is the type DFA at the time, it compiles the Automata.h header (i.e. in the virtual function of Automata class)
virtual DFA* dfaEquivalent(){}
// ^^^^--> unknown type
Since it is a pointer to a t... |
63,557,496 | 63,559,277 | CLion support for C++ concepts | Apparently CLion supports concepts now.
However I can't even get the official example to work.
On the std::convertible... CLion shows an error Expected concept name with optional arguments.
When I try to compile it, it tells me to add the -fconcepts flag. When I do that and compile again, I get the error
make: concepts... | I was able to run the cppreference example with CLion 2020.2. The problem why it wasn't working initially for me was that the gcc compiler on my system (Ubuntu 20.04) was too old (9.2). I tried with the packaged g++10, but that still didn't work, so I had to compiler gcc-10.2 directly from the git sources. That finall... |
63,557,696 | 63,558,216 | How to get INT variable to QProcess write command? | Following code works
QProcess *p = new QProcess();
p->write("10 cats\n");
Now I need to send int variable to write command.
Something like:
QProcess *p = new QProcess();
int i = 10;
p->write(i << " cats\n");
| Looks like you want to append variables to then pass them as parameter.
try something like this
int i{10};
QString formattedString{QString("%1 cats\n").arg(i)};
QProcess* p = new QProcess();
p->write(formattedString.toStdString().c_str());
|
63,557,754 | 63,558,190 | int32_t main() vs int main() | I've written a cpp program, and I am able to run it with int32_t main() but not with the signature int main().
Can someone tell me why? Its a .cpp file and not a .c file (as mentioned in some other questions).
| The possible explanation could be that one of your #include files at the top redefines int as something else. This may happen if somebody tried to change the data type in some algorithm by simply redefining int.
Try to put #undef int into a line line immediately before the int main() to restore the default meaning of "... |
63,557,878 | 63,557,991 | Sort Integers in an array by the number of 1 Bits in each integer | Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the sorted array.
Input: arr = [0,1,2,3,4,5,6,7,8]
Output: [0,1... | The simplest (but not most efficient) is to store the numbers and the counts together in a container, sort that, and the extract the numbers:
class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
vector<std::pair<int,int> temp;
for(int i =0; i<arr.size(); i++){
int... |
63,558,068 | 63,558,150 | Passing a lambda argument to a std::function parameter without intermediate variable | This might look similar to "I cannot pass lambda as std::function", but I'm actually passing the std::function parameter by value, so that problem doesn't apply. I've defined the following function.
template<typename T>
std::vector<T> countSort(const std::vector<T> &v, std::function<int(T)> keyFunc, int n);
The second... | The problem is, template argument deduction doesn't consider implicit conversion (from lambda to std::function), which causes the deduction for T on the 2nd function parameter keyFunc to fail.
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload ... |
63,558,615 | 63,559,152 | Passing parent as child to a function c++ | BoxCollider, CillinderCollider and PlaneCollider are all public : Collider, so
Am I doing something wrong or is this simply not possible in c++?
This is the code:
class Collider
{
public:
Collider();
~Collider();
std::string* checkCollision(Collider* _reference);
char* type;
std::string* tag;
pro... | As alternative to traditional inheritance (which seems only used to allow multiple-dispatch), you might use std::variant:
// Your shape structures
struct Box
{
// center, dimension, direction...
};
struct Plan
{
// origin, vector_x, vector_y...
};
struct Cylinder
{
// origin, radius, vector_height...
};
// The real ... |
63,558,941 | 63,563,575 | Calculate p value of a t - statistic using the student_t_distribution | I wanted to calculate p-values of a t-statistic for a two tailed test with 5% level of significance. And I wanted to do this with the standard library. I was wondering if this was possible using the student_t_distribution from the < random > module.
My code currently is as following
#include <iostream>
int main(){
... | The <random> header just provides you with the ability to get random numbers from different distributions.
If you are able to use boost you can do the following:
#include <boost/math/distributions/students_t.hpp>
int main() {
double t_stat = 0.0267; // t-statistic
double alpha_los = 0.05; // level of significa... |
63,559,554 | 63,560,746 | How to remove the multiplier from the libtorch output and display the final result? | When I try to display/print some tensors to the screen, I face something like the following where instead of getting the final result, it seems libtorch displays the tensor with a multiplier (i.e. 0.01* and the likes as you can see below) :
offsets.shape: [1, 4, 46, 85]
probs.shape: [46, 85]
offsets: (1,1,.,.) =
0.01 ... | Basing on libtorch's source code for outputting the tensors, after searching for " *" string within the repository, it turns out that this "pretty-print" is done in aten/src/ATen/core/Formatting.cpp translation unit. The scale and asterisk is prepended here:
static void printScale(std::ostream & stream, double scale) {... |
63,559,981 | 63,560,460 | Getting cURL JSON response C++ | I would like to know how to get a JSON response with cURL. My current code doesn't work, it just returns an empty string. Any help would be greatly appreciated! I've included my current code below.
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
((std::string*)userp)->append((c... | you have an error here :
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
you are passing a temporary copy of std::string here instead of a pointer to the variable you expect to be passed to the callback so the original variable isn't touched ! worse : the callback is passed a dangling pointer which is the casted ... |
63,560,015 | 63,560,206 | Why do I not get guaranteed copy elision with std::tuple? | I would expect that in C++20 the following code prints nothing between prints of A and B (since I expect guaranteed RVO to kick in). But output is:
A
Bye
B
C
Bye
Bye
So presumably one temporary is being created.
#include <iostream>
#include <tuple>
struct INeedElision{
int i;
~INeedElision(){
std::cou... | When constructing std::tuple<int, INeedElision> from {i, {47}}, the selected constructor of std::tuple takes elements by lvalue-reference to const.
tuple( const Types&... args );
Then when use {i, {47}} as the initializer, a temporary INeedElision will be constructed and then passed to the constructor of std::tuple ... |
63,560,303 | 63,560,435 | how do I check how many int digits are inside and reset it to zero? | I need to do the same but the variable gram can be any other number but no more or less than 3 characters.
I also need to immediately reset n if the if condition is met
int gram = 123, n = 0; // gram = 241, gram = 333, gram 512. etc
for (int i = 0; i < 10; i++) {
n = 1000 * n + gram;
if (n == 123123123) // <... | If you know gram is precisely three digits, given your multiply by 1000 and add approach, you can just have an inner loop that runs precisely three times, or a test for i % 3 == 2 to reuse information from the outer loop's loop variable.
If the value isn't fixed, and you need to stop at or above 9 digits, just use the ... |
63,560,386 | 63,560,821 | Defining a scale factor to graph three quantities, the sum of which is constant | I am trying to write a graph in standard output, the program returns rows of "#" that should add up to the initial quantity after another function changes them. I guarantee that the function that modifies the numbers is not at fault. This is my code :
struct mystruct {
long long int s;
long long int i;
long... | You are doing integer divisions in the lines
int scale = round(Ntotal/10) ;
std::string a(Ntotal/scale,'#') ;
std::string b(round(P.s/scale),'#') ;
std::string c(round(P.i/scale),'#') ;
std::string d(round(P.r/scale),'#') ;
and the remainders are truncated, so round() used here aren't working as expected.
You can do ... |
63,560,730 | 63,572,879 | ESP8266 send & recieve data without being in a network | I want two NodeMCU ESP8266s to communicate to each other, but I don't want them in a network. I was thinking about the transmitter could broadcast packets all the time and the reciever could use the promiscuous mode to capture and read the packets. How to do this?
EDIT:
If this is not possible using the ESP8266 is ther... | If you solely want to communicate among ESP8266 devices I suggest you give ESP-NOW a go.
Espressif says
ESP-NOW is yet another protocol developed by Espressif, which enables
multiple devices to communicate with one another without using Wi-Fi.
The protocol is similar to the low-power 2.4GHz wireless connectivity
that ... |
63,560,962 | 63,561,748 | How to get same system time as in Python? | I am using a python program which uses time.time() function in variable as:
currentTime = time.time()
Now I am trying to write same function in C++:
lastCallTime = std::time(nullptr);
Unfortunately, the return value is not the same, sure should not be 100 % the same, but it should more close if I am not wrong.
from p... | Let me just compile a full answer:
One is very very slighty off for some reason I think one counts a second as not 1 second but 0.99999999 ... seconds. Im not sure about a fix but for short term calculations it should be accurate enough (e.g) 14.9999999999999 and 15
For long term calculations a possible fix is using di... |
63,561,834 | 63,561,916 | Is Marshal.PtrToStructure on pointers that point to the native C++ heap sane? | I have an application that marshals data between C# and C++ using PInvoke. The application is a native C++ app that starts the CLR with the C# part internally.
At some point I have to marshal data from C++ to C# and I'm using Marshal.PtrToStructure for this. The C++ part basically looks like this:
struct X {};
auto xP... | Yes that's perfectly reasonable and safe as long as the C/C++ code doesn't free the memory. Note that it isn't always necessary (or desirable) to use Marshal here; depending on what <X> is, you can do this in other ways too, including:
unsafe (cast a void* to a X*)
Unsafe.AsRef<X>(...) (which casts a void* to a ref X)... |
63,561,910 | 63,562,031 | Why can't I see my red triangle on window with OpenGL core profile? | The following code should displays a red triangle on the window with OpenGL compatibility profile, but I can see nothing but a blank window core profile:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
unsigned int shader_create(const char* src_vertex, const char* src_fragment) {
...
}
int main(void)
{
GLFWwindo... | When you use a core profile OpenGL Context, you've to generate and named Vertex Array Object, because the default Vertex Array Object (0) is not valid.
Either switch to a compatibility profile:
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE)... |
63,562,157 | 63,583,216 | VS Code can't step into linked library project | VS Code 1.48, Ubundu 18.04, cmake 3.10, gdb 8.1-ubuntu3.2, gcc 7.5.0.
VSC newb, ubuntu newb, unix experienced, cmake experienced, gdb newb, c++ grizzled vet. I'm mostly a windows guy, though I've dabbled with various flavors of Unix since college back in the early 90s. wheeze
I have two project directories loaded int... | I added the following to my CMakeLists.txt and it seems to be happy. There's probably a better way to do it though.
if (UNIX)
add_definition(-ggdb)
endif()
Down side: Always adds -ggdb to Linux builds, including Release... not just the debug variants. Problems in with non-gdb debuggers.
I'm guessing there's a bet... |
63,562,267 | 63,563,140 | Extracting data from an std::string using regex | Similar to Parse comma-separated ints/int-ranges in C++,
I want a regex to extract edges from a string: (1,2,1) (2,4,5) (1,4,3) (3,4,10) (3,6,2) (3,5,3) (6,7,6) (4,7,4) where (Node1 number, Node2 number, distance).
I currently am using: std::regex reg_edge("\(.*?\,.*?\,.*?\)"); which does not work (as in not a single m... | You can use the regex \((\d+),(\d+),(\d+)\) with std::sregex_iterator. Note that you have to escape ( and ) to match against them literally. ALso, using a raw literal string makes it easier with regexes.
Then extract each matching group using operator[]. Group 0 is always the whole group, so you want groups 1, 2, and 3... |
63,562,291 | 63,562,311 | How do I add numbers in a different order? | This is a simple question don't look for difficulties.
I have such a cycle
int arr[]{ 111, 222, 333 };
for (size_t i = 0; i < 3; i++) {
test = 1000 * test + arr[i];
}
std::cout << test;
it returns the result 111222333
the question is how to make it output the result 333222111
in short add numbers from the ... | You can use
test = 1000 * test + arr[2 - i];
instead of the line.
To handle input other than arrays, you can use "delta" to keep track the place to insert new values.
int delta = 1;
for (size_t i = 0; i < 3; i++) {
test += delta * X;
delta *= 1000;
}
|
63,562,504 | 63,562,594 | Optimize memcpy on Windows (MSVC++) | Let's say I want to copy #SIZE no. of integers from one array to another. I see that the performance of the following 3 are different, even though they accomplish the same job:
memcpy((char*)(arr), (char*)(temp), sizeof(int) * size);
memcpy((int*)(arr), (int*)(temp), size);
memcpy((double*)(arr), (double*)(temp), size/... | memcpy always copies bytes, while you seem to assume that it copies the type you pass (int or double). From cppreference:
Copies count bytes from the object pointed to by src to the object pointed to by dest. Both objects are reinterpreted as arrays of unsigned char.
As your three calls do copy different amount of by... |
63,562,592 | 63,562,737 | Why does MSVC 16.7 treat function overload involving conversion from long to int ambiguous? | I have updated my MSVC to 16.7 and now he complains about the following code:
error C2668: ... ambiguous call to overloaded function
void f(int){
}
void f(double){
}
int main()
{
long l = 5;
static_assert(sizeof(long)==4,"");
f(l);
}
It used to compile in older compilers
https://godbolt.org/z/PG7GT... | First the compiler looks for a function that can be called without implicit conversion. If it finds exactly one it calls it.
If it finds none it looks for a function that can be called with one implicit conversion. In your example both functions need exactly one implicit conversion. That makes the code ambiguous.
The s... |
63,562,607 | 63,563,344 | sample void_t example does not compile with intel compiler 19.0.4 | I'm trying to compile the cppreference example code of void_t with intel compiler :
#include <iostream>
#include <type_traits>
#include <vector>
#include <map>
class A {};
template <typename T, typename = void>
struct is_iterable : std::false_type {};
template <typename T>
struct is_iterable<T, std::void_t<decltype... | The problem is not related to a compiler but to the implementation of the C++ Standard Library it works with. For instance, on Linux systems, Intel icpc typically uses system-installed libstdc++. Note that the support for std::void_t was added into libstdc++ in version 6.1.
While icpc on Godbold uses libstdc++ version ... |
63,562,640 | 63,625,280 | Why are templated functions in a static library crashing when linked to a dynamic library? | On OSX using XCode 11.6 I'm building v8 as a static library (libv8_monolith.a). In one case I'm linking it into an Executable and everything is fine, in another case I'm linking it into a Bundle (dynamic library) and templated functions crash EXC_BAD_ACCESS:
For example AllocatePage():
memory-allocator.h
template <Mem... | It turns out After Effects has its own v8 dynamic library inside it, so when After Effects was loading our dynamic library there was a name clash between some of the functions. My solution for now will be to recompile v8 with changed namespaces to avoid the conflict.
|
63,562,652 | 63,562,669 | Printing size_t using cout gives uncanny output | I am trying to print size_t values using cout. Here is my code
#include <iostream>
using namespace std;
int main() {
size_t blah = 15;
cout << blah +" gibberish";
return 0;
}
The output I get is this: D.
Thanks for the help! :)
*I am trying to use this to print memory usage.
*Also, what exactly is unit of size_t... | blah +" bytes" is adding an integer to a pointer (converted from array of char), so the pointer is moved to invalid place.
You should do
#include <iostream>
using namespace std;
int main() {
size_t blah = 15;
cout << blah << " bytes";
return 0;
}
instead. (use << instead of +: print the number and string one-by-... |
63,562,819 | 63,562,947 | What's wrong with this Linked List implementation? |
Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked li... | Here are what's wrong:
get() doesn't check if the index is invalid.
addAtTail() cannot handle empty list well.
addAtIndex() cannot handle insertion to before 0-th node (head) well.
addAtIndex() cannot handle index greater than the length well.
deleteAtIndex() cannot handle deletion of 0-th node (head) well.
deleteAtIn... |
63,563,301 | 63,563,349 | Incrementing an Iterator with and without creating a template | I'm writing a very simple line of code to display the contents of a map container and I came across an interesting error.
If I write:
void DisplayMap(const map<int, string>& myMap)
{
for (const map<int, string>::const_iterator myIterator = myMap.begin();
myIterator != myMap.end(); ++myIterator)
{... | Most of the iterator and template stuff is not that relevant here. What is relevant is the const:
for (const map<int, string>::const_iterator myIterator = myMap.begin();
myIterator != myMap.end(); ++myIterator)
^^ !!!
You cannot increment a const iterator because it is const. You would ge... |
63,563,347 | 63,563,588 | Is there a dangling pointer problem in this code? | string str;
char *a=str.c_str();
This code is working fine for me but every place else I see this code instead
string str;
char *a=new char[str.length()];
strcpy(a,str.c_str());
I wonder which one is correct and why?
| The two code segments do different things.
The first assigns the pointer value of str to your new c-tpye string, and implicitly converts from const char*(c_str() return type) to char*, which is wrong. If you were to change your new string you would face an error. Even if c_str() returned char*, altering the new string ... |
63,563,452 | 63,563,935 | What optimizations / settings should I use for compiling in release mode in Xcode for MacOS? | I have an app I am working on that will be used in MacOS with Adobe products.
The SDK only comes with a debug release mode for the projects. If I try to edit the scheme and look under 'run', I cannot switch it to release as there is no other option either than debug. From what I've read, this means I either have to cre... | To create a new scheme:
Get the screen looking like the following screenshot:
Click on '+' under where it says AppStore. This creates a duplicate of an existing scheme with a new name.
Edit the newly created configuration with the desired compiler settings etc.
The newly created configuration should then show u... |
63,563,550 | 63,564,190 | Correct way to convert rvalue reference to temporary parameter to const lvalue return in C++ | I'm trying to implemenet find-like method to extract reference to value from container and return a default value if the value is not found or of an incompatible type.
template<class T> const T& get (key_type k, const T& def)
{
const T* r = dynamic_cast<const T*> (find(k)); // suppose `find` returns a pointer to co... | No, you can't. The temporary object is alive only for that statement and will be destroyed before you access it through the returned reference.
const sometype &val = get(not_existing_key, get_temporary_object());
do_something_with(val);
When you do_something_with(val), the object to which the reference val is bound is... |
63,564,634 | 63,564,803 | Time calculation in the main game loop | There is the code in the Quake 2 main game loop implementation:
if (!initialized)
{ // let base retain 16 bits of effectively random data
base = timeGetTime() & 0xffff0000;
initialized = true;
}
curtime = timeGetTime() - base;
I'm wondering about the line base = timeGetTime() & 0xffff0000. Why are they apply... | The if (!initialized) check will only pass once. Therefore curtime will become larger with each gameloop, which wouldn't be the case with suggested rewrite, since the upper word may increase after sufficiently many gameloops.
Likely this is in preparation of an int-to-float conversion where smaller numbers result in hi... |
63,564,652 | 63,564,716 | Is there any technology to "cache" the result of a branch choice? | In my code there's a regular: if a if statement is true, it will keep true for a while, and if it changes to false, it will keep false for a while. Since the performance in this code matters, I want to make the branch predict more efficient.
Currently what I tried is to write two versions of this if statement, one is o... | If it stays the same for a while, the branch predictor will figure that out pretty quickly. That's why sorting an input sometimes makes code run significantly faster; the random unsorted data keeps changing the test result back and forth with no pattern the branch predictor can use, but with sorted data, it has long ru... |
63,564,841 | 63,566,086 | shared pointers in main function, factory | Is there a better way of writing this code in a more experienced/c++17 way.
int main(int argc, char* argv[])
{
//I recieve a std::string str as input here
manager mgr;
auto baseptr = ( (str == "doA") ? std::make_shared<myclass>(mgr):
std::make_shared<otherclass>(mg... | You can't use the conditional operator (<cond> ? <true result> : <false result>) like that since the true result and false result must be of compatible types.
Since you only have two classes, you could just do this:
(All manager declarations below may need to be const depending on the usage.)
#include <memory>
#include... |
63,565,063 | 63,565,756 | Derive template arguments from other argument but keep intelli sense | Let's assume I have the following classes:
template<typename A> class Foo { ... };
template<typename A, typename B = Foo<A>> class Bar { ... };
Bar is virtual, and it can be derived with many different arguments for A and B. The template's purpose is to provide intelli-sense for the derivations. I do not want to use i... | Simpler would be to add alias in Foo/Bar:
template<typename A> class Foo { using type = A; };
template<typename A, typename B = Foo<A>> class Bar { using T1 = A; using T2 = B; };
class Derived : Bar<int, Foo<float>> { /*...*/ };
template <typename BarType>
class Algorithm
{
using A = typename BarType::T1;
usi... |
63,565,071 | 63,565,168 | Do reference to dereferenced NULL pointer produce UB on creation or on access in C++ | I'm trying to implement code like this
if (auto *ptr = get_obj_ptr(), &obj = *ptr; ptr)
{
// access obj here
}
else
// handle error without accessing ptr and obj
assuming that get_obj_ptr() could return either valid pointer to valid object or NULL. Is this code legal in C++? Accessing to obj if prt == NULL is ... |
Is this code legal in C++?
No , it is not legal.
just defining NULL-dereferenced reference also result into UB?
Yes.
Maybe there is any other elegant and UB-. exception-, and boost-free solution?
An elegant solution: Bind the reference after checking for nullness:
if (auto *ptr = get_obj_ptr())
{
auto& obj = ... |
63,565,126 | 63,565,930 | Pass a parameter to an unordered_map (or set) hash struct | I have the following struct:
array<int, 2> map_size;
struct Node{
int id;
array<int, 2> pos;
vector<Node*> nbs;
bool in_open;
bool in_closed;
};
Every Node has a position (pos) that is in range of map_size (global variable).
And I'm using the following unordered map
struct PosHash{
public:
... | Here's a complete program showing how to construct a PosHash object storing a specific value. Note that you don't need a custom comparison - std::arrays are compared the same way anyway.
#include <iostream>
#include <array>
#include <unordered_map>
using Pos = std::array<int, 2>;
struct PosHash {
PosHash(int m) ... |
63,565,283 | 63,565,789 | Somehow 'using' a list of types (in C++17 and up) | How is is possible to make the following simple idea work?
template <typename ...Types>
void Function()
{ /* do something that depends on the Types */ }
void Test()
{
using my_types = { int, float }; // not possible
using my_types = int, float; // alternative disallowed syntax
Function<my_types>... | A possible alternative is define a sort of type wrapper (as std::tuple but that do absolutely nothing with template arguments)
template <typename...>
struct type_wrapper
{ };
and declare Function() receiving an object of that type
template <typename ...Types>
void Function (type_wrapper<Types...> const &)
{ /* do som... |
63,565,540 | 63,565,857 | runtime error: reference binding to null pointer of type 'int' (stl_iterator.h) | Can someone help me to solve this error?
I met a problem when I did an exercise on LeetCode.
The question is finding a number in a [n*m] 2D array.
In an n * m two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please comple... | The error occurs when a matrix with 0 columns is entered. Then in the line
if(target<*(*row).begin()) return false;
*row is empty, thus, (*row).begin() returns the past-the-end-iterator and dereferencing it causes undefined behaviour (a crash in your case).
You need to catch this case. Because every row has the same n... |
63,565,855 | 63,567,414 | Pure virtual function issue | I have a base class in which I have a pure virtual function and with this function, I want to override it in other derived classes (in some of those with a different number of parameters if possible).
So in the MergeSort subclass, I have MSort method which will need a different number of parameters as it is done recurs... | As stated in the comments, you have to use the same signature for all your overrides. In doing so, you could use the following approach:
use overridden function as a sort of entrypoint, inside which you call a real function (maybe private) that performs sorting. An example to illustrate the approach:
class SortingAlgo
... |
63,565,866 | 63,565,971 | C++ && operator not evaluating the conditions | I have this piece of code which ensures that the user inputs a N-digit Number(With no leading zeroes). I am new to C++ but I feel the approach is correct. Please correct if anything is amiss.
#include <iostream>
#include <string>
#include <cmath>
std::string get_input(int n) {
std::string guess;
do
{
... | Your logic is incorrect. You need to keep asking for input when the input string is either not the appropriate length OR there are some leading zeros in the input string.
So your condition should be:
do {
// ...
} while ((guess.length() != n) || (std::stoi(guess) / std::pow(10,n) == 0))
Also, instead of using std::p... |
63,566,176 | 63,566,577 | Why the scope resolution operator (::) does not allow virtual function mechanism? which may lead to infinite recursion otherwise | I was reading about Virtual Functions from the book "The C++ Programming Langauge" by Bjarne Stroustrup, and encountered the following code snippet:-
class A {
//...
protected:
int someOtherField;
//...
public:
virtual void print() const;
//...
};
class B : public A {
//...
public:
... | If qualified call A::print() did not disable virtual dispatch, the usage like presented in B::print() would be infinite recursion and it would be pretty much impossible to call function from base class.
See the imaginary code execution if qualified call did not disable virtual dispatch:
You have A* a = new B;
a->print... |
63,566,186 | 63,566,224 | How do I store addresses in a map in C++? | I'm trying to find the intersection point between two linked lists. I already know how to solve the problem by calculating the absolute difference in length of the two lists and displacing one of the pointers.
I want to know if it is possible to solve the question by storing addresses of each of the nodes along with a... | map<SinglyLinkedListNode *, int> m1;
will do the trick. For each pointer to a SinglyLinkedListNode, you keep a number, the number of visits.
You can do even better with:
map<const SinglyLinkedListNode *, int> m1;
If you don't need to iterate over the pointers in order, another option is:
unordered_map<const SinglyLin... |
63,566,242 | 63,566,960 | BFS implementation C++ | I was trying to implement BFS using Vertex classes and BFS class, since I wanted to learn implementation of classes along with algorithms.
vertex.h
#ifndef vertex_H_
#define vertex_H_
#include<vector>
class Vertex{
private:
int _data;
bool _visited;
std::vector<Vertex> _neighbours;
... | It's happening because you're copying nodes and vectors all over the place. The particular problem here is that you create v1 and v2, then attach v1 to v2 by pushing v2 onto v1._neighbors. This is a copy of v2, not the original! THEN you set the neighbors for v2, but you are setting neighbors NOT for the v2 in v1._n... |
63,566,297 | 63,566,562 | nlohmann and copying maps | Anyone has idea how to quickly copy nlohmann::json MAP values to an other nlohmann::json?
nlohmann::json j1;
nlohmann::json j2;
j1["MAP"]["value1"] = 1;
j2["MAP"]["value2"] = 2;
j2["MAP"] += j1["MAP"];
This will throw because += will think that I am adding a value to a list.
[json.exception.type_error.308] cannot us... | The json::update() method is the built-in version of this operation.
j2["MAP"].update(j1["MAP"]);
|
63,566,797 | 63,566,818 | CPP vector concatenation in recursive function | I have this recursive function, which does not compile giving errors at vector concatenation lines.
vector<int> binaryInsert(vector<int> subArray, int subArraySize, int nextVal) {
if(subArraySize == 1)
{
if(nextVal >= subArray[0]) subArray.insert(subArray.begin()+1, nextVal);
else subArray.i... | Calling std::vector::insert returns an iterator, not the modified vector. So the return statement will try to convert an iterator to a vector, giving the compiler error that you see.
You can solve this by simply breaking up the return statement into 2 lines:
newVec.insert(newVec.end(), rightSubArray.begin(), rightSubAr... |
63,567,205 | 63,567,206 | Objective-C++ Resize Instance Vector Not Working | I have an iOS OpenCV wrapper in Objective-C++ that looks like this:
// CVImage.mm
@interface CVImage()
@property std::vector<std::vector<cv::Point>> contours;
@end
@implementation CVImage
...
- (void) findContours
{
// Find and store contours with cv::findContours
}
// Resize method
- (void) resizeTo:(NSInteger)... | Okay I figured it out. I guess I was initializing it poorly. You have to make sure that contours is a pointer (i.e. std::vector<std::vector<cv::Point>> *).
Update all the references to match and it works as it should.
|
63,567,495 | 63,567,781 | Overloading operator + in c++ to add two arrays | Task is to overload the operator + so that it adds two arrays. Array is a class with two private members int* data, and int m(capacity of array).
void Array::setM(int m){
this->m = m;
this->data = new int[this->m];
}
int& Array::operator[](int i){
return this->data[i];
}
Array& Array::operator+(Array& a){
Array res;... | Let's consider your operator implementation step by step.
For starters the right hand operand is not changed within the operator. So the function should be declared at least like
Array& operator+( const Array& a );
The function crates a new object of the type Array within its body.
Array res;
So as the object is a lo... |
63,567,813 | 63,579,139 | How to get the parent node of the current node while iterating over YAML::Node? | I am building a tree structure while iterating over a YAML::Node. So far, i am able to build the tree when the hierarchy goes downwards. But if there is change in heirarchy i am not able to get the parent node.
batman:
type: super hero
entity: ""
natural: yes
attributes:
powers:
whip:
x: ""
... | You can't because in general, a YAML node does not have a single parent.
The content of a YAML file constitutes a directed graph, not a tree. For example, this YAML:
- &a 123
- foo: *a
Defines a sequence of two items, the scalar node 123 and a mapping node containing a single key-value pair. That pair has the scalar f... |
63,567,934 | 63,568,011 | How does caller know which member functions of same name shall be called | I see the below code today.
I know the difference between returning a reference and returning a const reference.
But I don't know when T& operator()* will be called, and when const T& operator()const* will be called.
They have the same name.
template<typename T>
class CSmartPtr
{
public:
CSmartPtr(T *ptr = nullptr)... |
But I don't know when T& operator()* will be called, and when const T& operator()const* will be called.
They have the same name.
In this case, if the member function is called on a const object, the const method will be invoked, and the non-const method will be invoked for a non-const object.
How does caller know wh... |
63,568,237 | 63,568,304 | Using characters as indices in arrays | #include<iostream>
using namespace std;
int main()
{
int arr[128];
arr['a'] = 101;
cout<<arr['a'];
return 0;
}
So i was experimenting around and found that characters can be used as indices in arrays instead of conventional whole numbers.
This program gives the correct output i.e 101 which is correct.... | 'a' is a char type with an implementation defined numeric value (depends on the character encoding used on your platform: in ASCII, it's 97).
That numeric char is used in the evaluation of arr['a']. If you're fortunate, that will give you an element of the arr. If the value is outside the bounds of arr then the behavio... |
63,568,277 | 63,568,386 | Does Polymorphic Slicing occur when Derived Object declares no New Members | Does slicing occur in polymorphism, if you store a derived class by value, but the derived class has no extra members?
For example, if I have a class Base. But I want a custom constructor, so I implement Custom, like so:
class Base{
public:
int a;
int b;
Base(int a)
: a(a)
{ b = 2; }
};
class ... |
Does slicing occur in polymorphism, if you store a derived class by value, but the derived class has no extra members?
Yes.
It's quite another matter that you don't see any significant loses in your posted code. The metrics you are using to compare the objects indicate as though nothing got lost because of object sli... |
63,568,605 | 63,580,206 | C++ Template instancing with mutual reference | Is there a way to allow two or more templates instanciations to mutually refer to each other ?
Example :
/* invalid C++ */
/* we suppose MyTemplate1 and MyTemplate2 are declared */
typedef MyTemplate1<MyInstance2> MyInstance1;
typedef MyTemplate2<MyInstance1> MyInstance2;
I suppose there is none, still asking just in... | Here's a solution that at least gives the correct output. If it's also a viable solution for your use case is not very clear though but maybe it can at least help you clarify your question a bit more.
#include <iostream>
template <template <typename> typename TemplateT> struct TemplateType {
template <typename typ... |
63,568,716 | 63,586,612 | How to configure the widget Entry so that the length of the frame so as not to exceed 11 characters | I am on Ubuntu 20.04. I need to configure the frame of GTK::Entry widget to not exceed 11 characters. I thought I could use this code set_max_width_chars
Gtk::Entry nomUsb;
nomUsb.set_can_focus(true);
nomUsb.set_max_length(11);
nomUsb.set_max_width_chars(11);
boiteBoutonsH1.pack_start(nomUsb, Gtk::PACK_SHRINK);
but th... | Here is some code that will, I suspect, do what you want:
#include <gtkmm.h>
class MainWindow : public Gtk::Window
{
public:
MainWindow()
{
// Can't type in more than 11 chars (copy/paste will truncate):
m_11CharMax.set_max_length(11);
// Sets the width of the entry to about 11 chara... |
63,568,827 | 63,568,967 | C++ read keyboard events | I am new to C++ and I am trying to make a program that reads keystrokes. This is a function I made that looks for a certain key.
void printKey(short vk)
{
if ((GetAsyncKeyState(vk) >> 15) & 1)
{
LPWSTR key;
GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key));
w... | In addition to the comments above, GetKeynameText needs a buffer for the key name, so instead of:
LPWSTR key;
GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key));
you want something like:
WCHAR key [128];
GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key) / sizeof (W... |
63,568,953 | 63,576,603 | Why is my render-pass not transitioning into final layout | I am currently trying to incorporate imgui into my vulkan-application.
So i have two render-passes, one for my 3d-scene, and one for imgui.
In my 3d-renderpass i set initialLayout to undefined and finalLayout to attachmentOptimal.
In the imgui-renderpass i set initialLayout to attachmentOptimal and finalLayout to prese... | Turns out I was doing something extremely stupid in a part of the code not immediately connected to any of the render-passes.
I basically asked for the ui-related VkCommandBuffer of the current frame before retrieving the index for the new frame. This meant that I re-recorded, and re-submitted a VkCommandBuffer which h... |
63,569,322 | 63,571,244 | How to get output from a long-running child process in C++ | From a C++ program, I am wanting to:
Launch a child process.
Wait until it emits a line of output.
Capture that line of output, and allow the child process to continue running.
This feels like it should be trivial, but I've tried it now two ways, and have hit a similar roadblock each time. First I used boost::process... | Turns out both implementations were working fine— the issue was that the Python script wasn't flushing stdout. I thought I was in the clear here because I was emitting a \n and it seemed to be fine when invoked from the terminal, but clearly not.
Thanks for the pointer on this, @paul-sanders.
|
63,569,885 | 63,570,039 | Why is const template parameter not a universal/forwarding reference | I'm reading about universal references/forwarding references and this link says that:
Here param is a universal reference:
template<typename T>
void f(T&& param);
But here param is not a universal reference, it is an rvalue reference:
template<typename T>
void f(const T&& param);
The definition for universal refer... | Foreword: The official term is forwarding reference.
So why is the second case not a universal reference?
Because it is a reference to const. And references to const are not forwarding references.
why?
The whole point of a forwarding reference is that when an rvalue is given as an argument, the parameter will be de... |
63,570,032 | 63,570,060 | Difference in the usage of function prototype with / without pointers | I'm following simple C++ tutorial.
#include <iostream>
using namespace std;
int main()
{
int a = 1, b = 2;
cout << "Before swapping " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(a,b);
cout << endl;
cout << "After swapping " << endl;
cout << "a = " << a << endl;
cout << ... | The issue with the first program is you're not actually calling your own swap function. At the top of the file, you have:
using namespace std;
which brings std::swap into scope and that's the function that you're actually calling. If you put a cout statement in your own swap you'll see that it's never actually called.... |
63,570,314 | 63,570,379 | C++ unknown escape sequences on regex + groups captured by half | I'm trying to use the following regex
(https?|rtsp):\/\/(?:([^\s@\/]+?)[@])?([^\s\/:]+)(?:[:]([0-9]+))?(?:(\/[^\s?#]+)([?][^\s#]+)?)?([#]\S*)?
on C++ like this:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string str("rtsp://3333:1232@hellowebsite.com:2222");
std::regex r("(https?|... | Especially when you're doing regexes, raw string literals are your friend. So, as a starting point, I'd do something like this:
std::regex r(R"--((https?|rtsp):\/\/(?:([^\s@\/]+?)[@])?([^\s\/:]+)(?:[:]([0-9]+))?(?:(\/[^\s?#]+)([?][^\s#]+)?)?([#]\S*)?)--");
If you really don't want to use raw string literals, the start... |
63,570,627 | 63,570,829 | String literal wont have end for regex expression | I'm trying to use this Regex
^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$
to parse IPV4 addresses
I tried to put it inside a raw string literal:
std::regex ipv4(R"^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$");
but I'm getting error:
main.cpp:14:4: error: expected ';' at end of declaration
}
... | No, if you look at the reference for string literals, you'll see that the minimal raw string literal needs to be R"()".
You can have additional delimiters between the " and the (, which must match the delimiters between ) and ". e.g. R"~~(hello world)~~" contains the string literal "hello world".
|
63,570,634 | 63,572,077 | Qt UDP can't read data | I try to write a simple Multicast UDP receiver.
I can receive data when the Internet is not available, but not when it is available.
In Wireshark, Data is received in either state.
m_pUdpSockRecv = new QUdpSocket(this);
m_pUdpSockRecv->bind( QHostAddress("192.168.0.254") ,usPort, QUdpSocket::ShareAddress );
m_pUdpSockR... | Sorry, I solved.
m_pUdpSockRecv = new QUdpSocket(this);
connect(m_pUdpSockRecv, SIGNAL(readyRead()), this, SLOT( fnUdpRecvData() ));
m_pUdpSockRecv->bind( QHostAddress("192.168.0.254") ,usPort, QUdpSocket::ShareAddress );
m_pUdpSockRecv->joinMulticastGroup( QHostAddress("239.0.0.20") );
This code is connected.
It pro... |
63,570,856 | 63,571,203 | C++ getting the key pressed | I am making a program and I want it to be able to read key presses. It does that just fine but I am running into some trouble when I am trying to get the name of the key that was pressed. The code just stops in the middle of the program and for what part is ran it does not give the expected output. Here is my code.
... | Read the documentation. MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) is not valid input for GetKeyNameTextW(), as you are mapping a virtual key code to a character, but GetKeyNameTextW() expects a hardware scan code instead (amongst other flags), such as from the LPARAM of a WM_KEY(DOWN|UP) message.
You are also not ensuring t... |
63,571,618 | 63,571,715 | C++ : How to safely deallocate a heap-allocated array of vectors? | I am currently working with code that at the moment requires me to make an array of vectors (I am new to C++ - if this is an absolutely terrible idea, I would greatly appreciate the feedback).
Let's say I allocate memory on the heap for my vectors like so:
#include <iostream>
#include <vector>
#include <random>
int ma... |
f this is an absolutely terrible idea, I would greatly appreciate the feedback).
Yes, this is a terribly bad idea. To be specific, owning bare pointers are a bad idea. Instead of manually allocating a dynamic array, it is usually better to use a container such as std::vector.
How to safely deallocate a heap-allocate... |
63,571,642 | 63,574,399 | How to access regex search result inside std::sub_match? | std::smatch ipv4Match;
std::regex_match(ipv4, ipv4Match, ip);
if (ipv4Match.empty())
{
return std::nullopt;
}
else
{
if (!ipv4Match.empty())
{
uint8_t a, b, c, d;
a = (uint8_t)(ipv4Match[0]);
b = (uint8_t)(ipv4Match[1]);
c = (uint8_t)(ipv4Match[2]);
d = (uint8_t)(ipv... | Your issue is unrelated to regex, but string to int conversion.
You might use std::atoi/std::stoi:
uint8_t a = std::stoi(ipv4Match[1].str());
uint8_t b = std::stoi(ipv4Match[2].str());
uint8_t c = std::stoi(ipv4Match[3].str());
uint8_t d = std::stoi(ipv4Match[4].str());
|
63,571,773 | 63,571,836 | Returning an object pointer from a recursive function met with access violation | I've created a simple recursive function that performs preorder traversal to return a node that matches a target string.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
string value;
Node *left, *right;
Node(string value) {
this->value = value;
this->left = NULL;
... | preorder doesn't return anything in yhe recursive cases. The behaviour of the program is unrefined.
Hint for future: Use compiler warnings.
|
63,571,976 | 63,573,641 | Why can I create an object when there is no explicitly defined constructor? | I have two pieces of code:
Piece 1:
class Test{
public:
Test(int a) {};
};
Piece 2:
class Test{
public:
Test() {};
};
When i want to create an array of some size with the Test object i have a problem. With the first piece of code i can't create the array as Test arr[some number], instea... | From logical point of view, which permeates C++ language rules:
Constructors of class describes ways one object of class-type can be created.
If any user-defined constructor was provided, compiler would not generate default constructor. If no constructors defined, compiler would generate copy, move and default const... |
63,572,120 | 63,572,227 | Segmentation fault in linked list code in C++ | So, i'm trying to implement this code on C++ which inserts an element at a specific position in a linked list and I keep getting a segmentation fault. I've narrowed it down to it being the l.push(a) statement in the main function but can't rectify it.
n - number of nodes.
then the linked list is inserted.
data - the da... | You have made couple of mistakes here.
1.In your Push API you are not checking for Null.
void push(int data) {
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
if (head == NULL)
head = temp;
else {
Node* curr = head;
while (curr->ne... |
63,572,515 | 63,572,573 | (C++) Why can't I rely on an extration operator to act as an iterator? | #include <iostream>
#include <fstream>
int main()
{
std::ifstream file("input.txt");
char currentChar;
int charCount = 0;
while (file >> currentChar)
{
charCount++;
if (currentChar == 'a')
{
std::cout << charCount;
}
}
in the above, the charCount t... | It's not "massively large". You're simply outputting the current count every time you encounter the letter a, and because you don't include any whitespace or newlines, then every number will be joined together and appear like a huge number.
Try this:
std::cout << charCount << std::endl;
And consider doing this just o... |
63,572,850 | 63,618,591 | integrate python with C++ | I want to integrate python code with C++, in which c++ source code call a function/class in python. I specifically need to pass array from c++ code to python code and get another array from python in c++ source code. To illustarte,
the main.cc
// call_function.c - A sample of calling
// python functions from C code
//... | I decided to use pybind11 to integrate python and c++. A simple and good reference for learning working with the library, you can use this tutorial
|
63,573,079 | 63,610,175 | What leads to "Could not find QtWebEngineProcess" error? | I am triyng to port WebKit (Qt5.5.1) plugin to WebEngine (Qt5.11.3) one as described here: https://doc.qt.io/qt-5/qtwebenginewidgets-qtwebkitportingguide.html
Building and running in Ubuntu 18.04 I get following errors:
QXcbIntegration: Cannot create platform OpenGL context, neither GLX nor EGL are enabled
and then
Co... | Problem was in missed dependency files.
Our cmake build copied only auto-determined dependencies (libs) from the Qt folder to the app folder. But for a full deploy a QtWebEngine app needs few non-libs dependencies such as QtWebEngineProcess executable xcbglintegrations plugins (first error) and WebEngine resources. Thi... |
63,573,287 | 63,573,563 | Convert std::string to PyObject in C++ in Python3 | I am trying to convert std::string to PyObject.
std::string st = jsp.updateRoot(people, people);
PyObject* pValue = PyBytes_AsString(st);
It is not working using the above method.
How can I convert?
| From doc.:
char* PyBytes_AsString(PyObject *o)
Return a pointer to the contents of o. The pointer refers to the internal buffer of o, which consists of len(o) + 1 bytes. The last byte in the buffer is always null, regardless of whether there are any other null bytes. The data must not be modified in any way, unless th... |
63,573,317 | 63,573,860 | Cannot find function implementation in the code | In OpenVDB C++ repository, there is this condition inside VolumeToMesh.h:
if (ijk[0] > origin[0] && ijk[1] > origin[1] && ijk[2] > origin[2]) {
constructPolygons(invertSurfaceOrientation,
flags, refFlags, offsets, ijk, *signleafPt, *idxLeafPt, mesher); // 1st function: implementation not found
} else {
... | As pointed out by @molbdnilo it is a template not a single function and all the input parameters passed to the template satisfy interfaces/traits needed by template.
|
63,573,343 | 63,574,688 | Error in assignment operator overloading in C++ | class Array
{
private:
int *ptr;
int size;
public:
Array& operator = (const Array& rhs);
};
Array& Array::operator = (const Array& rhs)
{
ptr = new int [rhs.size];
size = rhs.size;
for( int i = 0; i < size; i++ )
ptr[i] = rhs.ptr[i];
return *this;
}
int main()
{
... | Before we can talk about the operator=, we need to realise that the class is fundamentally broken: it has no working constructor, and it is violating the rule of three, and is therefore not managing its resources properly.
After these two points have been fixed, (but really only after that!), we can turn to the impleme... |
63,573,424 | 63,574,547 | error: (-215:Assertion failed) m.dims <= 2 in function 'FormattedImpl' in cv::dnn | I am loading a pre-trained TensorFlow model in the opencv dnn module using the following code -
cv::dnn::Net net = cv::dnn::readNetFromTensorflow("frozen_inference_graph.pb",
"graph.pbtxt");
net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA); //Run model on GPU
net.s... | This error occurs because you are trying to print a cv::Mat to standard output that has more than 2 dimensions. With cv::dnn, the output after using net.forward() is 4-dimensional. However I have no idea what model you are using because the output structure of the blob is different depending on what task you are tryi... |
63,573,591 | 63,583,936 | Max Sum Subarray with Partition constraint using Dynamic Programming | Problem statement: Given a set of n coins of some denominations (maybe repeating, in random order), and a number k. A game is being played by a single player in the following manner: Player can choose to pick 0 to k coins contiguously but will have to leave one next coin from picking. In this manner give the highest su... | It looks like the idea is converting the problem - You must choose at least one coin in no more than x+1 coins in a row, and make it minimal. Then the original problem's answer would just be [sum of all values] - [answer of the new problem].
Then we're ready to talk about dynamic programming. Let's define a recurrence ... |
63,573,839 | 63,574,443 | Issue with custom C++ QuickSort | I am implementing the Quicksort algowithm myself in C++. But I have problems: the result isn't sorted!
Here are my files:
Main file: quicksort.cpp:
#include <iostream>
#include <ctime>
#include "quicksort.h"
#include "utils.h"
using namespace std;
int main() {
int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
... | First, the line exch(a, lo, hi); should be exch(a, lo, j);. It appears to solve your problem:
https://godbolt.org/z/ehh31G
Second - if you're learning c++, use c++ features. That is, use the standard library.
Use std::array<T, N> indtead of T[N]. Use iterators instead of ints for lo, hi, i, j. exch can be replaced with... |
63,573,894 | 63,591,542 | Visual Studio doesn't recognize std library | I'm writing an MFC application on Visual Studio 2015 in C++. I added some code which uses members of std library and suppose to take an int and create from it a hex char* with the prefix "0x". I tried to build the project on VS 2015 and VS 2017 from two different computers and I get the same errors - VS doesn't recogni... | I've included the headers in the wrong order. In every C++ project in Visual Studio it includes "stdafx.h" library automatically. This library contains many of the commonly used libraries such as <string> and etc. The solution was to write the includes in the following way:
#include "stdafx.h"
// other headers of the f... |
63,574,212 | 63,596,955 | boost Serialisation on a variant containing boost::blank | I have a boost::variant wherein one of the fields has the boost::blank field, using boost::serialise on the same throws an error saying error: no member named 'serialize' in 'boost::blank'.
Is there a way to avoid this by adding a separate function for boost::blank somewhere?
| Yeah, just use non-member serialization, a.k.a. non-intrusive serialization:
namespace boost { namespace serialization {
template <typename Ar> void serialize(Ar&, boost::blank&, unsigned) {}
} }
You could also add the overload in namespace boost as ADL will find it there
Live Demo
Live On Coliru
#include <boost/a... |
63,574,214 | 63,574,271 | Get length of a instance of string class using recursion in C++ | I am writing a recursive function to find the length of a string in C++. It's a simple problem and I wrote two functions in C++ and one in Python.
First
int length(char *str) {
if (*str == '\0')
return 0;
return 1 + length(str + 1);
}
Second
int get_size(string str, int i) {
if (str[i] == '\0')
... | The C++-equivalent to pythons string[1:] is std::string::substr:
int get_size(std::string str) {
if (str.empty()) // end of recursion
return 0;
// call recursively with substr from second to last character.
return 1 + get_size(str.substr(1));
}
|
63,574,438 | 63,574,614 | How to implement Javascript-like dynamic typing in C++ | I have to write a very basic JSON serializer/deserializer in C++. The goal is to build something similar to this https://github.com/nlohmann/json. Unfortunately I can't use this awesome library because my compiler does not fully support the C++ 11 standard. Switching the compiler is not an option.
I would like to go wi... | In your case, you don't actually need fully dynamic typing, as JSONValue can't have any type, just some amount of different types. This is what you would use a union for:
union JSONValue {
long long integer;
double floating;
std::string string;
...
}
Unions of non-trivially destructible types are howev... |
63,574,542 | 63,574,714 | Two-parameter template ambiguous binary operator overload | So I have a matrix class (of type Derived) based on CRTP that takes two template parameters template<class T, class Derived>, and need to overload the binary operators +, - and * for a matrix multiplied by a scalar (of class T). For the * operator it will for instance be
template <class T, class Derived>
Derived operat... | The compiler can't possibly discern two overloads, that take arbitrary types for both parameters. In
template <class T, class Derived>
Derived operator*(const Derived &other, const T scalar) {...}
Derived and T are just template parameters that could be replaced by any type. The same goes for the other operator. Both... |
63,574,640 | 63,575,457 | Generate windows executable from Linux source code? | I want to make Bison.exe from Bison source code to run it on windows. On Linux we can use make to generate the Bison executable but I want to use Bison on windows.
I am unable to find win-Bison for any of the latest releases, most of them are for 2.x release. Because of a CVE I need to use 3.5.4 or higher version.
| You can use MSYS2 to use bison on Windows. Here is the package link. Version 3.6.4-1 is available there.
A quick search took me to this video. You can refer to that if you don't have experience setting up MSYS2 on Windows.
I noticed that you are using Chocolatey. So you can install MSYS2 using that also. Here is the pa... |
63,574,645 | 63,574,797 | How to use QList with std::generate? | I ran a test to compare QVector and QList insertions/sorting performance with this code:
#include <algorithm>
#include <iostream>
#include <boost/timer/timer.hpp>
#include <QVector>
#include <QList>
int main()
{
constexpr auto size = 10000000ul;
srand(time(nullptr));
std::cout << std::endl;
std::cout <<... | The problem is that reserve only allocates memory, but it doesn't set the size.
You can reserve any amount, but the size will still be zero.
There's no QList function to actually set the size.
However you might be able to use e.g. the std::back_inserter iterator adapter function to append elements to the list. Combine ... |
63,574,973 | 63,575,157 | Infinite loop when trying to read an int greater than INT_MAX | I was writing some C++ code, to figure out the internal representation of integers. But I stumbled upon a weird bug, and I can't seem to reason about the cause of this issue.
The code is quite simple. it asks for a user input (I, LI, or SI).
LI and SI gives the representation of largest and smallest integers respective... | The problem isn't the integer representation. It's that the conversion of the input fails, which means it will still be left in the input buffer, leading to your infinite loop reading the exact same data over and over again.
You need to check if the input succeeded or not, and if it failed you need to clear the buffer ... |
63,575,094 | 63,575,434 | How do I find the size of tokenizer<char_separator<char>> | I have the following code:
#include <boost/tokenizer.hpp>
using namespace boost;
Vibranium::MySQLConnectionInfo::MySQLConnectionInfo(Config& config, const std::string &connectionDetails) {
char_separator<char> sep{";"};
tokenizer<char_separator<char>> tokens(connectionDetails,sep);
}
How do I find how many e... | It doesn't have a size because it doesn't contain tokens – it tokenizes as you iterate over it, "delivering" tokens into an iterator.
You can copy the tokens into something, and then check what you got.
std::vector<std::string> actual_tokens(tokens.begin(), tokens.end());
If you're only interested in how many tokens t... |
63,575,562 | 63,576,176 | Right values as function argument, correct usage? | Trying to use rightvalues a bit more but I got confused, how should I design my function in which I want to use the right value:
// Pass by whatever-it's-called
void RockyBalboa::DoSomething(std::string&& str){
m_fighters.push_back(str);
}
// Pass by reference
void RockyBalboa::DoSomething(std::string& str){
... | You've swapped the usage. It's the Rvalue reference that can be moved. The Lvalue reference should be made const:
// Rvalue reference
void RockyBalboa::DoSomething(std::string&& str){
m_fighters.push_back(std::move(str));
}
// Lvalue reference
void RockyBalboa::DoSomething(const std::string& str){ // note: const
... |
63,575,667 | 63,575,929 | Can you find error in this code for Palindrome Partitioning problem https://leetcode.com/problems/palindrome-partitioning/ | Can you please help find the error. I am pushing temp which is vector<vector> type in dp[i], it is showing error. Can you help pointing out the error.
Line 54: Char 14: error: no matching member function for call to 'push_back'
dp[i].push_back(vv);
~~~~~~^~~~~~~~~
^
1 error generated.
class Solutio... | Not sure if this is all your compiler gave you, but here's the full error message I got:
main.cpp: In member function 'std::vector<std::vector<std::__cxx11::basic_string<char> > > Solution::partition(std::string)':
main.cpp:53:31: error: no matching function for call to 'std::vector<std::vector<std::__cxx11::basic_stri... |
63,575,865 | 63,599,323 | Issue change tab QTabWidget & QScrollArea Qt | I'm trying to create a QScrollArea in a QTabWidget.
Versions :
Qt 5.15.0
Qt creator 4.12.4
MSVC2019 64 bits
First of all, I've created the QTabWidget :
tabWidget = new QTabWidget(this);
tabWidget->setGeometry(10, 15, 1200, 665);
tabWidget->setStyleSheet("font-size : 15px");
tab1Content = new QWidget(tabWidget); tabW... | try this code
#include "widget.h"
#include<QTabWidget>
#include<QLabel>
#include<QVBoxLayout>
#include<QScrollArea>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
QTabWidget *tabWidget = new QTabWidget(this);
tabWidget->setGeometry(10, 15, 1200, 665);
tabWidget->setStyleSheet("font-size : 15px");... |
63,576,136 | 63,613,598 | Why do std::ranges algorithms lack parallel overloads (taking an execution policy parameter)? | Many functions in the C++ Algorithms library have overloads taking a parameter of type ExecutionPolicy, e.g. std::copy. However, I noticed that the corresponding functions in the std::ranges namespace do not have these parallel overloads. This is unfortunate because it means that for many cases the non-ranged variants ... | Concluding from Eric Niebler's (and other authors') numerous answers (during talks and on his github comments), they (the committee and the authors) simply ran out of time. The proposal was already large (notice the fact that it heavily referenced the <concepts> proposals) and adding even more to it would spawn a risk ... |
63,576,341 | 63,576,751 | Constructor to initialize base part of derived class by object of another derived class | Let's say I have a base class and 2 derived classes:
class Base {
public:
Base() : m_base(0) { }
private:
int m_base;
};
class Derived1 : public Base {
public:
Derived1() : Base(), m_d1(1) { }
private:
int m_d1;
};
class Derived2 : public Base {
public:
Derived2(): Base()... |
Pointer to Derived1 + dynamic_cast + base class copy-constructor within initializer list
There is no need for pointers, no need for dynamic casting, and no need to limit the argument to only Derived1.
Reference to Base and cast Derived1 when calling
This is fine, except the cast is redundant. An object is impli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.