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,741,215 | 63,741,383 | How can I give alternative names to functions? | Let's say I have a function called get_color:
std::string get_color()
{
return "green";
}
I also want to have the same function but with the en-gb spelling, which is get_colour. I could just make an identical function and call the get_color function like this:
std::string get_colour()
{
return get_color()
}
b... | auto get_colour(get_color);
is one way. Needs a little more thought if you want to support overloaded functions.
|
63,741,263 | 63,746,697 | Top level declarator error but the program runs correctly | I have a project with multiple files including main.cpp and two headers. Both headers have an error at the line with class name declaration. Building any of the files or project as a whole gives no errors or warnings. The program itself runs correctly.
I'm using CodeLite IDE and GCC compiler.
What can be a reason for s... | Your IDE thinks that the header files are written in C (where class is not a keyword and so Creature is a declarator), because you gave them the conventional extension .h used to indicate that. Don't do that: use .hh, .hpp, or .hxx for C++ header files so that tools (and humans) know what you're writing without having... |
63,741,277 | 63,744,261 | More than one operator overload in Rust | I know it is possible by using traits to implement operator overloading in Rust. In C++ is also possible to have multiple operator overloading for the same operator and the same struct, and switch on/off which operator to use.
Is it possible to do the same as the following C++ code in Rust? Possibly in the same source ... | The idiomatic answer in Rust to:
How do I use different overloads of +, <, ... for my Type?
is to wrap the type up and implement the operator on the wrapper.
Example on the playground
#[derive(Clone, Copy, Debug)]
struct S(i32);
#[derive(Debug)]
struct Adder(pub S);
impl std::ops::Add<S> for Adder {
type Output... |
63,741,820 | 63,741,856 | C++ incrementing a globally declared counter | say I had a counter declared globally that incremented in another function
#include <iostream>
using namespace std;
int count = 0;
string passorFail(int x, int y)
{
if (x > y)
{
return "pass";
count++;
}
else
{
return "fail";
}
}
int main()
{
int x = 10;
int ... | In this snippet:
return "pass";
count++;
you are returning from the function before incrementing count. Your compiler should warn that count++; is unreachable code.
You need:
count++;
return "pass";
Also, please don't use using namespace std;. e.g. if <iostream> brings in the name count (which it's allowed to do), th... |
63,742,112 | 63,743,699 | C++: How to implement polymorphic object creator to populate a table | I have a table widget object that can be resized with set_num_col(int) and set_num_row(int).
A call to each of these functions will call a resize_table() function to populate the widget with table_cells objects.
However, I have two polymorphic types of cells: table_cell_default and table_cell_custom, derived from the s... | Here's an example of using a factory lambda to produce the initial cells in the Table's constructor. Refer to main function where the lambda is located, and the Table constructor for how it is used.
I do not know what your code looks like, so I just wrap each cell into an object_t and put that into the Table.
#include... |
63,742,682 | 63,742,805 | What operations can make floats leave a [0, 1] range? | I frequently work with float or double types which are in a range of [0, 1]. I am aware that floating point operations are imprecise, so I typically clamp my values so that they are guaranteed to be in this range before/after operations.
In some cases I rely on floats being not even slightly negative and being exactly ... | Restricting this answer to IEEE754 if I may.
0, 1, and 2 can all be represented exactly as a float. The arithmetic operators are required to return the best floating point value possible. Since x and y are neither greater than 1, their sum cannot be greater than 2 since then otherwise there would exist a better float f... |
63,743,062 | 63,771,865 | How can I create separate cv::Mat headers for the channels of an image? | I am using OpenCV 4.1.1. and have the following goal
Given a Mat of size (m, n, 2) of float32, create separate Mat headers for each individual channel, so that it can be written to, without copying the image data
What I am trying to do is this:
const int mat_sz[]{shape_.height, shape_.width, 2};
Mat cost(3, mat_s... | Turns out this is not possible, because the documentation for the cv::Mat constructor taking in number dimension, their sizes and preallocated data states that
steps: Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed ... |
63,743,137 | 63,743,197 | How to overload the [] operator to support both assignment and const parameters in other functions? | Consider a class SomeClass:
class SomeClass{
public:
// Constructors, other members
float& operator[](const unsigned i);
friend bool operator==(const SomeClass &A, const SomeClass &B);
};
Suppose this is how the == operator is overloaded for this class (not the actual implementation, but an... | Overload operator [] to provide both:
float& operator [](unsigned int i);
float operator [](unsigned int i) const;
For a generic T that’s not cheap to copy, use a T const& return value. The general pattern for implementing read/write operator [] is
T& operator [](index_type i);
T const& operator [](index_type i) const... |
63,743,149 | 63,745,127 | How to check whether a the program has created a file in the past | So, I have created a program that creates a separate file for every individual student to store his data. I have set a bool variable to restrict accessing data without entring it but it only allows me to get data if I stored it first while I run the program but I restart the program multiple times which means it won't ... | Yes, there is a way to check if file exists. You will have to know it's name first, though. I guess that since you have some files already created, then you have your data stored in some sort of array / other structure and based on that you can guess the name of the file.
Anyways, here's the code:
#include <fstream>
..... |
63,743,368 | 63,746,886 | Issues trying to make a filter using Qt | I'm trying to make my software filter a list of elements.
I think I need to put my data in a TableWidget because I have to display other information.
I also put 3 Line Edit to search respectively in each category (called leName, leSource, leDestination)
so I tried to implement my filter for the name property, for now I... | The fact that a cell exists does not imply that it has an associated QTableWidgetItem, so you must verify that it is not null.
QTableWidgetItem * item = ui->tableWidget->item(0, 1);
if(item && item->text().contains(arg1))
{
qDebug() << "If validated";
ui->tableWidget->showRow(i);
}else{
qDebug() << "If not ... |
63,743,687 | 63,744,167 | Why is std::remove_reference used in std::move? | I tried implementing std::move, which uses std::remove_reference, however it seems to work without it. Please give me an exemple in which my implementation fails, where std::remove_reference is necessary.
template <class type> type && move(type & source) { return (type &&) source; }
template <class type> type && move(t... |
I tried implementing std::move, which uses std::remove_reference, however it seems to work without it.
Yes, it is working because you explicitly provided the overload for lvalue reference. While std::remove_reference is only relevant if you are using forwarding references.
If you take out this line:
Godbolt
template ... |
63,745,017 | 63,875,011 | How to access & use string defined in shared library | I'm trying to bake a version string into a shared library, but can't figure out how to access the string in a client program of the library.
The method I'd like to work is: have the version string in a text file version.txt, turn that into an object file using objcopy, link that into a .so and link the client program a... | So, I found how to do it "my way" but still think Lorinczy's approach is better.
I ultimately gave up trying to read the size of the string and came up with this code that works pretty well:
#define DATASTRING(NAME) \
[]() -> std::string { ... |
63,745,569 | 63,751,821 | webview 2 icon not displayed in Visual Studio toolbox | For some reason, and after trying all the solutions that i found on the internet, the Webview 2 tool isn't showing in the Toolbox.
I have installed and upgraded Visual Studio, Microsoft Edge and Microsoft Edge Canary, but nothing seem to help.
i am using Visual Studio 2019 version 16.7.2
Webview 2 9.538 (Pre-release, a... | i would like to share with you the solution:
i have added the component manually:
inside toolbox menu -> right click anywhere -> choose items -> browse -> project name -> packages - > webView 2 folder -> lib -> net462 -> Microsoft.Web.WebView2.WinForms.dll
disclaimer:
I have tried this solution with other (newer) webVi... |
63,745,829 | 63,746,201 | What are the requirements to make a lambda constexpr? | Several times, in code review, I'm told to add contexpr to some named lambda closure declaration, i.e. I'm told to change this
auto lam = [capture list](args){body}
to this:
constexpr auto lam = [capture list](args){body}
Therefore, I'd like to understand what the conditions are that allow a lambda closure to be declar... | The only thing that decides whether a lambda can be constexpr is the capture list. The body can be non-constexpr and a constexpr lambda can still have parameters like std::string, which are not literal types either.
its type must be a LiteralType.
The LiteralType requirement for lambdas effectively means that all cap... |
63,746,597 | 63,746,681 | Why output change when i change cout position after decrementing my function? | Here is my code :
#include<iostream>
int x;
void gad(int x)
{
if(x==0)
return;
else{
std::cout<<"geek"<<" ";
std::cout<<"for geeks ";
gad(x-1);
}
}
int main()
{
gad(3);
return 0;
}
The output is this
geek for geeks geek for geeks geek for geeks
Now if the change the position of 2nd std::cout... | You're printing the first sentence, then going into a recursive call to the same function which will, in return, print the first sentence and go to another recursive call...etc.
After the last function returns, it will continue with x=1 to print the second sentence...etc.
To visualize what happens, this will be the cal... |
63,746,847 | 63,747,230 | How to do type conversion on an "implicit" rvalue in the return statement | Is this invalid? gcc accepts it, clang and msvc don't.
#include <memory>
class Holder {
std::unique_ptr<int> data;
public:
operator std::unique_ptr<int>() && { return std::move(data); }
};
std::unique_ptr<int> test()
{
Holder val;
return val;
}
Assuming that I don't want to add something like std::un... | The "implicit" rvalue conversion is standard mandated. But depending on which standard version you are using, which compiler is "correct" varies.
In C++17
[class.copy.elision] (emphasis mine)
3 In the following copy-initialization contexts, a move operation
might be used instead of a copy operation:
If the expression... |
63,746,862 | 63,747,859 | Iterating over a column of a multidimensional array with std::count_if()? | I have a multidimensional array of type double (double someArray[10][20]). I'd like to:
a) use std::count_if() to iterate over a single column of that array, returning the number of values greater than some number
b) also require that the row index of that number is within a certain range.
I know the basics of using st... | Divide and conquer.
Use count_if to iterate over a single column of a multidimensional array, checking that the index of the row is within a certain range.
Break the problem into smaller pieces, until they are small enough to solve.
Use count_if
iterate over a single column of a multidimensional array
checking that ... |
63,747,200 | 63,747,228 | Printing gibberish after printing all characters c++ | I have the following code:
# include <iostream>
using std::cout;
const int ARRAY_SIZE = 15;
union one4all
{
int int_value;
long long_value;
double double_value;
char char_value[ARRAY_SIZE];
};
int main()
{
one4all x;
for (int i = 0; i < ARRAY_SIZE; ++i)
{
x.char_value[i] = (int)... |
Why did it keep printing after the 15th character? I know that it could not detect any terminating character, but hey! it knew the size of the character array?
"it" might if you mean the compiler generally, but you called a streaming function operator<<(std::ostream&, const char*) - which is only matched because the ... |
63,747,267 | 63,747,422 | Future and Promise mechanism usage | I'm trying to understand the Fututre-Promise mechanism in C++. Here is the code:
#include "FuturePromise.h"
void func(std::promise<int>* p) {
int a = 10, b = 5;
int result = a + b;
std::cout << "From inside the Thread...." << std::endl; p->set_value(result);
}
void func2(std::promise<char*>* p) {
... | As mentioned in the comments, you are storing a pointer to a local variable in your promise, and that goes away when func2 ends.
A simple fix (as so often with char * pointers) is to use std::promise <std::string> instead:
void func2(std::promise<std::string> *p) {
const char *str = "Abc";
std::cout << "From in... |
63,747,291 | 63,747,360 | Reading a wav file returns 0 bytes | So I'm reading from .wav file but it returns 0 bytes.
FILE *pFile = fopen("file.wav", "r");
if (pFile == nullptr)
{
cout << "Unable to open wave file";
return 1;
}
long lSize = ftell (pFile);
char *p = new char[lSize];
size_t bytesRead = fread(p, 1, lSize, pFile); // 0 bytes... | You need to seek to the end before getting the file position, then rewind:
FILE *pFile = fopen("file.wav", "rb");
if (pFile == nullptr)
{
cout << "Unable to open wave file";
return 1;
}
fseek(pFile, 0, SEEK_END); // <----- ADD THIS -------<
long lSize = ftell (pFile);
rewind(pFile); // <----- AND THIS ------... |
63,747,889 | 63,748,428 | I was trying to find a binary tree with given in-order and pre-order I am following a Recursive approach, but I am getting a Wrong Output | I am following a Recursive approach to solve the problem. There is no syntax error in the code
/**************** **We are given Inorder and Preorder . We have to find the Binary Tree.** ***************/
#include <iostream>
using namespace std;
#include <queue>
template<typename T>
/* Class Defination */
class BinaryT... | At the very least the second line should be root->right = ...:
root->left = buildTreeHelper(in, pre, lInS, lInE, lPreS, lPreE);
root->left = buildTreeHelper(in, pre, rInS, rInE, rPreS, rPreE);
|
63,748,118 | 63,748,461 | simple rust generic/template add function | So I am just learning rust - I have setup the tools and got it all structurally working, cross compiling, linking libraries and so on... but now I am exploring the language after a few simple functions I now want to write some templates (I have a c++ background). So in c++ talk I want to do this:
C++
template<typename ... | First of all, you better refer to the documentation of std::ops::Add first. There's a type Output which you've set, but there's also a template parameter Rhs that you can set too. So you may try:
pub fn add_to_rhs<A, B>(a: A, b: B) -> B
where A: std::ops::Add<B, Output = B>
{
return a + b;
}
There you declare th... |
63,748,206 | 63,748,306 | Class template method specialization | I'm trying to specialize a template method like this:
template <typename X, typename Y>
class A {
public:
void run(){};
};
template<typename Y>
void A<int, Y>::run() {}
But I get
main.cpp:70:17: error: nested name specifier 'A<int, Y>::' for declaration does not refer into a class, class template or class templa... | You need at first partially specialize the class itself including the function declaration. After that you can write its definition. You may not partially specialize a function.
For example
#include <iostream>
template <typename X, typename Y>
class A {
public:
void run()
{
std::cout << "How do you do?... |
63,748,847 | 63,748,944 | Checking equality/inequality of multiple variables | Let's say we have four variables: int a, b, c, d;. I need to check if excatly two of them are equal.
So for example: 1 1 9 5 is true, but 3 9 8 4 and 3 3 3 1 are false.
Of course writing an if statement for this would take a lot of time, won't be easily readable and it would be easy to make a mistake writing it.
What i... | There are several ways to do this.
One involves explicitly checking all the conditions. Since you have 4 variables, you only 6 conditions to check. These can easily be counted.
int n = (a == b) + (a == c) + (a == d) + (b == c) + (b == d) + (c == d);
Then check if n is 1. This works because a boolean value will be conv... |
63,749,077 | 63,749,661 | C++/CMake can't find libxml++ | I'm a Java/Go/Python dev trying to get my feet wet with the C++ toolchain and having a hard time forcing CMake to find dependencies. I installed libxml++ on Debian using apt-get install libxml++2.6-dev and it installed it to /usr/include/libxml++2.6/libxml++. This is a problem, because that's not the right path relativ... | You may should add this line to your CMakeLists.txt :
include_directories("/usr/include/libxml++2.6/")
( or use any macro to achieve to this result )
then in your main :
#include <iostream>
#include <libxml++/libxml++.h> // <= like this
int main() {
std::cout << "hello" << std::endl;
}
Another way to do :
If it... |
63,749,080 | 63,753,143 | winapi: get callback when thread ends | I have some c++ library code that creates some book-keeping data per thread that accesses it (based on thread-id). I would like to cleanup that data when a thread ends. Is there a way (if not portable, then using win-api) to get notified when a thread ends?
// simplified example:
std::mutex mutex_;
std::unordered_map<s... | Thread-local storage is both C++ standard way and platform way.
C++ has thread_local keyword to declare thread-local variable. Then destructor of that variable is called for each thread for which it was constructed. Thread local variable is constructed for at least all threads that access the variable, and possibly for... |
63,749,314 | 63,749,341 | Run-Time Check Failure #4 - Stack area around _alloca memory reserved by this function is corrupted? | #include <iostream>
#include <malloc.h>
void print_vals(int n)
{
int *arr = (int *)alloca(n);
for (int i = 0; i < n; i++)
arr[i] = i;
for (int i = 0; i < n; i++)
std::cout << arr[i] << ' ';
std::cout << '\n';
}
int main()
{
print_vals(5);
print_vals(10);
}
When I run this c... | I'm going to assume this is just sample code since, if your intent is just to print the numbers 0..n, there's absolutely no reason why you would use an array for this :-)
On to your actual problem, the alloca function, like malloc, allocates a number of bytes. If you then treat it as if you have a number of int values... |
63,749,522 | 63,749,545 | C++ how to reset a counter to 0 when a function is called? | I have a question regarding the reset of a counter back to 0. Below is my function
std::string passorFail(double performanceScore, int threshHold)
{
if (performanceScore > threshHold)
{
pass++; //if the judge socres a pass, 1 is added to the counter
return "pass";
}
else
{
return "fail";
}... | You don't show the code that prints the count, but what you want is a separate variable that keeps track of the value of pass the last time it was printed. So you want something like this:
printf("count of first pass: %d\n", pass - lastpass);
lastpass = pass;
|
63,749,909 | 63,750,286 | Declaring a using declaration before using it in other using declarations | Is it possible to declare a using declaration before using it?
I would like to do something like:
using V = std::vector< V >;
or like:
using X, Y; // declaring X and Y
using Node = std::variant< X, Y >;
using X = std::unordered_vector< Node >;
using Y = std::vector< Node >;
Is it possible?
EDIT: The comments are foc... | The approach with using doesn't work because this simply introduces a new name for an existing type. using V = std::vector<V>;, if it were even allowed, would lead to infinite recursion in the compiler when it tries to determine what type V even is.
One approach that could work would be to inherit std::vector<V> from ... |
63,750,121 | 63,750,693 | Is it possible to get both the modulus and quotient of division in a single operation in C++? | I hear that when the processor does / or %, it will perform the same operation but one way it returns the quotient, the other way the remainder.
Is it possible to get both in a single operation? Maybe if I throw in a snippet of assembly code (which I've never done)?
| Yes, the compiler will do it for you. Just use a divide followed by a remainder with the same operands.
https://godbolt.org/z/oK4f4s
void div(int n, int d, int *q, int *r)
{
*q = n / d;
*r = n % d;
}
div(int, int, int*, int*):
mov eax, edi
mov r8, rdx
cdq
idiv esi
... |
63,750,404 | 63,750,451 | If a class contains object of another class can it be initialized by having default value in the constructor of containing class in C++? | Compiling this code produces the error
error time constructor time::time(int,int,char) cannot be overloaded with time::time(int,int,char)
I'm trying to reduce overloaded constructors so I am trying to give default values in the constructor parameters. Is the line entry(int sno=5,time t{1,2,'p'}); in the constructor f... | Yes it's possible, this is just about syntax :
#include<iostream>
using namespace std;
class Time
{
int _hours;
int _mins;
char _ap;
public:
Time(int hours=0,int mins=0,char ap='n'): _hours(hours),_mins(mins),_ap(ap)
{};
void showtime()
{
cout<<"\nTime : "<< _hours << " "... |
63,750,761 | 63,815,656 | Unable to connect to ssh server using system() function in C++ | I'm trying to connect to my school's ssh server using a simple C++ program that I wrote. My windows computer has OpenSSH Client installed and I'm able to establish a connection using the command prompt.
Here's how it works via the command prompt:
C:\Users\Username>ssh username@example.server.name
Password:
Last login: ... | Thanks to everyone who commented and helped on this question. Turned out it was an issue of the platform I was building my program for. The platform was initially set to x86 but once I changed it to x64, everything worked as intended.
|
63,751,519 | 63,751,610 | using-declaration may not name namespace | If I have a file like this, everything works as expected:
#include <filesystem>
#include <iostream>
int main() {
std::filesystem::path o = "C:\\Windows\\write.exe";
auto s = o.parent_path();
std::cout << s << std::endl;
}
However I would like to use a line like this if possible:
filesystem::path o = "C:\\Wind... | You can use a namespace alias like
namespace filesystem = std::filesystem;
Here is a demonstrative program
#include <iostream>
namespace A
{
namespace B
{
int x;
}
}
int main()
{
namespace B = A::B;
B::x = 10;
std::cout << B::x << '\n';
return 0;
}
Its output is
1... |
63,752,643 | 63,752,674 | decltype of pointer to class accessing its () operator | I have following class
template<class T> class CT
{
T& operator()(int i,int j) const noexcept
{ return indx[i*N+j]; }
private:
T *indx;
int N;
};
Now some where in my application I have something as the following
CT<double> arr, (...);
(...)
decltype(arr) *alias;
if(usearr)alias = &arr;
(...)
alias(0,0) ... | decltype(arr) yields the type of arr, i.e. CT<double>, then decltype(arr) * yields the type CT<double> *, which is a pointer to CT<double> and you can't call operator() on it directly.
You can dereference it then call operator() like (*alias)(0,0).
|
63,752,833 | 63,754,055 | Is there something wrong with my "stoi" function or my compiler? | I tried writing a function to convert a string of numbers to an integer. I get a wrong output when I run my code on VS code with g++ 9.2.0 but when I run it on repl.it, I get a right output. This is my code:
#include <iostream>
#include <cmath>
using namespace std;
int charToInt(char c)
{
return c - '0';
}
int my... | The usual approach to this problem is to accumulate the result by multiplying by 10:
for (int i = 0; i < len; ++i) {
r *= 10;
r += s[i] - '0';
}
|
63,752,855 | 63,753,136 | How to use std::iota with std::pair? | Suppose I have to use this template which I cannot modify:
// cannot modify
template <typename C,typename T>
void foo(C& c,const T& t) {
// ...
std::iota(std::begin(c),std::end(c),t);
// ...
}
It fails when c is a container of std::pairs:
#include <vector>
#include <utility>
#include <numeric>
int main()
... | Please, note that std::iota() has separate types for the iterator and the value to increment/assign:
template< class ForwardIt, class T >
void iota( ForwardIt first, ForwardIt last, T value );
This can be utilized to use a type for value which is different from (though assignable to) the element type of vector.
In m... |
63,753,067 | 63,753,121 | erase() space in string | This is the code that I've written to remove spaces in the given string. It normally works.
string a = "hello there world";
int n = a.size();
for(int i =0 ;i<n;++i){
if(a[i] == ' '){
a.erase(a.begin()+i);
}
}
cout<<a;
But for the given input above ( note that there are two spac... | No but your problem is that you loop forwards and ignore the fact that the string that you are looping over changes while you loop.
After you erased a space, the rest of the string shifts one position backwards, but you consider the current character as already checked, even though you just changed it.
So you essential... |
63,753,086 | 63,758,165 | coverage for enable_if template class functions in C++ | I'm trying to generate accurate code coverage for my templated math classes. I'm default instantiating every method inside a template class with a trick from here
template class Vector2D<float>;
so that the coverage is not always 100% but shows me, where functions were never called. The problem is that if i go further... | I ended up explicitly instantiating the template member function (see this post)
template void Vector2D<float>::rotate<float>(float);
The coverage report then shows the function as never called (orange/red) if i indeed do not call it explicitly in code.
|
63,753,129 | 63,753,633 | Time Complexity of input a data | There is any cost of taking 2d array as input ?
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cin >> a[i][j];
}
}
Is it O(n^2) time complexity or O(1)?
| Time Complexity depends on how you define it. In competitive programming, there is a chance that you might be given a readymade 2D matrix and you have to find out a particular answer.
Now, what approach you take while finding out the answer defines your time complexity. But in this case, taking input is not taken into ... |
63,753,225 | 63,753,284 | Can we access protected member functions of base class in derived class? | As i have studied that Derived class can access protected member of base class. In derived class, protected member of base class works as public in derived class. But when i implement this , i get a error
My code :
#include <iostream>
using namespace std;
class Shape {
protected :
void setWidth(int w) {
... | Yes, the derived class can access protected members, whether those members are data or functions. But in your code, it's main which is attempting to access setWidth and setHeight, not Rectangle. That's invalid just like using width and height from main would be.
An example of the derived class using the protected membe... |
63,753,290 | 63,753,335 | Reference to variable out-of-scope | I have made the following example to test my understanding of references:
#include <iostream>
int test(){
int a = 1;
int &b = a;
return b;
}
int main(int argc, const char * argv[]) {
std::cout << test() << std::endl;
}
What I intended to do is to write an example where the referenced variable is ... | The function does not return a reference to any object. It returns a temporary object of the type int that was copy-initialized by the value referenced by b.
int test(){
int a = 1;
int &b = a;
return b;
}
In fact the function is equivalent to the following function without using intermediate variables
int ... |
63,753,782 | 63,754,286 | What exactly is the expected format of the locale in setlocale()? | If I use the fputws without setlocale, only ASCII letters get printed. It seems that setlocale is necessary, and according to this site, both setlocale(LC_CTYPE, "UTF-8") and setlocale(LC_CTYPE, "en_us.UTF-8") would work.
But when I tried it, setlocale(LC_CTYPE, "UTF-8") did not work, and it printed "Hello ". Only with... | The answer is system specific. To quote the cppreference page you linked to:
system-specific locale identifier. Can be "" for the user-preferred locale or "C" for the minimal locale
I think "UTF-8" is an invalid locale name generally (it needs the language identifier at minimum, not 100% on that though). However gene... |
63,753,785 | 63,757,565 | C/C++ recv hangs altough local server sends data | I am having a hard time figuring out a bug in my TCP client-server app. The problem I am facing: in my recv function do-while loop, if the condition is bytes > 0, the function hangs forever. Replacing that with bytes == NMAX, everything works fine, UNLESS NMAX is equal to 1. A few side notes: doing a single send-recv w... | The problem with your program is that the receiving side does not know how many bytes to receive in total. Therefore it will just endlessly try to read more bytes.
The reason why it "hangs" is that you perform a blocking system call (recv) which will only unblock if at least 1 more byte had been received. However since... |
63,754,329 | 63,754,410 | Bit masking and bit manipulation | Let's say i have a byte sized variable like : unsigned char a = 0b0000'1111
and i turn on / off a certain bit using bit masking. I wanna know is this process of turning on / off slow for array of such unsigned char variables, for an array of size let's say like 20250000 etc
| It would be extremely fast to perform such an operation. Flipping bits in C++ would map to a relatively small amount of assembly code. There are x86 instructions to flip bits, so there is no reason for it to be slow.
With this said, If you are writing a bigger application, chances are high that somewhere else in your a... |
63,754,344 | 63,772,086 | Azure pipeline doesn't use specified compiler even though it is installed | We have an azure pipeline with a Microsoft-hosted agent that builds our c++ project for Linux, Mac and Windows. Because we use the std::filesystem library we needed to specify a higher GNU version in order to get it working on Mac and Linux. The issue is that while it works on Mac, Linux is still using gnu 7.5. How can... | In the 'ubuntu-latest', GNU 9.3 is not installed. So Linux still uses GNU 7.5 after specifying the GNU version as 9.3.
To solve this issue, You can change your imageName for linux from 'ubuntu-latest' to 'Ubuntu-20.04'.
Then you can use GNU 9.3.
The followings are my YAML file for the test and its builds log.
pool:
v... |
63,754,468 | 63,754,579 | Initialize an array with different index starting point to any N? | I've been sitting here for a few hours now, trying to figure out how an array can be initialized with specified array[index], no not 0-n, but n-N, meaning that index can be: 3, and then it increments to N.
int array[];
std::iota(std::begin(array), std::end(array), 2);
That line does one thing, but not what I want. Sin... | You can use std::fill to fill a range starting at index 2, with some value N, like this:
std::fill(std::begin(array) + 2, std::end(array), N);
|
63,754,477 | 63,754,603 | Virtual member function changes result of typeid - why? | this code is working fine and prints "yes":
#include <iostream>
using std::cout;
using std::endl;
class A {
public:
virtual void talk() { cout << "person talking" << endl;}
};
class B : public A {
public:
void work() { cout << "employee working" << endl; }
};
int main() {
A* pA = new B();
if (type... | This is how typeid works. A class that has no virtual members is a non-polymorphic type and carries no run-time type information. Hence there's no way to determine it's type at run time.
See [expr.typeid]/p2:
When typeid is applied to a glvalue expression whose type is a polymorphic class type, the result refers to a ... |
63,754,495 | 63,754,568 | How to print vector <vector<int>> in c++? | I am trying to assign and print vector<vector<int>> dynamically , However i cannot figure out how to do this i am stuck here is my program
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class A {
public:
vector<int> getVector(int s) {
vector <int> A(s);
for (int j = 0; j ... | vector<vector<int>> ::iterator it;
it = A.begin();
for (it; it != A.end(); it++) {
for(vector<int>::iterator it2 = it->begin(); it2 != it->end(); ++it2)
cout << *it2;
}
|
63,754,507 | 63,755,076 | Declare structure in header file and implement in source file | Whenever I try to implement my structure in my product.cpp file, I can't perform an instance of the object, because I get the following error "invalid use of incomplete type".
The temporary solution was to implement my struct in the product.hpp file itself. Is there any way to declare the structure in the product.hpp f... | There is plenty of mistakes. Let's start with product.h file. First of all, you put a multi inclusion guard. But you need to place your code between #ifndef and #endif block. Then you need to include string instead of iostream. Also, in C++ you do not need to declare typedef to use struct name as a keyword as in the C.... |
63,754,533 | 63,754,673 | Compiler cannot deduce type of template function? | I have the following code sample:
template<typename T>
void print(T t) {
std::cout << t << std::endl;
}
template<typename Key, typename Value, typename F>
void traverse(std::map<Key, Value>& m, F f) {
for (auto&& [key, value] : m) {
f(value);
}
}
int main()
{
std::map<int, std::string> M;
... | Template argument deduction works on the basis of the template parameters of the function, the signature of the function, and the types of the arguments provided. Nothing more. Even ignoring the fact that print is a template function (and therefore doesn't have a type that could be used for deduction), there is nothing... |
63,754,783 | 63,754,811 | c++ how to iterate over a collection of objects w/o explicitly created iterate-able container | i would like to loop over a fixed number of objects (all of the same type) without having to first explicitly create an iterate-able container with those objects as members, for example:
object_type a, b, c;
// do sth with objects a, b, c
for (auto &x in {a, b, c})
{ // do }; // wish: be able to loop over objects vi... | You can just iterate over an initializer list containing the objects:
for(auto o : {a, b, c})
// ...
Here's a demo.
You could also write auto &o, but note that o is not a reference to the actual objects a, b, and c, so you won't be able to modify them. If you want to do that, you could write it this way:
for(auto *o... |
63,755,145 | 63,755,523 | Problem with dynamic-memory-allocation while using constructors to a class | i am learning the concept of object oriented programing
Started with dynamic memory allocation , and find a problem in this code .
I cant find the problem in this code , in my opinion it all good
#include <iostream>
using namespace std;
class Team
{
private:
char *name;
char stadium[20];
char city[20];... | I corrected some typos in your code, modified copy constructor of class Team, and it works fine on my PC.
class Team
{
private:
char* name;
char stadium[20];
char city[20];
public:
Team(const char* i = " ", const char* stadium = " ", const char* city = " ")
{
name = new char[strlen(i) + 1]; ... |
63,755,403 | 63,755,737 | Why no race conditions in std:cout in Visual Studio 2019? | I wanted to show a friend a simple race condition example based on std:cout as a shared resource, as described in this article.
So, I entered the following code in a brand new Visual Studio 2019 console application:
#include <iostream>
#include <string>
#include <thread>
using namespace std;
void CallHome(string mess... | I changed void CallHome(string message) to print messages 100 times per thread,
void CallHome(string message)
{
for (int i = 0; i < 100; ++i)
cout << "Thread " << this_thread::get_id() << " says " << message << endl;
}
and I got the following messages.
Thread 10588 says Hello from Uranus
Thread 10588 says ... |
63,755,481 | 63,755,537 | Is static_cast creating new child object? | This code runs fine, when it should have a run-time error, since i haven't instantiated a derived class object.
#include <iostream>
using namespace std;
class Person {
public:
void walk() { cout << "person walking" << endl; }
};
class Employee :public Person {
public:
void work() { cout << "employee working" <... | No.
Your assertion that your code should "crash at runtime" is, unfortunately, wrong. Your code exhibits undefined behaviour meaning that it could do literally anything. In this case I expect it works because the address of the function is the same in both objects but really, it could be for any reason.
|
63,755,565 | 63,756,953 | What is this declaration in Cython? cdef PyObject **workers. Is it a pointer to a pointer? | I'm trying to utilize the concepts in this sample code to run some Cython code in parallel, but I can't seem to find any information in the Cython documentation about what this notation actually means.
cdef FLOAT_t[:] numbers
cdef unsigned int i
cdef INDEX_t n_workers
cdef PyObject **workers
cdef li... | Not only is it a pointer to a PyObject* pointer it's also the pointer to the first element of an array of PyObject* pointers.
You can see it is allocating memory to accommodate self.n_workers, presumably the workers are implemented using a PyObject derivative, so in memory you will have:
self.workers -> self.workers[0]... |
63,755,673 | 63,758,761 | Arduino. While loop with a timer inside an infinite loop | I have an arduino leonardo and I would like to make a while loop with a given work boundary inside an infinite loop. That is, an infinite loop repeats a ten-minute while loop. Is it possible to do it?
#include <Mouse.h>
#include <Keyboard.h>
#define timer 5 // running time of the while loop in minutes
void setup(){
... | According to the Arduino API reference for the millis() function, it returns an unsigned long which is necessary to hold "the number of milliseconds passed since the Arduino board began running the current program". The ATmega boards have 16-bit integers so your problem is integer overflow. Your ints are too small. Us... |
63,755,755 | 63,756,040 | Where am i going wrong for deleting a Node in a Binary Tree? | I am currently new to OOPS and was trying to write a class for basic Binary Tree implementation. When i try to delete a node, Inorder traversal doesn't work as it should.
Below is my current code. I have a few couts to LOG a few things as well.
#include<bits/stdc++.h>
using namespace std;
class Node {
pub... | if(t->right==delNode){
t->left=NULL;
delete(delNode);
You locate the node to be deleted on the right, but set the left pointer to NULL.
|
63,755,783 | 63,755,898 | Allocating twice - c++ | I saw a lot of similar questions about deleting twice, but what happens when you allocating twice and delete only once? isn't the old version is still exist and how does the program compile?
Don't I have to kind of release the new one too, because according to the d'tor it gets called only once.
For example:
int ma... |
what with the 5?? it will be a memory leak or something?
Yes! The second new will overwrite ptr, and you will need the old address for deleting the first allocation. Unless you save ptr it in another variable, or delete it before the second new, or use another variable name for the second pointer, you will have no wa... |
63,756,112 | 63,756,113 | Check the type of a generic lambda parameter | I have a generic lambda function that is called with several unrelated structs as its parameter.
Inside, I want to execute some code only if the parameter is of a special type.
auto const my_lambda = [](auto obj) {
// do something with obj
if (decltype(obj) == SpecialType) // <-- pseudo code, does not work
... | The approach with decltype already goes into the right direction.
Two types can be compared with std::is_same_v<Type1, Type2>
To prevent the compiler from complaining about the undefined .specialMember for the other calls, if constexpr is needed.
This amounts to:
auto const my_lambda = [](auto obj) {
// do somethin... |
63,756,458 | 63,756,624 | Pass std::istream and std::ostream by reference to be used from within function | I am trying to consume the following function:
void f(std::istream& input, std::ostream& output) {
int n;
output << "enter a number: ";
input >> n;
}
int main() {
std::istream is;
std::ostream os;
f(is, os);
return 0;
}
Error:
'std::basic_istream<_CharT, _Traits>::basic_istream()
Full err... | Have a look at the std::istream constructor and the std::ostream constructor and example also.
You want to do this:
#include<iostream>
void f(std::istream& input, std::ostream& output)
{
int n;
output << "enter a number: ";
input >> n;
}
int main()
{
f(std::cin, std::cout);
return 0;
}
Demo
inste... |
63,756,503 | 63,756,536 | Is this a way to check whether or not a LinkedList node is initialized? | I am trying to create an insert-at-end function for a linked list class. I was having some trouble, so I looked up some code and found the following:
if (!start) // empty list becomes the new node
{
start = newNode;
return;
}
This seems to be a check to make sure that if the user uses the function with an empt... | if (!start) // empty list becomes the new node
{
start = newNode;
return;
}
! negates whats in start. So if start is NULL then !NULL meaning true so it goes inside and make it as a start node. Similarly when start is not NULL then it doesn't go inside.
|
63,756,836 | 63,757,071 | Double pendulum with a single PID | I'm trying to understand how to use Drake to control a simple Double Pendulum using a PID controller.
Following the example at this link, I created a similar program but I only wanted to try to use 1 PID on the lower joint and see what the system did. (I am aware it is impossible to get to a stable state in this manner... | Instead of constructing PID controller with a scalar Kp, Kd, Ki gain, you should use a size 2 vector as the gain. Since you only want to control the lower joint, then only the entry corresponding to the lower joint is non-zero in the gain matrix.
I think you can change your code to
const Eigen::VectorXd Kp = Eigen::Vec... |
63,757,417 | 63,757,856 | Calling multiple commands via system() under windows doesn't work | So basiclly im trying to use this:
int main()
{
system("adb kill-server \n"
"adb devices \n"
"adb start-server & \n"
"var=$(adb shell \"pidof com.rok\")\n"
"AFTER=`echo $var | sed 's/\\r//g'`\n"
"echo \"$AFTER\"\... | Each call of system() creates it's own shell as a subprocess, that's why multiple subsequent system() calls don't work if you e.g. try to set shell variables or do a cd command (expecting subsequent commands running in a specific directory).
The easiest way to do it, is to create a little temporary script file containi... |
63,757,430 | 63,757,507 | error: lvalue required as unary ‘&’ operand - signal connect in Qt | https://doc.bccnsoft.com/docs/PyQt4/qplaintextedit.html
connect(&objQPlainTextEdit, &QPlainTextEdit::cursorPositionChanged,
this, &MainWindow::extractTextBlock( objQPlainTextEdit.textCursor().block() );
objQPlainTextEdit is QPlainTextEdit's object as a class member.
public:
QPlainTextEdit objQPlainTextEdi... | If you want to call extractTextBlock(objQPlainTextEdit.textCursor().block()) in the slot then you can use a lambda (untested)...
connect(&objQPlainTextEdit, &QPlainTextEdit::cursorPositionChanged, this,
[this]()
{
extractTextBlock(objQPlainTextEdit.textCursor().block());
});
The... |
63,757,483 | 63,757,863 | How to wrap a list of pointers to abstract class? | I try to wrap a list of smart pointers to abstract class (list<shared_ptr<Base>> list_) into some classes (Item, Drawer, Box). Then in the main function, I have a map of Box'es and it doesn't work. I found a way around and I can use new but I suspect that it just causes bugs which I can't see. How to make it work? Her... | In this line here
boxes.insert(std::pair<int, Box>(i, Box()));
You are creating a temporary Box object in your pair, which is moved into the map.
Let's call them Box1, the temporary that is created, and Box2, the move-constructed object inside the map.
When Box1 is created it correctly has a drawer which refers to the... |
63,757,523 | 63,759,769 | Error parsing input for const deceleration in ANTLR CPP Grammar | I am using the below ANTLR grammar for parsing my code.
https://github.com/antlr/grammars-v4/tree/master/cpp
But I am getting a parsing error in the below part of my code
const GstTensorsInfo info_in = {
.num_tensors = 1U,
.info = {{ .name = NULL, .type = _NNS_UINT8, .dimension = { 1, 10, 1, 1}}},
... | The designated initializer syntax (.num_tensors = 1U) was only added to C++ in C++20. The grammar you are trying to use is named "CPP14", which I suppose means that it is a C++14 grammar. In that case, it's not surprising that it doesn't accept the syntax.
You might be able to find something useful in a C grammar, sinc... |
63,757,941 | 63,758,010 | Difference in definition of null pointer in C99 and C++03 | N2431 is the paper that introduces nullptr. It says:
The current C++ standard provides the special rule that 0 is both an integer constant and a
null pointer constant. From [C++03] clause 4.10:
A null pointer constant is an integral constant expression (expr.const) rvalue of integer type
that evaluates to zero. A nul... | In C you have
An integer constant expression with the value 0, or such an expression cast to type void *
which means integer constants with the value of 0 and (void*)0 are valid null pointer constants.
In C++ you have
A null pointer constant is an integral constant expression (expr.const) rvalue of integer type that... |
63,758,003 | 63,758,054 | How can I conveniently initialize array of function pointers? | template<int I>;
void f(int value) { }
constexpr std::array<void(*)(int), 100> f_pointers = { &f<0>, &f<1>, &f<2>, ... &f<99> };
How can we fill f_pointers 0 ... 99 without typing them all out? Expecting the answer to involve std::integer_sequence unpacking, but reading pack expansion doesn't make it obvious how to e... | #include <array>
#include <utility>
template<int N>
void f(){}
template<int... Indices>
constexpr auto create_functions(std::integer_sequence<int, Indices...>)
{
return std::array {f<Indices>...};
}
constexpr auto arr = create_functions(std::make_integer_sequence<int, 100>{});
int main()
{
return 0;
}
|
63,758,216 | 63,758,671 | I can't use subclass specific funcitons when I add them to a vector using parent class pointers | I am trying to create an "alien invaders" game by myself. In order to create enemies and player, I created a class called "entity" and made subclasses of it. Like Player, shootingEnemy, IdleEnemy. When coding I realised gathering them in a vector<Entity> would make my collision detection function much easier.
After sea... | You need to check runtime polymorphism in C++. Let's check it out how can you do that. First of all, you need to change your Entity class interface. You need to add virtual or pure virtual functions. I have added pure virtual function;
class Entity
{
public:
int x;
int y;
int width;
int length;
i... |
63,758,274 | 63,758,402 | unexpected result removing a char from a string | For some reason the code below doesn't work. It looks to me like it has undefined behaviour but i can't figure out why.
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
void CIS_CIP_bdpm() {
string str = "oui";
string newStr;
char ch = 'u';
char ch2 = ... | From the documentation for std::remove (emphasis mine):
Removing is done by shifting the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the physical size of the container is unchanged.
It... |
63,758,287 | 63,758,364 | C++20 Concepts: Difference in the behavior of the compound requirement expression with a pointer-type member in GCC and Clang | Consider the following code (Godbolt):
#include <iostream>
//#include <concepts>
#include <type_traits>
// Since the latest clang doesn't have <concepts>,
// took this here: https://en.cppreference.com/w/cpp/concepts/same_as
// Using of std::same_as still gives an error in GCC.
namespace detail {
template< class T... | By my reading of [expr.prim.req.compound]/1, GCC is correct to emit an error:
The immediately-declared constraint ([temp.param]) of the type-constraint for decltype((E)) shall be satisfied.
With an accompanying example:
requires {
{ E1 } -> C;
{ E2 } -> D<A₁, ⋯, An>;
};
is equivalent to
requires {
E1; require... |
63,758,319 | 63,758,390 | Error while using >> operator overloading | The error looks like this (2nd last line):
Error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()')|
Here is the code:
#include <iostream>
using namespace std;
class Complex {
private:
int a, b;
public:
Complex(int x, int y) {
a = x;
... | Complex a();
This is a vexing parse. You think it means "default-initialize the variable a, which has type Complex." However, the compiler parses it as "declare a function called a which takes no arguments and returns a Complex value." The syntax is ambiguous: it could mean either, but the language prefers a function... |
63,758,485 | 63,758,536 | c++17: which versions of global operators new/delete must be replaced at least to cover all cases? | when globally overloading operators new and delete, which versions need to be implemented to cover all cases?
it seems before c++17 it was enough to implement void* operator new(size_t bytes) and void operator delete(void* ptr) since the array versions and the non-throwing versions of the default implementation were im... | From cppreference https://en.cppreference.com/w/cpp/memory/new/operator_new#Global_replacements (And a similar note with operator delete):
The standard library implementations of the nothrow versions (5-8) directly calls the corresponding throwing versions (1-4). The standard library implementation of the throwing arr... |
63,758,905 | 63,759,720 | Makefile to compile a list of sources to custom directory | I have this makefile:
IDIR = include
SDIR = src
ODIR = obj
BDIR = build
DEPS = $(shell find $(IDIR)/ -name '*.hpp')
SRCS = $(shell find $(SDIR)/ -name '*.cpp')
OBJS = $(patsubst %.cpp,$(ODIR)/%.o,$(notdir $(SRCS)))
BIN = main
CPPC = g++
CFLAGS = -Wall -c
all: dir $(BDIR)/$(BIN)
@echo Finished compiling $(BIN)
d... | Your $(OBJS) rule is wrong.
There are (at least) two ways to do this.
You could write a pattern rule and use vpath to locate the sources:
vpath %.cpp $(dir $(SRCS))
$(OBJS): obj/%.o: %.cpp
$(CPPC) $(CFLAGS) $^ -o $@
Or you could generate a rule for each object:
define template
$(patsubst %,obj/%.o,$(notdir $(1)))... |
63,759,015 | 63,759,085 | Template Class that takes a Template Class that Takes a Concrete Class | While I've seen a few posts regarding taking in template classes as a parameter into a template class I can't seem to find something that works with my code, or simply I do not understand the explanation well enough.
Ultimately, I'm looking for a template class that takes another template class which takes a standard c... | Firstly, you need a class or typename keyword before the template parameter name in the case of template-templates. Secondly, you should put the template<class> before TemplateClass, not ConcreteClass. TemplateClass is your templated type, so it needs that specifier:
#include <string>
// I had to make up your types be... |
63,759,706 | 63,764,677 | is it well defined which thread calls constructors of thread_local storage? | does the c++ standard define how, when and by which thread the constructors of thread_local variables are called? Is it for example always the thread itself for which the thread_local data is allocated? or maybe it's the thread that spawns the new thread? or the first thread of the process? or maybe it's up to the comp... |
[basic.start.dynamic] It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with thread storage duration is sequenced before the first statement of the initial function of a thread or is deferred. If it is deferred, the initialization associated with the entity for thread t... |
63,759,892 | 63,760,155 | How to disable MFC Edit control popup menu additional items? | Is there a clean and easy way to disable "Right to left reading order" and Unicode related messages from a context popup menu for an edit control. Yes, I know that I can subclass and intercept WM_CONTEXTPOPUP, then walk the menu. Attached is the image with menu items in question.
I
| I know you said you don't want to subclass, but I don't think it's that painful.
Derive from CEdit, in this case I used the class name CEditContextMenu and add WM_CONTEXTMENU to your message map:
EditContextMenu.cpp
// ...
BEGIN_MESSAGE_MAP(CEditContextMenu, CEdit)
ON_MESSAGE(WM_CONTEXTMENU, &CEditContextMenu::On... |
63,760,042 | 63,760,111 | Why is memoization giving the wrong output? | I am tryna solve a question using recursion+memoization. It is just modified Fibonacci with an additional start+3 step that can be done only K times. This is the recursive code I came up with:
#include <iostream>
using namespace std;
int helper(int start, int N, int K) {
// cout<<start<<" "<<N<<" "<<K<<"\n";
... | You're caching results in db based entirely on start, and ignoring K entirely. But helper(0, 7, 0) and helper(0,7,7) need to cache entirely different numbers at each index, based on whatever K is remaining. So you need the cache index to also be based on K.
I see three ways to optimize:
Have a cache of caches. db[s... |
63,760,095 | 63,768,052 | Why doesn't fstream work when called from Swift (Xcode)? | I'm working on an Xcode project that compares rendering with Metal and OpenGL.
It's separated in 2 different targets so the Metal part is in Swift and the OpenGL part is in C++.
I made a C++ class for model loading for both of them to access. The OpenGL(C++) part accesses it directly and the Metal part has some Objetic... | Disabling "App Sandbox" in the entitlements solved this.
|
63,760,247 | 64,724,836 | How to run SSH with system() in C++ | I've written a simple program to connect to a Linux server using SSH via my C++ program. Here's the code:
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int main()
{
string hostIP;
string username;
string password;
cout << "Welcome to SSH Program" << endl;
cout <<... | I've managed to solve this issue. It seems to have been a problem with the selected platform in Visual Studio. Initially the platform for the project was set for an x86 architecture. This is the reason why ssh.exe could not be accessed even though it was present in the environment path.
By changing the platform to 64-b... |
63,760,452 | 63,760,480 | C++ using {} instead of () for function call | In C++ I have seen a functioning library with a function with this signature
DocumentReference::DocumentReference(model::ResourcePath path, std::shared_ptr<Firestore> firestore)
: firestore_{std::move(firestore)} {
// code here removed for https://stackoverflow.com/
}
But the library calls the function using {... | It's not "calling a function". DocumentReference::DocumentReference is a constructor. There are many ways to construct an object and {} is one of those. See
Calling constructor with braces
When should we use parenthesis ( ) vs. initializer { } syntax to initialize objects in C++11?
Why is list initialization (using cu... |
63,760,539 | 63,770,749 | No way to set protobuf element by copyin instead of set_allocated_something? | On my generated protobuf classes, I see only set_allocated_something.
Example:
syntax = "proto3";
import "uuid.proto";
import "openvpn.proto";
package message;
message VPN {
UUID uuid = 1;
oneof vpn {
OpenVPN openVPN = 2;
}
}
then I have:
OpenVPN openVPN;
//fill openVPN
auto vpnAny = someObject.ad... | Protobuf generates copy constructors and copy assignment operators for every type. So the most normal way to copy a message into another would be something like
OpenVPN openVPN;
// (...)
*someObject.add_vpns() = openVPN;
|
63,760,838 | 63,760,899 | In C++, can you define a variable in terms of other variables that have already been defined? | For example, can I define a variable "z" in terms of variables I already defined called "x" and "y" (yes I know these are horrible naming conventions but it's an example). Like this:
int x = 0;
int y = 0;
int z = x * y;
Can you do something like that and just go on with your program or will you get error messages?
| You may be interested in lambdas:
int x = 0;
int y = 0;
auto z = [&x, &y](){ return x * y; };
This code does exactly what you are requesting: calling the z() function would always give you the result that is the multiplication of the x and y variables:
int v = z();
assert(v == x * y);
Even if x or y change you would ... |
63,760,925 | 63,761,004 | Constructor with ostream and istream parameters | I've got a question implementing a class constructor that has istream and ostream parameters. These values are to be used within the scope of the class. I am building a game that will ask questions and I want to use the istream parameter to collect the user input and the ostream to show things in the console.
class MyC... | I don't see any particular problems here (and your question hasn't mentioned any). For example
#include <iostream>
#include <fstream>
using namespace std;
class MyClass
{
public:
MyClass() : _in(cin), _out(cout) {}
MyClass(istream& in, ostream& out) : _in(in), _out(out) {}
private:
istream& _in;
ostrea... |
63,760,957 | 63,761,298 | C++ What's the difference between the way compiler accesses static members and accesses ordinary members? | Let's say that I designed a class like this :
// MyClass.h
#pragma once
class MyClass
{
public:
const int member = 1; // Since it is a const-integral type var...
static const int s_member;
...
};
then I can access each member like this :
// MyClass.cpp
const int MyClass::s_member = 2; // Initialization of... | First of all, you should realize that a const static member of integer type often won't involve any memory access at all. Unless you use it in a way that (more or less) forces the compiler to do so (e.g., taking its address) this will often (usually?) become simply a symbolic name for a constant. So, given something li... |
63,761,866 | 63,764,917 | Difference in behaviour between clang and gcc when trying to confuse them by using a template alias with a dummy parameter to conceal the base class | Consider the following c++ program:
class A
{
protected:
int x;
};
template<typename X>
using B = A;
template<typename T>
class C : public B<T>
{
public:
void f()
{
x = 0;
}
};
int main()
{
}
When compiled with clang and gcc using -std=c++17 -pedantic-errors as co... | This looks similar to CWG1390, and looks like Clang's behavior is consistent with CWG agreement on how such alias templates should be handled (substituted eagerly, at template definition time):
1390. Dependency of alias template specializations
According to 17.7.2.1 [temp.dep.type] paragraph 8, a type is dependent (am... |
63,762,006 | 63,762,286 | c++20 How to make a constrained tuple like container that contains only the allowed types and an instance of itself | Imagine I want to make a tuple like template container as part of api interface. And I want to constraint it to the list of allowed types plus an instance of this template container. Now I have something like this:
#include <string>
#include <tuple>
#include <utility>
#include <type_traits>
template<typename T>
conste... | You can check this by using partial template specialization.
template <typename T>
constexpr const bool bIsContainerType = false;
template <typename... Types>
constexpr const bool bIsContainerType<Container<Types...>> = true;
Then we just add it to you list of checks in bIsAllowedType
template<typename T>
constexpr c... |
63,762,707 | 63,762,743 | C++ Inconsistent result by set_intersection method on unordered_set and set | I was working on a problem on Leetcode when I encountered this inconsistency with unordered_set and set.
Let two vectors be nums1 = [4,9,5] and nums2 = [9,4,9,8,4]. We have to find their intersection so I did the following two things:
1.
unordered_set<int> s1 (nums1.begin(), nums1.end());
unordered_set<int> s2 (nums2.b... | In first snipped only first intersecting range is returned, because original set is unsorted
Constructs a sorted range beginning at d_first consisting of elements
that are found in both sorted ranges [first1, last1) and [first2,
last2). If some element is found m times in [first1, last1) and n
times in [first2, last2)... |
63,762,945 | 63,762,987 | Default "NULL" value for an ofstream | I have currently a function
int myfun(const int a) {
...
return rval;
}
that performs several actions.
I mean to adapt it to write debug information on its behaviour or not according to some parameter that I can pass.
In the cases I want to write that info, I also want to pass the ofstream to use.
And I want a... |
I want applications that were using myfun to still work with no modifications.
If so, use an ofs with default nullptr
int myfun(const int a, ofstream *ofs = nullptr)
{
if (ofs != nullptr)
{
// (*ofs) << ... ;
}
// ...
}
You can't use a reference parameter ofstream& ofs for such function beca... |
63,763,095 | 63,763,203 | How to set defines with the same name as a function in c /c++? | I have a not very well documented c library which allows me to override some functions. But sadly there are no examples :(
library.h:
#ifndef some_function
uint8_t some_function(void);
#endif
So I defined a function like this in my c++ code:
#include "library.h"
extern "C" uint8_t some_function(void) { return 0;}
vo... |
Any suggestions?
#define some_function some_function
Not advocating for this, of course, but it should work.
Maybe the author wanted to allow the users to define their own functions with different names. I.e. the macro is not meant as much for you, as for the library to use a custom function name.
uint8_t my_functio... |
63,763,112 | 63,967,247 | Trying to build a torchscript extension results in INVALID TYPE: Only int64_t and bool are supported as an integral argument type error | I'm following the torch_script_custom_classes in order to expose my C++ dll in Python. The bulk of the code that I have at the moment is as follows:
#include <torch/script.h>
#include <string>
#include <vector>
struct PyManager : torch::CustomClassHolder {
PyManager(std::string model_path,
std:... | The error is kind of misleading! all that was needed was to convert all return types from int to int64_t and that was it. All compiles just fine now!
|
63,763,304 | 63,763,447 | how default assignment operator works with string pointer | Should the code fail during runtime? Visual studio executes it without failure
#include<iostream>
#include <string>
using namespace std;
class Boy
{
string* _name;
public:
Boy(string n) :_name(new string(n)) {}
string getName() const { return *_name; }
};
int main() {
Boy t("Tom");
string str = "To... |
Should the code fail during runtime?
No, it shouldn't.
Let's dissect, what the following line does:
t = str;
There's a temporary Boy instance implicitely constructed. Thus it's merely the same as
t = Boy(str);
the operator= copies the pointer generated in the constructor to t._name.
The temporarily created Boy inst... |
63,763,481 | 63,763,636 | Undefined reference to overloaded operator inside of namespace | I'm having trouble using an overloaded operator that's declared inside of a namespace.
The setup looks like this:
classa.h
#ifndef CLASSA_H
#define CLASSA_H
namespace ns1 {
class ClassA {
public:
ClassA();
enum class MyEnum : unsigned {
VAL_A = 0,
VAL_B = 1,
VAL_C = 2,
VAL_D = 4,
VAL_E = 8
... | You need to define the operator in the same namespace that it's declared in, otherwise you have two different, unrelated operators (one of which is undefined, and the other only defined in classa.cpp).
Just wrap the entire implementation in a namespace ns1 block:
classa.cpp
#include "classa.h"
namespace ns1 {
ClassA:... |
63,764,639 | 63,764,724 | What is asio::io_service? | I am studying asynchronous I/O. i knows about select(), poll(), and epoll().
What I'm curious about is asynchronous I/O when using boost::asio. as a result of investigation, io_service is used. Which one of select(), poll(), and epoll?
| asio::io_service is outdated.
In newer boost versions it is replaced by asio::io_context.
io_context (formly io_service) main purpose executing ansynchrounous operations for object in the asio library, for ex. socket, acceptor, etc, according documentation:
...Synchronous operations on I/O objects implicitly run the i... |
63,764,651 | 63,775,329 | How to stop having a white square when using a sprite vector with SFML 2? | I'm trying to make a sprite vector but the first few elements always show a white square.
The variables are contained in the TileRPG class to then be used in the main.cpp
tile.cpp
void TileRPG::draw(int id, float x, float y, sf::RenderWindow& window) {
m_sprite[id].setPosition(sf::Vector2f(x, y));
window.draw(m... | The problem
From the sf::Sprite::setTexture() documentation:
the sprite doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function.
So, an sf::Sprite object doesn't store a copy of an sf::Texture object. By the way, this is related to The Flyweight Pattern, as it... |
63,764,678 | 63,764,710 | Assigning object address to a pointer is not working outside main | This code shows compilation error: ‘head’ does not name a type.
#include<iostream>
using namespace std;
class Node{
int val;
Node *next;
};
Node *head;
Node a;
head=&a;
int main()
{
}
However this one compiles fine.
#include<iostream>
using namespace std;
class Node{
int val;
Node *ne... | Assignment statement cannot exist outside a function body. You can convert the global version to initialization.
|
63,764,779 | 63,765,772 | Using CMakeLists.txt with multiple targets with different flags | I'm trying to compile the following file, into two different executables, using CMakeLists.txt.
This file is: main.cpp
#include <iostream>
#include <cassert>
int main(int, char**) {
std::cout << "Hello, world!\n";
assert(0);
return 0;
}
and this is the CMakeLists.txt file
cmake_minimum_required(VERSION 3... | Based on the CMake code, the tests executable should not produce an assertion error. You added the NDEBUG compile definition, which disables the assert macro per the assert documentation.
If you want to apply compile flags to specific CMake targets, you should use the target-specific CMake commands, such as target_comp... |
63,764,971 | 63,765,048 | Vector of objects with a unique_ptr member and custom destructor | Assume the following piece of code to move an object of type A into av (vector):
#include <memory>
#include <vector>
struct A
{
~A() {};
std::unique_ptr<int> an_int;
};
int main(int argc, char* argv[])
{
std::vector<A> av;
av.push_back(A());
return 0;
}
This will fail to compile as is. However... | Defining a custom destructor disables generation of the default move constructor and move assignment operator. Thus push_back(const A&) is used, but A does not have copy constructors either since it has unique_ptr member.
The solution is to manually define them as default. But defining the move constructor disables the... |
63,765,032 | 63,767,330 | problem with passing argument to QThreadPool::globalInstance()->start() | So i have this member function in AntiFlood class:
void AntiFlood::unBan()
{
QThread::msleep(5000);
std::string lineToPost = "KICK " + roomToPost +" "+ nickToPost + "\r\n";
sendIT(lineToPost);
}
and i want to pass it to:
threadpool.globalInstance()->start(unBan);
which doesnt work - results with error: ... | The basic problem you're seeing is that AntiFlood::unBan is (or at least 'appears to be') a non-static member function. That being the case it must be invoked against a valid object of type AntiFlood. Since QThreadPool::start has the signature...
void QThreadPool::start(std::function<void ()> functionToRun, int prior... |
63,765,063 | 63,765,105 | What is the difference between epoll and boost::asio::io_context? | I know that epoll and io_context work asynchronously. So, can you tell me what is the difference between the two?
Are you using epoll inside asio::io_context?
| POSIX gives us a suite of utilities useful for dispatching on events and watching for activity on file descriptors. One of those utilities is epoll().
Boost ASIO also gives us a suite of utilities useful for dispatching on events and watching for activity on file descriptors. io_context is what it sounds like: a "handl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.