question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
66,080,689 | 66,080,825 | C++ template for Runnable function | I am writing a library for thread management using C++ for my app and as part of the same I am trying to write a template class that takes a FunctionPointer to be executed inside the run function. I am a Java developer and trying to visualize as follows:
class MyRunnable : public Runnable {
public:
MyRunna... | Not sure... but seems to me that you're looking something as
class MyRunnable
{
private:
std::function<void()> mF;
public:
template <typename F, typename ... Args>
MyRunnable (F && f, Args && ... args)
: mF{ [&f, &args...](){ std::forward<F>(f)(std::forward<Args>(args)...); } }
... |
66,080,723 | 66,080,813 | Overload a virtual method in a derived class so it takes more parameters in C++ | I have an abstract class A with the pure virtual method void foo(int a) = 0
Then I have several classes that inherit from A and all of them define the method foo. But I need one of them, B, to make it so foo takes an extra parameter, int b, so sort of an overload.
Then I would like to do this:
A *bInstance = new B();
b... | You can use the overloaded function of B only if the pointer to use is of type B.
See:
#include <iostream>
#include <memory>
class A{
public:
virtual void foo(int a) = 0;
};
class B : public A
{
public:
virtual void foo(int a) override
{
}
void foo(int a, int b)
{
std::cout << a << "," ... |
66,080,782 | 66,081,628 | clang AST Matcher: Whats the best way to match the current Matcher over hasParent() | I am trying to search for ifStmts, which aren't an else if. To accomplish that, I want to test if the Stmt has a Parent, which is not an ifStmt(hasElse(ifStmt(equals(<myCurrentNode>))))
The following obviously does not work, but I could not find a better solution.
clang-query> m ifStmt(<myMatcherforMyNode>, unless(hasP... | Ok just found it out myself by searching the source of clang-tidy:
Just use something like ifStmt(ifStmt().bind("if"), <myMatcherForMyNode>, unless(hasParent(ifStmt(hasElse(ifStmt(equalsBoundNode("if"))))))).
Also, ifStmt(stmt().bind("if"), <myMatcherForMyNode>, unless(hasParent(ifStmt(hasElse(ifStmt(equalsBoundNode("i... |
66,081,003 | 66,081,120 | how do i find the location where a Spirit parser matched? | i'm parsing a simple configuration file format consisting of name-value pairs:
an_int_option 42;
a_string_option "foo";
an_identifier_option somevalue;
i have a basic rule to parse each item:
typedef boost::variant<int, double, std::string> config_value;
struct config_item {
std::string name;
config_value ... | You can use qi::raw[] to get the source iterator pair spanning a match.
There's a convenient helper iter_pos in Qi Repository that you can use to directly get a source iterator without using qi::raw[].
Also, with some semantic action trickery you can get both:
raw[ identifier [ do_something_with_attribute(_1) ] ]
[d... |
66,081,063 | 66,081,979 | Template function with different amount and type of parameters | so I have a template function:
int someFunc(int num) {
int a = num / 2;
int b = num + 10;
return a + num / b + b;
}
template<typename Type, typename Function>
Type test() {
Function func = (Function)&someFunc;
return func();
}
In the function test I now want to call other different functions, not... | You can do this via Parameter pack. It folds the Arguments that you have given.
I wrote a small example. I hope it helps you.
template<typename Func, typename... Args>
auto test(Func f, Args&... args)
{
return f(args...);
}
template<typename Func, typename... Args>
auto test(Func f, Args&&... args)
{
return f(... |
66,081,403 | 66,081,459 | Why my hashing using chaining program in c++ gives unexpected output? | I am trying to implement hashing in C++ from scratch. Everything seems to be fine except the output.
I am implementing hashing using chaining. This style of hashing uses a linked list for handling collisions. I used an array of linked lists of the type HashNode which I defined inside the HashTable class.
#include <bits... | One mistake is that
cout<<"\n Bucket " + i<<" =>"<<endl;
should be
cout << "\n Bucket " << i << " =>" << endl;
Another mistake is here
auto bucket = *(ptr + index);
for(auto x = bucket.begin();x!=bucket.end();x++){
if((*x).key == k){
(*x).val = v;
found = true;
brea... |
66,081,991 | 66,083,381 | get (multi)return value from a std::tuple function QtConcurrentRun | Hi I have a class for generate MD5 of some file in Qt, (I use tuple to return multiple value from it), I want to run it on other thread because its possible that generate all file MD5s takes some time and its freeze gui
I decide to use QtConcurrentRun for run it on other Thread, but so far I don't have any Idea about H... | Instead of getting value from QFutureWatcher you can send it via signal. And we can create a disposable QFutureWatcher that delete itself when the job done.
class HashGen : public QObject
{
Q_OBJECT
public:
HashGen(QObject *parent = nullptr);
private:
QString Md5_gen(QString const& fname);
public slots:
... |
66,082,843 | 66,083,121 | How to use typedef and define | I write this code to print on the output the current line and the file name:
#ifdef _DEBUG
char buffer[10000];
std::string const full_path = __FILE__;
auto const basename = full_path.substr(full_path.rfind('\\'));
sprintf(buffer, "Line:%d %s \n\n", __LINE... |
I mean a way to call it in just a single line.
std::string const full_path = __FILE__;
auto const basename = full_path.substr(full_path.rfind('\\'));
Generally, that's what functions are for. The only problem is the use of the macro that depends on what file it's in (__FILE__). Luckily, C++20... |
66,083,085 | 66,084,083 | Access octave struct member from c++ api | I have to create a c++ program to read and manipulate an image using the Octave C++ API. The image is in .mat binary format.
To read the file in octave I use
S = load("/path/to/file", "-mat", "house") // house is the var name
and S is of type scalar structure.
To read the file in c++ I have a created the following fun... | You can use subsref to extract variable "house":
octave_value val = out(0).subsref(".", {ovl("house")});
Matrix mat = val.matrix_value ();
It is assumed that house is a matrix. You can instead get it as a N-dimensional array of double values:
NDArray arr = val.array_value ();
Other data types are also available.
|
66,083,109 | 66,112,855 | How to extract genotype information for each sample as a string from a VCF file using htslib? | I am using htslib for extracting all the information contained in a VCF file in C++.
Currently, thanks to the VCF specification and the documentation in the file vcf.h, I have successfully extracted all the metadata information in the header (Meta-Information Lines), and most of the information contained in each row of... | I finally figured it out. There are some functions for doing this, depending on the type specified in the header for the format ID: the functions are inside of the vcf.h file in htslib:
#define bcf_get_format_int32(hdr,line,tag,dst,ndst)
bcf_get_format_values(hdr,line,tag,(void**)(dst),ndst,BCF_HT_INT)
#define bcf_ge... |
66,083,165 | 66,083,185 | How to reassign a bitset? | #include <iostream>
#include <bitset>
using namespace std;
int main()
{
// a = 5(0000000101)
unsigned char a = 5;
bitset<10> y(a);
cout<<y<<endl;
//Using left shift operator a = 10(0000001010)
a = a<<1;
bitset<10> z(a);
cout<<z<<endl;
}
I want to set the bitset y as the new refre... | Bitsets are CopyAssignable. Simple assignment works:
y = a<<1;
|
66,083,178 | 66,083,261 | Access child members within parent class when children are inside a vector of type parent | I have multiple child classes inside a parent class vector where each child has it's own type. The parent has a virtual getType function and each child overrides it with it's own; not even sure if I need this TBH but I got from this Access child members within parent class, C++
When I loop over the vector (loop not sho... | You just experimented slicing.
A Child is a Parent plus a few more things.
When you try to put a Child in the vector of Parent, only the Parent part of each of these Children is put in the vector (because the vector does not contain Children but Parents); hence the name slicing.
In order to obtain the dynamic polymorph... |
66,083,569 | 66,084,133 | boost::multi_index_container compiled with vs2008 but not with vs2019 | I have multi index container like below
typedef Lock_<boost::mutex> DefaultLock;
template<class ADD_DATA>
struct ResourceRawData : private boost::noncopyable
{
ResourceRawData(const TSTRING& pathFileName,bool bMustDirectory,const ADD_DATA& addData = ADD_DATA() )
{
...
}
ResourceRawData(const TSTRING... | Two-phase lookup was recently fixed in MSVC. You might now run into a diagnostic that this use of typename was actually non-conformant (should never have compiled):
typedef typename ResourceRawData< ADD_DATA > QUEUE_DATA;
Just remove it
typedef ResourceRawData< ADD_DATA > QUEUE_DATA;
very similarly, the compiler will... |
66,084,587 | 66,084,751 | Strange behavior using Generalized Lambda Capture | Basically, I was trying to write a C++ code to transform a vector<int> into a vector<pair<int, int> > where each entry of the output means <x, frequency x appears together>. For example, {1, 1, 2, 3, 3, 3} would become {(1, 2), (2, 1), (3, 3)}.
As a competitive programmer, readability or good practices are not prioriti... | Mutating the predicate in remove_if is not safe: the order of evaluation (yes, really!) and whether or not the predicate is "recopied" midway is unspecified. The standard algorithms intentionally have vague specifications to allow a lot of latitude in implementation. If you need to visit the elements in order, you need... |
66,084,828 | 66,084,896 | C++ Help: Error: lvalue required as increment operand | What is wrong here. What does it mean by the error: lvalue required as increment operand?
(NOTE: this is a textbook example)
#include <iostream>
using namespace std;
int main()
{
int num1 = 0, num2 = 10, result;
num1++;
result = ++(num1 + num2);
cout << num1 << " " << num2 <... | The ++x is called preincrement operator while x++ is called postincrement.
Both need a modifiable 'lvalue' variable as the operand. In this case x is the 'lvalue'.
If you have a code y = ++x it has the same semantic meaning as
x = x + 1;
y = x;
So this specific code ++(num1 + num2) is actually making the error because... |
66,084,931 | 66,084,976 | I have just started learning about Linked list using C++. I am trying to create a linked list using a vector. Why is the problem with this code? | #include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
// Constructor
node(int d){
data = d;
next = NULL;
}
};
// Linked List from Vector
void createList(node*& head , vector<int> v){
cout<<v[0];
head->data = v[0];
head->next = NULL;
node* last = head;
for(int i = ... | You are passing a null pointer (head) into createList, but you are dereferencing it immediately in the function with this line:
head->data = v[0];
Before you attempt to use it, head must point to something.
|
66,085,029 | 66,085,126 | Read numbers from a file into a multidimensional array | I have a .txt file that is formatted as follows:
906 25 25
1997 25 25
900 25 25
1990 50 1.75
1981 50 50
925 25 25
I have written the following code to read the numbers into an array:
float numbers[1029][2];
std::ifstream fin;
fin.open("GiftCardFinal.txt");
if (!fin.is_open())
{
return 0;
}
for (int i = 0; i < 1029... | Try to run this code:
#include <iostream>
#include <fstream>
using namespace std;
#define NUM_LINE 10000
int main()
{
float numbers[NUM_LINE][3];
std::ifstream fin;
fin.open("GiftCardFinal.txt");
if (!fin.is_open())
{
return 0;
}
for (int i = 0; i < NUM_LINE; i++)
{
f... |
66,085,056 | 66,085,173 | Trying to get hour int from time string but getting this error in c++ | #include<bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int h;
string s1;
getline(cin,s1);
cout<<s1;
h=10*(s1[0]-'0')+1*(s1[1]-'0');
cout<<h;
}
}
I gave below as input
1
11:01 PM
got this as output
-560
I want to conve... | Check this:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int h;
string s1;
getline(std::cin.ignore(), s1);
//getline(cin,s1);
cout<<s1 << endl;
h=10*(s1[0]-'0')+1*(s1[1]-'0');
cout<<h << endl;
}
}
I hi... |
66,085,165 | 66,085,316 | The sizeof() function followed by square brackets | I've seen an example showing as
int n = sizeof(0)["abcdefghij"];
cout<<n;
What does that thing in square brackets mean? I've read somewhere that (0)["abc"] is equivalent to ("abc")[0]. Meaning the above expression is simply
n = sizeof("abcdefghij")[0];
i.e. the first element.
| First, sizeof is not a function but an operator
sizeof(0)["abcdefghij"] can be parsed as either
sizeof( (0)["abcdefghij"] ), or
( sizeof(0) )["abcdefghij"]
Since sizeof has lower precedence than [], the former will take place
(0)["abcdefghij"] is equivalent to "abcdefghij"[0] which is just 'a', so the whole thing is ... |
66,085,336 | 66,086,194 | Write a program using conditional compilation directives to round off the number 56 to nearest fifties | Write a program using conditional compilation directives to round off the number 56 to nearest fifties.
Expected Output: 50
Where is the mistake?
#include <iostream>
using namespace std;
#define R 50
int main()
{
int Div;
Div = R % 50;
cout<<"Div:: "<<Div;
printf("\n");
#if(Div<=24)
{
... | The only sense-making way of interpreting the homework task is to consider 56 as an example and to require a compile-time constant result for any given integer number. The only sense-making way of using conditional compilation directives is taking also negative numbers into account.
#ifndef NUMBER
#define NUMBER 56
#e... |
66,085,962 | 66,110,385 | ns-3 logging - no logs on output | I'm trying to create new ns-3 module but somehow logs are not showing on output. I thought that it's problem with my code, so I copied first.cc and third.cc examples to the scratch dir and after running them, there was no logs too. I also tried to run them with an environment variable NS_LOG set to "*", but the output ... | It appears that you're using the optimized build. According to the Logging documentation of v3.31,
Logging statements are not compiled into optimized builds of ns-3. To use logging, one must build the (default) debug build of ns-3.
This is also the case for the latest development version of ns-3. To switch to the deb... |
66,086,492 | 66,087,064 | What is the most optimized way to assign a value to a two dimensional array? | I want to know what is the most optimal way to assign a value to a two-dimensional array?.
Say, I want to assign value 12 to the below array.
for (int i = 0; i < m; i+++)
for (int j = 0; j < n; j++)
array[i][j] = 10
Is there any better way to do this without for loop?.
| Your code is fine, readable and simple, except for the typos. Just make sure you use the same type for i and j as that of n and m.
#define N 10
#define M 10
int array[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++)
array[i][j] = 0;
}
The advantage of writing the code th... |
66,086,799 | 66,087,034 | Getting UB in my variadic template summing a variable number of vectors element-wise | I'm trying to make a function AddVector that adds a (variable) number of vectors element wise. I think I got it, but as I get the wrong output, I clearly don't. I'm adding three vectors of doubles, each sized 5, containing 1+2+1, thus I expect
4 4 4 4 4
I get
1.36234e-316 2.0326e-316 4 4 4
Which is clearly wrong (ma... | Not sure where lies your problem yet, You found it yourself :) ... But this is how I would implement it with C++17 and sizes:
#include <vector>
#include <algorithm>
template<typename T>
using Vec = std::vector<T>;
template<typename T, typename...Args>
Vec<T> AddVector_impl(Vec<Args> const & ... vecs){
auto sizes... |
66,086,885 | 66,087,154 | Fast int to float conversion | I am doing computations in Cuda using floats. Because we do not have enough memory on the GPU, we store the raw data as uint16_t and int16_t on the GPU. Thus, before I use this data I have to convert it to floats.
The number of ints is not that large (approximately 12k of uint16_t and the same number of int16_t). Profi... |
What is the fastest way to convert ints to floats.
Simple assignment. There are hardware type conversion instructions which the CUDA compiler will emit automatically without you doing anything. Hardware conversion includes the correct IEEE rounding modes.
Is there a substantial difference when converting int16_t ... |
66,086,922 | 66,087,095 | N-dimensional matrix class using vectors of vectors | I am trying to implement a custom class which handles n-dimensional matrices using vectors of vectors, generalizing the 1d, 2d and 3d definitions:
using mat1dd = std::vector<double>;
using mat2dd = std::vector<mat1dd>;
using mat3dd = std::vector<mat2dd>;
Here is my attempt to implement this class.
template <std::size_... | Use a template struct holding the type definition specialize it for n = 1:
template<size_t n, typename T>
struct matnd_helper
{
using type = std::vector<typename matnd_helper<n - 1, T>::type>;
};
template<typename T>
struct matnd_helper<1, T>
{
using type = std::vector<T>;
};
template<size_t n, typename T>
us... |
66,087,167 | 66,087,512 | noexcept operator with lambdas. MSVC bug? | It appears that MSVC treats all lambdas as noexcept. This code compiles in msvc 19.28 (checked in Compiler Explorer), but expectedly fails the static assertion in gcc:
void foo() {
auto lambda_may_throw = [] {};
static_assert(noexcept(lambda_may_throw()));
}
What is interesting is that I googled a bit but was una... | The behavior is only observed with /permissive.
When compiling with /permissive-, the assert triggers.
So perhaps it is a compatibility extension to support older Visual Studio code.
(You also may observe that it fails with /std:c++latest and compiles with /std:c++17 without specifying /permissive-. This is not the dif... |
66,087,497 | 66,142,778 | Debug C++ Standard Library with Visual Studio Code on macOS | I am using Visual Studio Code on macOS with the Microsoft C/C++ Extension to evaluate the real usability and productivity in a production environment.
In my scenario, I am using Clang/LLVM compiler and LLDB debugger.
For some unknown reason, I am unable to debug the C++ Standard Library. I can step into symbols defined... | The Microsoft C/C++ Extension support team points out that this is due to the default configuration of lldb. In fact, target.process.thread.step-avoid-regexp is set to ^std:: by default:
(lldb) settings show target.process.thread.step-avoid-regexp
target.process.thread.step-avoid-regexp (regex) = ^std::
Changing this ... |
66,087,573 | 66,089,025 | How to convert `ros::Time` to string while keeping the UNIX format? | Context:
I have image files with UNIX timestamps as their names, e.g. 1341846314.694004.png. The names correspond to the message header.stamp of the ROS .bag-file that publishes the images.
Using Python I generated bounding box files for each image and used the same pattern to name them, e.g. 1341846314.694004_bb.txt.
... | The time classes provides fields for secs and nsecs both in Python and C++. So you can use them and combine them to a string:
Python:
stamp = rospy.Time.now()
print(str(stamp.secs) + '.' + str(stamp.nsecs))
C++:
ros::Time stamp = ros::Time::now();
std::stringstream ss;
ss << stamp.sec << "." << stamp.nsec;
std::cout <... |
66,088,320 | 66,090,806 | I need 2 for loops to fill a matrix in Eigen but I can fill it with only 1 for loop in Matlab - can I get rid of the extra for loop? | I am filling an Eigen matrix with the following code:
int M = 3;
int N = 4;
MatrixXd A(M, N);
double res = sin(4);
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A(i, j) = sin(i+j);
}
}
In Matlab I only need 1 for loop to do the same thing using vectorization:
M = 3;
N = 4;
N_Vec = 0:(N-... | Using a NullaryExpr you can do this with zero (manual) loops in Eigen:
Eigen::MatrixXd A = Eigen::MatrixXd::NullaryExpr(M, N,
[](Eigen::Index i, Eigen::Index j) {return std::sin(i+j);});
When compiled with optimization this is not necessarily faster than the manual two-loop version (and without optimization it c... |
66,088,629 | 66,090,430 | Every time a string is turned to LPCWSTR or LPARAM it turns into chinese | I'm doing a desktop app using winapi.
It only happens whenever I try to do it with variables, whenever I pass just text, everything works correctly.
I tried switching out SendMessageW for SendMessageA, but the strings are still displayed wrong. When the text is put in, it is displayed correctly only with SendMessageA a... | Credit to Richard Critten
SendMessageW(TextField, EM_REPLACESEL, 0, (LPARAM)(tst.c_str())); You are castring and std::wstring to LPARAM not the data it contains.
|
66,088,947 | 66,090,115 | How to add cpplint.py check into CMake? | I am a newbie in CMake.
In my previous complie tools waf. it provide me a cpplint.py script that can check cpp source file's format, and make complie failed if the format is not good.
but i want to switch to Cmake. I googled this, but seems still cant make it work.
Can anyone tell me how to run cpplint.py when i make b... | I recommend to not try to run the linter through cmake and to instead keep cmake purely for building. You could for example use a shell script to run both linter and build in one command:
#!/bin/sh
set -e # makes script fail if any subprocess fails
python cpplint.py OPTIONS
cmake OPTIONS
cmake --build OPTIONS
|
66,089,775 | 66,089,894 | Concurrent producer/consumer queue design for different class types | I have two threads running, where the producer thread enqueues the concurrent queue (https://github.com/cameron314/readerwriterqueue.git) with different types of updates and a consumer thread which dequeues updates and executes different code paths based on the update type. These updates have to be processed in the cor... | Something along these lines, perhaps:
void ProcessA(std::shared_ptr<DataA> data);
void ProcessB(std::shared_ptr<DataB> data);
using UnitOfWork = std::function<void()>;
auto queue = moodycamel::BlockingReaderWriterQueue<UnitOfWork>(200);
// Producer
auto dataA = std::make_shared<DataA>();
queue.enqueue([dataA]() { Pro... |
66,090,304 | 66,090,429 | Correct sequence for initializing data members in C++ objects | When I am using this code, the output changes based on the sequence of declaration of the pointers in class
#include<iostream>
using namespace std;
class myClass{
int *y,*z,*x;
public:
myClass(int a,int b,int c): x(seta(a)),y(setb(b)),z(setc(c)){}
int* seta(int a){
cout<<a;
... | Because the members of a class/struct are ever initialized in the order of declaration.
In you first example, the order of declaration is y, z, x so the order of execution in the initialization list is
y(setb(b))
z(setc(c))
x(seta(a))
and isn't important the order you gave in the initialization list (but, as pointed b... |
66,090,346 | 66,090,490 | Pointer of array, what is the difference between (*ptr)[] and *ptr[] | I met a weird thing when I tried to understand the pointer tp this array
#include <iostream>
int main() {
using namespace std;
short tell[3]{1, 2, 3};
short (*pas)[3] = &tell;
cout << (*pas)[2] << endl;
cout << *pas[2] << endl;
cout << endl;
return 0;
}
I got two different values for ... | You declared a pointer to a whole array
short (*pas)[3] = &tell;
So to get the pointed object (array) you have to dereference the pointer like
*pas
Now this expression yields a lvalue reference to the array tell. So you may apply the subscript operator to access elements of the array
cout << (*pas)[2] << endl;
The ... |
66,090,403 | 66,171,039 | Quectel EC25 Sending SMS and getting +CMS ERROR 305 | This code sends some of SMS messages. But it gives error for some of the messages. It may about some wrong character that GSM module does not recognize like `(.
Is there any one can help to fix the code.
I am checking if GSM device is attached to ttyUSB2.
This is C++ code.
int sendSms(UsbPort &device, string phoneNumbe... | The problem was not about ASCII characters, but about sending a message longer than it should be.
When we use Concatenated SMS it solved our problem. It Send Sms without problem.
AT+CGMF=1
AT+CSCS="GSM"
AT+CSMP=17,167,0,241
AT+CMGS="Number"
> Message <CTRL+Z>
|
66,090,428 | 66,090,536 | Dump std::unique_ptr<uint8_t[]> content to file | To debug nncase and see it in action i like to dump the variable main_men_ declared here
like:
main_mem_.reset(new (std::nothrow) uint8_t[model_header_->main_mem]);
to be dumped into a file each time we cross here.
I see they access the object here
like:
base = (uintptr_t)main_mem_.get();
I tried to dump the content ... | I believe that what you want is std::basic_ostream::write:
myfile.write(reinterpret_cast<const char*>(main_mem_.get()), model_header_->main_mem);
|
66,090,823 | 66,105,602 | Count rows for merged cells using QAxObject | I need to read an Excel file with many merged cells. Suppose the first column contains the 'Category' value and the second column contains the 'sub_category' value. The problem is that each category cell might be a merged cell with multiple sub_categories in the second column. I need to know the number of rows witch th... | I finally got my answer from here:
https://blog.csdn.net/u18004660201/article/details/80350164
It's possible to get the number of the first line of the target cell and the first line of its next cell. It's doable by getting the cell's 'range' and 'MergeArea'.
for (int row = 2; row <= 150; ++row)
{
QAxObject *r... |
66,090,895 | 66,091,316 | convert c multidimensional array to multidimensional c++ vector | i am trying to convert c multidimensional array to multidimensional c++ vector, i mean, to convert something like this int arr[2][3] = {{1,2,3}, {4,5,6}}; into the correspondent vector.
The array isn't necessarily 2D shaped, it could also be something like this:
int arr[2][2][3] = {
{
{1,2,3},
{4,5,6},
... | The equivalent of a C multidimensional array is a flat C++ vector plus a mumtidimensional array view.
The naive equivalent is a vector of vectors (maybe of vectors), which actually corresponds to a C "jagged" array. The memory layout and performance characteristics will be very different.
There are many multi dimensio... |
66,091,065 | 66,091,266 | convert short form of tree string(parentheses) into full form | I want to convert a short form of a tree string expression (with parentheses) into the full form of it.
This is an example tree expression:
intput: ((((XX(XXX(XX
output: ((((XX)(XX))X)(XX))
and this tree looks like:
.
can some one provides me full code or at least some part of code in C++?
other example:
input: (S((S... | It is an inorder tree traversal process.
Root-->Left-->Right.
If you want I can write the full solution which will take some time.
Can You give me an example code(I mean is there any code snippets given)?
Or I have to write tree-building code and then output?
look at you code:
Let answer string = "";
step 01: root -->(... |
66,091,234 | 66,091,263 | Defining default values in c++ constructor? | Longtime java programmer here, recently switched to C++ for the first time.
I am trying to have several constructors for a Person class. I have defined Person as follows:
class Person {
private:
//stuff
public:
Person(std::string firstName, std::string lastName, int age);
Person();//I want to define a constru... | You are missing a ; after p1!
int main() {
Person p1 = Person("Chuck", "Norris", 55) <-HERE
Person p2 = Person();//SHOULD invoke no-args constructor
return 0;
}
|
66,091,284 | 66,091,418 | How to obtain constexpr `.size()` of a non-static std::array member | Given that std::array<T,N>::size is constexpr, in the snippet below
Why does it matter that Foo1::u is not a static member? The type is known at compile time and so is its size().
What's wrong with Foo2::bigger()?
Listing:
// x86-64 gcc 10.1
// -O3 --std=c++20 -pedantic -Wall -Werror
#include <array>
#include <cstdi... | These situations are a bit different.
In the first one:
static constexpr size_t length {u.bytes.size()};
//invalid use of non-static data member 'Foo1::u'
You're trying to access a non-static data member without an object. That's just not a thing you can do. There needs to be some Foo1 associated with this... |
66,091,423 | 66,091,756 | Checking if pointer args are null / Field should be initialized in the member initialization list for a raw pointer | I am reading about implementing Rule of Three/Five, and found examples on cppreference as well as this canonical answer on SO. I know that it doesn't make sense to use a char* in modern C++, but the point is to create some code which will need those three/five methods.
Cppreference starts with something like:
class rul... |
But the class doesn't check if s is null at all -- isn't this a potential problem?
That is a problem only if null is passed to the constructor. Otherwise it is not.
the second snippet actually has a null check which prevents me from using the member init list.
Having a null check doesn't prevent you from using the ... |
66,091,437 | 66,101,027 | C++ winapi Taking Screenshot and Making It Background of Window | I'm trying to make the snippingtool in c++. I managed to create a borderless, fullscreen window via this code;
WindProc:
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
switch (message)
{
case WM_CHAR: //this is just for a program exit besides window's borders/taskbar
if ... | Thanks for the comments, i did some more research on WM_PAINT message. And i found this golden document:
http://www.winprog.org/tutorial/bitmaps.html
My code in the original post stays the same, i only added 2 things;
1-Taking a screenshot of the screen and saving it;
(got it from here:
How can I take a screenshot in a... |
66,091,778 | 66,091,896 | Isn't the word "if" missing in the sentence below in [basic.link]/10? | Isn't the word if missing, just before the word all, in the sentence below at the end of [basic.link]/10?
As a consequence of these rules, all declarations of an entity are
attached to the same module; the entity is said to be attached to that
module.
| No, there's no missing "if", because that's not a valid option. As stated in the rule:
If two declarations of an entity are attached to different modules, the program is ill-formed; no diagnostic is required if neither is reachable from the other.
The consequence of this is that there's no well-formed program in whic... |
66,091,811 | 66,092,877 | Clang format for space around double colon (::) | Is there a way for clang format to add space around double colon used between class name and member function like class :: function.
Also is there a way that there be no space at all.
Currently majority of the legacy code has the format class :: function but auto formatting changes it to class ::function (removes spac... | No, there is no format option in Clang to add or preserve space after scope resolution operator (at least until version 10 whose options I checked).
|
66,091,817 | 66,092,025 | Is there a problem with common initial sequence with this union of std::array's? | Puzzled by Guillaume Racicot's comment here. Is there a problem with common initial sequence here or not? At least with GCC 10.1 x86-64 (-O3 --std=c++20 -pedantic -Wall -Werror) I write .words and read .bytes.
sizeof(MyUnion)==32 is reassuring, too.
union MyUnion {
static constexpr std::size_t size = 32;
using... | Standard says:
[array.overview]
... An array is a contiguous container. ...
An array is an aggregate that can be list-initialized with up to N elements whose types are convertible to T.
array<T, N> is a structural type if T is a structural type.
The standard doesn't explicitly say what members std::array has. As such... |
66,091,831 | 66,092,839 | Resolving to different types based on the argument types of a c++ template function | I'm doing some metaprogramming and I have ran into the following problem:
I have a class that takes one template parameter T, T can be assumed to be a function with an arbitary signature. The class a member variable V, that should have the type std::tuple<> if T takes no arguments or the first argument is not a std::tu... | Something along these lines, perhaps:
template <typename T> struct ExtractFirstTuple;
template <typename R>
struct ExtractFirstTuple<R()> {
using type = std::tuple<>;
};
template <typename R, typename... Ts, typename... Args>
struct ExtractFirstTuple<R(std::tuple<Ts...>, Args...)> {
using type = std::tuple<Ts... |
66,092,125 | 66,092,252 | Template functor and class template parameter deduction | I'm trying to implement a class which is an iterator across a linked-list. I want to templatize it so you can construct it with a functor to determine when we are iterating to the end, but I can't get the class constructor template deduction to deduce the type of the functor.
A reduced example of what I'm trying to do:... | For CTAD to work you can't supply any of the template parameters and since T can't be deduced, you need to supply the second template parameter too (that is, no CTAD).
Example:
auto l = [b]() -> bool { return false; };
C<B,decltype(l)> foo(&b, std::move(l));
You could add a helper function template though:
template<ty... |
66,092,516 | 66,092,657 | C++ class variable not changes after assignment | I have two classes and one is a private variable in the other.
The private member has a base class that have a variable as a private member.
The code is like below:
#include <iostream>
class Base {
public:
Base(): _p(5) {
}
void setP(int p) {
_p = p;
}
int p() const {
return _p... | The problem is in your operator=. You create a temporary Test and modify that, but you do not modify this object. The correct implementation is:
Test& operator=(const Test& rhs) {
setP(rhs.p());
return *this;
}
Please also note that operator= returns a reference Test&, not a Test.
|
66,092,618 | 66,095,083 | Switching *pointers instead of using BitBlt() in winAPI? | As I read, BitBlt() function from winGDI from winAPI is the fastest to put some image on the screen.
But "blitting" only copies a memory from one source to a destination.
So I was wondering, why we can't just have two bitmaps (buffers) and just switching the pointers that will point to the current buffer if it is compl... | The BitBlt method in GDI is to copy the contents of the back buffer to the redirection surface. A more efficient method has been implemented in directx.
The runtime uses the bit-block transfer (bitblt) and flip presentation
models to present graphics content on display monitors. The biggest
difference between bitblt a... |
66,093,522 | 66,094,193 | Bubble sort the numbers from a file in descending order for the first number | I want to sort using the "Bubble Sort" algorithm of the 2d array. My array size will be about array[100000][100000]. my input number will be n=100,000.
For now we can use a small size of the array to fix the sorting issue.
I need to sort them in descending order for the first number(first number's line).
If the firs... | Use a std::vector<std::array<int,2>>for your base container. The dynamic growth capabilities of std::vector solves your stack space issue, and the std::array use gives you tied cell comparison. I.e. you can do this:
std::array<int, 2> ar1{1,2}, ar2{1,3};
if (ar1 < ar2) ...
and it will do the right thing. The result ... |
66,093,541 | 66,093,619 | Is there a way in C++ to pass arguments by name like in python? | Is there a way in C++ to pass arguments by name like in python?
For example I have a function:
void foo(int a, int b = 1, int c = 3, int d = 5);
Can I somehow call it like:
foo(5 /* a */, c = 5, d = 8);
Or
foo(5, /* a */, d = 1);
| There are no named function parameters in C++, but you can achieve a similar effect with designated initializers from C++20.
Take all the function parameters and put them into a struct:
struct S
{
int a{}, b{}, c{}, d{};
};
Now modify your function to take an instance of that struct (by const& for efficiency)
voi... |
66,093,683 | 66,094,016 | What's the purpose of Boost pipe and why it's important? | Apologies if this question is overly broad. I'm new to C++ and trying to understand different stream types and why they matter (or doesn't matter).
I'm learning by coding a simple program that launch a child process, and process the output. I'm following the Boost process synchronous IO example: https://www.boost.org/d... | What Are Processes, How Do They Talk?
Programs interact with their environment in various ways. One set of channels are the standard input, output and error streams.
These are often tied to a terminal or files by a shell (cmd.exe, sh, bash etc).
Now if programs interact with eachother, like:
ls | rev
to list files and... |
66,093,874 | 66,093,899 | "Type name does not allow storage class to be specified" error when passing value as argument | I have been writing the foundations of an emulator for a 6502. I have a function that I want to use to set the zero and negative flags for a given register. This function is contained in a struct called CPU.
My code currently looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <cstdint>
typedef uint8_t BY... | register is a (deprecated) keyword. Pick a different name for the variable.
See:
Register keyword in C++
Why was the register keyword created?
|
66,094,377 | 66,094,454 | Problem with conversion from className * to className &(and the reverse) | Can someone , for the love of god please help me. I've been stuck on this for hours
This is the "father" .h file , which i am NOTallowed to alter at all
//------------ Declarations for List traits used in Test1 in main.cpp
template <typename T>
class ListTraits
{
public:
virtual unsigned int size() = 0;
virtu... | List& List::insert(const T &item) is declared to return a reference to List. this is a pointer to List. To return a reference to List, return *this:
List & insert(const T& item) override {
return *this;
}
|
66,094,678 | 66,104,870 | String erase function causing heap corruption | Hello I'm working on my string class and I wanted to add an erase function. So I figured I go with the strategy of copying the memory before the start index, then copy the memory after the length + start index. This would just copy over the data outside of the part you want to delete.
Here is my code right now.
//size ... | I don't know why but it stopped throw the exception, here's the current code if you want it.
void erase(const size_t& start, size_t length) {
if (start >= size) {
return;
}
if (start + length > size) {
length = size - start;
}
... |
66,094,763 | 66,095,419 | Unsure how to round integers in C++ | I am new to C++, so I'll do my best to explain my problem. I'm trying to output rounded values after the user inputs a low value and high value. The thing is that the output will only show the incremented values (and possibly zero as well). Here is how the increments are determined:
inputDifference = high - low;
if (i... | Code is not tested
You write a function double GetIncrement(double low, double high) with mostly the initial code snippet.
Then write a function that find the maximum range (floor minimum, ceil maximum)
std::pair<double> FindIncrementMutipleRange(double low, double high, double increment)
{
return std::make_pair(
... |
66,094,846 | 66,095,139 | Why std::ranges::view_interface using CRTP | According to cppreference, the helper class template for defining views view_interface using the curiously recurring template pattern (CRTP) techniques.
What is the design philosophy behind them? Is there a dramatic advantage versus overriding a virtual base class method in the derived class?
| If you give a base class virtual functions, then it has those functions. Always. It can never not have those functions, and every class derived from it will inherit those functions.
view_interface has an empty function if and only if the range category for the type is forward_range. That is, empty exists if begin retur... |
66,095,290 | 66,095,389 | How to construct a class with a constant reference cycle? | I am writing a toy program and I accidentally created a class that I don't know how to construct.
struct Parent;
struct Data {
const Parent &parent;
// ...
Data(const Parent &parent) : parent(parent) {}
};
struct Parent {
const std::vector<Data> datas;
// ...
Parent(std::vector<Data> &&data) : datas(std::... | You can use the fact that C++ allows self-referential declarations to create both the Parent and Data instances in the same statement:
Parent parent(std::vector{Data{parent}, Data{parent}});
I'm not sure how this design would be useful in practice, but as you said, this is just a toy program.
|
66,095,291 | 66,098,628 | Trying to build test-launch.c for gstreamer but fails to build | I am trying to build test-launch.c on my ubuntu machine (i5) with this command:
gcc -o test-launch test-launch.c `pkg-config --cflags --libs gstreamer-rtsp-server-1.0`
but it fails to build. The error message I see is the following:
test-launch.c:(.text+0x170): undefined reference to `gst_rtsp_media_factory_set_enable... | What version of GStreamer do you have installed? According to the documentation gst_rtsp_media_factory_set_enable_rtcp() is introduced with GStreamer 1.20 which has not yet been released.
|
66,095,939 | 66,096,239 | Pointer Statement in Scapegoat Tree | SGTNode **a = new SGTNode* [ns];
Can anyone please help me with this statement in Scape Goat Tree implementation in C++.
Link to C++ program : https://www.sanfoundry.com/cpp-program-implement-scapegoat-tree/
| That statement allocates an array of ns pointers-to-SGTNode (aka SGTNode *) on the heap.
After the statement completes, the local variable a is pointing to the first pointer-to-SGTNode in the array, which is why the type of a is SGTNode ** (i.e. a is a pointer-to-a-(pointer-to-SGTNode))
|
66,096,035 | 66,096,247 | Linked Lists: structure inside a structure? | I'm still kind of new in terms of working with Linked lists in C++. I was looking through my textbook and found this header file under the linked lists section.
//Specifcation file for the NumberList class
#ifndef NUMBERLIST_H
#define NUMBERLIST_H
class NumberList
{
private:
//Declare a structure for the list
stru... |
So I am wondering what exactly is happening on the line where it says struct ListNode *next;
As you mentioned later, it is a pointer that points to the next block of the struct ListNode. Check the following figure. The ListNode consists of Data and Next here. The Next is a pointer that points to the next ListNode cel... |
66,096,336 | 66,096,553 | How to add or change value for a declared string using string(int, char) function? | I know there is a way to give a value of a specific character being repeated n times to a string while declaring it, like this:
string example(int, char);
But what if I didn't give it a value initially, is it possible to use the repeated character function later?
I tried doing this but it didn't work:
string example;
... | You can't do exactly that, but here's the next best thing.
If you need to increase/decrease size, you can use std::string::resize(), which has a second parameter to fill the new chars. So try this:
std::string foo;
foo.resize(10, 'A');
std::cout << foo << '\n';
And the output will be: AAAAAAAAAA
However, note that if ... |
66,096,591 | 66,096,631 | How to comprehend inline, const and reference in a function declaration? | I noticed a function declaration in my program which included inline, const and reference(&) before the function name. It is easy to follow each of the keywords separately, but can anyone explain the overall meaning when they are used together?
inline const std::string& foo()
{
}
I'm new to CPP programming. Ah, puttin... |
const std::string&
This is the return type of the function, which is a reference to a constant std::string.
inline
This means that this function may be defined multiple times, but you are sure that those definitions are identical and the linker may keep one of those definitions and discard the rest. You usually use t... |
66,097,113 | 66,098,955 | dlopen Segmentation fault error when get a instance from shared library's exported function | I have been stuck in a problem for several days when using dlopen/dlsym to deal with the shared object. I desperately need your help!
There are three headers/source files: Animal.h, Animal.cpp and test.cpp, and two products: libanimal.so and a.out.
Here is the source code:
Animal.h:
// Animal.h
#ifndef STDLIB_ANIMAL_H
... | Ok, my suspicion from the comment has confirmed itself. The problem is with the early binding on animal->shout() which resolves at compile time to a call to _ZN6Animal5shoutB5cxx11Ev and this symbol is nowhere to be found.
If I change it to virtual (late binding, resolved at runtime through a vtable):
// Animal.h
#ifnd... |
66,097,168 | 66,097,204 | How to assign a pointer to object to another pointer to object of same class? | I have a class called arr and it has a function named _union written like this:
template<class T>
arr<T> *arr<T>::_union(arr<T> B) {
arr<T> *C(this->length + B._length());
bool isPresent = false;
for (int i = 0; i < length; i++)
C->push_back(this->get(i));
for (int j = 0; j < B._length(); j++) {... | In this code
arr<T> *C(this->length + B._length());
C is a pointer and this->length + B._length() is an integer, hence the error. You can't assign an integer to a pointer.
I guess you were trying to write this code
arr<T> *C = new arr<T>(this->length + B._length());
This code allocates a new arr<T> object using new a... |
66,097,210 | 66,097,502 | How can I access to different column in displayText function in QStyledItemDelegate | I am going to change the display text for one of my QTableView column. I inherit from QStyledItemDelegate class and change the definition of displayText according to the following:
QString CellIdDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
QString currentColumn = value.toString();
... | You can't since displayText() is for exactly one cell. It's only meant to add e.g. a prefix or suffix. If you want to display other text, modify the data returned by Qt::DisplayRole accordingly. This is nothing for a delegate.
|
66,097,341 | 66,097,479 | How to append or insert std::array elements into a std::vector? | I'm relatively new to c++ and I've tried to do some research, but while searching online I've mainly come across C arrays rather than std::array. What are the most efficient ways to append std::array elements into a std::vector, and to insert std::array elements into a std::vector? Should I use STL functions such as st... | "Appending" values can mean two things - you either want to copy/duplicate the elements in question, or you don't need them in the source container aftwards and might also move them into the destination container. Also, it makes sense to distinguish between insertion at construction time vs. appending to an existing, a... |
66,097,641 | 66,097,811 | Good way to code if (var=x) {var=y} atomicly? | Given this function:
#include <mutex>
std::mutex mut;
bool data_being_processed=false;
void process_data() {
std::lock_guard<std::mutex> lock(mut);
if (data_being_processed == false) {
data_being_processed = true;
// Process data
data_being_processed = false;
}
}
My understand... | std::atomic makes this fairly easy:
#include <atomic>
std::atomic<bool> data_being_processed{false};
void process_data() {
bool value = false;
if (data_being_processed.compare_exchange_weak(value, true)) {
// Process data
data_being_processed = false;
}
}
compare_exchange_weak sets the da... |
66,097,926 | 66,098,137 | How can I copy a templated instance with a virtual base class? | TL;DR
how can I copy the last element of a vector, given that this element is an instance of a template class which is also derived from a virtual base class?
I want to create a vector which will act as an undo stack. the stack should hold float and string based objects (and possibly other types). It might contain all... | Traditionally, it's done by adding clone method to the Base:
struct Base {
virtual std::unique_ptr<Base> clone() const = 0;
virtual ~Base() = default;
};
CRTP can be used to automate overriding this method here:
template<class Child> struct Clonable: Base {
std::unique_ptr<Base> clone() const final {
... |
66,098,155 | 66,098,267 | Do 'true' and 'false' have their usual meaning in preprocessor conditionals? | Given a C++11 compiler, which #error is the correct one it should end up with?
// no #includes!
#define SOMEMACRO true
#if SOMEMACRO
#error "it was true"
#else
#error "it was false"
#endif
Godbolt demo
Obviously I'm using #error just as a test. I know true and false are defined in the language proper, but this is ... | In all ISO C++ standards, both true and false are keyword constants, just like nullptr in C++11. So #if SOMEMACRO = #if true and the preprocessor will go to the truthy branch.
In C, however, neither true nor false is ever a keyword. They're macros defined to 1 and 0 respectively, as of C99 and with #include <stdbool.h>... |
66,098,229 | 66,099,189 | Give Reference to an Object in an other file results in "..." is not captured (Node MCU) | I having problems with giving over references in c++ for a node mcu. Im compiling with Platform IO (I tried Arduino also but had similar problems)
i structed my class like that in a .h
class mess_server{
private:
public:
int brerechnung_proz(Kalibrierung& kalibrierung, kali_dat& dat);
void server_init(Kalibrier... | Sorry, I missed the error a bit myself.
The problem is that you are using a lambda function here and your variable is not known in the lambda function unless you reference it.
server.on("/Kali_nass", HTTP_GET, [](AsyncWebServerRequest *request){
dat = kalibrierung.laden(); // not captured inside the lambda
... |
66,098,387 | 66,098,846 | How to run an old binary on modern GNU/Linux distribution? | I'm trying to run an old C++ program, compiled on CentOS 6, on modern GNU/Linux distribution (Gentoo Linux). Nowadays CentOS 6 is outdated as well as suggested libraries, so it is necessary to provide working environment for the binary.
I already tried to copy all necessary shared libraries from CentOS 6 required by th... |
Is there a reliable way
No. :p
Is there a way to run an old binary on modern Linux without containers or virtual machines?
You can run the program using the old linker and with the library path. When you have a old system chroot, you can:
LD_LIBRARY_PATH=$PWD/lib $PWD/lib/ld-linux-x86-64.so.2 ./my-program
But note... |
66,098,516 | 66,100,249 | C++, change data type of all the elements into a nested C array | i am trying to change the data type of all the elements into a nested C array, something like this.
const int a[2][3] = {
{1,2,3},
{4,5,6}
}
The arrays are "multidimensional", and i don't know how many dimension they have.
I figured out something like this:
template <class D, class T, unsigned S>
inline D& unif... | So, here's one way of doing it:
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdio>
#include <type_traits>
// array_type_swap convert T[a][b][c][...] to Y[a][b][c][...] for arbitrary
// dimensions
template <class T, class Y>
struct array_type_swap {
using type = T;
};
template <class T, class... |
66,098,530 | 66,170,288 | Retrieving the wrong data from gps | I have been trying to implement a program to print out my GPS coordinates. However, I receive data which makes no sense at all.
my class files:
class GpsHandler
{
public:
GpsHandler(const std::string& gpsDaemonIpAddress, uint16_t updateRate);
~GpsHandler();
void initialize();
void printoutData();
priv... | It was a problem of different library versions. Some changes in the gps_data structure were introduced in the newer version of libgpsmm (3.22) , while I used older one. Therefore, I was getting the wrong data.
|
66,098,792 | 66,098,912 | How to get value from declaration only once? | Say I have a function that I want to call multiple times. At the start of this function I have declared an integer for a value of zero, and at the end of it I increased its value by one. Now I want to save the new value so when I call the function again the value of that variable becomes 2. Is there a way to do that be... | you can use a static variable declared inside the function, since it is static the initialization to zero will happen only once and the rest of the time you call the function it will retain its value...
here is an example:
#include <iostream>
void foo(int x)
{
static int counter{0};
std::cout<< "this is x: " <... |
66,098,992 | 66,099,327 | C++ implicit conversion and universal forwarding on gcc 7.5 | I am creating a library component that uses universal forwarding.
This works fine in most cases but I have encountered a case where our linux build (seeminingly) incorrectly uses a copy constructor instead of a move constructor.
I was able to reproduce this in godbolt on gcc 7.5 (same as our linux build platform) with ... | The shown program (using return a;) is well-formed since C++17. As such, you need a C++17 conforming compiler to compile it. C++17 support in GCC 7 was experimental (C++17 hadn't been released yet).
Using return std::move(a); is well-formed since C++11, and such should work with much older compilers.
Regarding the dif... |
66,099,135 | 66,114,945 | Consuming nuget package made with .nuspec and .targets (C++) | Struggling to get a compiled c++ dll (both x86 and x64) packaged up so that a C# library can consume it.
Managed to pack and push the dll using nuspec file however when using VS2019 package manager it successfully installs the package however the reference does not appear. (Any Cpu)
.nuspec
<?xml version="1.0"?>
<packa... | Your steps are in a mess.
You should note that the targets file should be named as <package_id>.targets`, the same name as the nuget package id or it could not work. See this link.
Also, the targets file should be put into build folder of nupkg.
That are the two importance tips.
1) Please change your nuspec file to thi... |
66,099,362 | 66,099,722 | Initilize a vector of std future at construction | Consider following code:
#include <vector>
#include <future>
using namespace std;
void someFunction(){
//do something
}
int main() {
vector<future<void>> tasks1;
tasks1.emplace_back(async(launch::async, someFunction));
vector<future<void>> tasks2{ async(launch::async, someFunction) }; //doesn't compile... | future cannot be copied, only can be moved.
By
{ async(launch::async, someFunction) }
future is stored in initializer_list. All elements of initializer list are considered to be const, reference. const object as a source object can be only copied into the target vector, not moved, that is why the code compilation fail... |
66,099,443 | 66,112,059 | Visual Studio: project reference vs link static lib | In Visual Studio when I want use existing project in my solution I can either add it as a reference, or add it as a statically linked lib in other project properties. I'm confused when I should use with option and which benefits those two approached has.
PS: talking about C++ projects.
| In my opinion, when a project needs to use a library, you have to do at least two things:
Include header files corresponding to the library
When linking, add the corresponding .lib in VS
File When there are multiple projects in your solution, for example, Project A is exe and Project B is static lib. If Project A dep... |
66,099,466 | 66,099,864 | warning: decomposition declaration only available with -std=c++1z or -std=gnu++1 | I've got this warning:
warning: decomposition declaration only available with -std=c++1z or -std=gnu++1
for this code:
#include<algorithm>
#include<vector>
int main(){
std::vector<int> vect{ 10, 20, 30 };
const auto [min, max] = std::minmax_element(vect.begin(), vect.end());
return 0;
}
what does decomp... |
what does it mean?
The warning means that you've used syntax / language feature that was introduced to the language in C++17 standard (whose working title was C++1z), but you are compiling for an older standard version.
what does decomposition declaration in this context means?
"Decomposition declaration" is anothe... |
66,099,600 | 66,100,125 | use array to change every digit in a 3-digit number | #include<iostream>
using namespace std;
int main(){
int n,d1,d2,d3;
cout<<"Enter a 3-digit positive integer"<<endl;
cin>>n;
d1=n/100;
d2=n%100/10;
d3=n%10;
int a[3]{d1,d2,d3};
for (int i = 0; i < 3; ++i) {
if(a[i]!=0){
a[i]=10-a[i];
}
cout<<"The new number is :"<<a[i]<<endl;
}
}
This code takes a 3... | u can print the information out from the for loop or u can do for loop like this
for (int i = 0; i < 3; ++i) {
if(a[i]!=0){
a[i]=10-a[i];
}
if(i == 0)
cout<<"The new number is :";
cout <<a[i];
}
cout << endl
|
66,099,872 | 66,100,143 | C# / C++ passing struct got Access Violation Exception | Good morning,
I'm tring to implement a pos device. The native api is a C++ lib, that I have to use in my C# project.
I already imported almost all the functions required (working fine), but there is one of them that I cannot do it anyway.
This is the function into the C++ lib:
__declspec(dllexport) void setHost(char* i... | Just a quick guess
On the unmanaged side, the parameter type is Host* and in C++ you're passing &test_host.
However, on the C# side, you have a struct (a thing that is by default pass by-a-copy, so by-val) and you're passing just host to a function with declared params of:
private delegate
void cdecl __setHost(
... |
66,100,083 | 66,100,134 | C++17 to_string() converts floats with comma | This is happening inside a big project so I cannot really post a minimal reproducible example but I'll try asking anyway. I'm building a list of benchmarks application integrated with a framework we're working on and on one of them the convertion we require to make (float -> string) with to_string appears to reproduce ... | As stated in the Notes of https://en.cppreference.com/w/cpp/string/basic_string/to_string, to_string relies on the current locale for formatting purposes:
std::to_string relies on the current locale for formatting purposes,
and therefore concurrent calls to std::to_string from multiple threads
may result in partial se... |
66,100,349 | 66,100,443 | Do we need vectorization in C++ or are for loops already fast enough? | In Matlab we use vectorization to speed up code. For example, here are two ways of performing the same calculation:
% Loop
tic
i = 0;
for t = 0:.01:1e5
i = i + 1;
y(i) = sin(t);
end
toc
% Vectorization
tic
t = 0:.01:1e5;
y = sin(t);
toc
The results are:
Elapsed time is 1.278207 seconds. % For loop
Elapsed tim... |
Do we need vectorization in C++
Vectorisation is not necessarily needed always, but it can make some programs faster.
C++ compilers support auto-vectorisation, although if you need to have vectorisation, then you might not be able to rely on such optimisation because not every loop can be vectorised automatically.
a... |
66,100,910 | 66,104,257 | QPdfDocument/QPdfView: How to display an animated PDF? | I implemented a PDF Viewing widget in C++ using Qt, loosely based on https://doc.qt.io/qt-5/qtpdf-pdfviewer-example.html, using the pdfwidgets module. (For this question, we can assume that I copied the code in that link 1:1).
This works well so far.
But now the thing is, the PDF I want to display happens to be an anim... | It's not implemented at the moment. On Windows, you could use an ActiveQt widget to embed Acrobat Reader inside your application, if present. Otherwise you'd need to find a PDF rendering library - most likely a commercial one - that has such support.
|
66,100,945 | 66,102,259 | How to tell the compiler to optimize array access? | I have the following fragment of code. It contains 3 sections where I measure memory access runtime. First is plain iteration over the array. The second is almost the same with the exception that the array address received from the function call. The third is the same as the second but manually optimized.
#include <map... | template <typename T>
[[gnu::const]]
T& find_in_cache(T& var) { ... }
lets clang optimize the code the way you want, but gcc fails to handle the call as a loop invariant, even with gnu::noinline to make sure the attribute is not lost (maybe worth a bug report?).
How safe such code is may depend on the rest of your cod... |
66,101,028 | 66,101,172 | Lifetime of a class returned as const reference | If I try to return a string literal from a function, I can make these two versions:
std::string get_val()
{
return "1234";
}
const std::string & get_ref()
{
return "1234";
}
However, what confuses me is that I thought you need to have a long-lived object, in order to have an lvalue reference (I am reading con... | The second implementation is not valid.
Actually return "1234" creates a temporary(rvalue) string object(as if it was return std::string("1234")) which resides on the stack, and as soon as it returns the returned reference becomes a dangling reference as it was on the stack memory.
Recent compilers would make a warning... |
66,101,029 | 66,101,221 | operator[] of QVector returns incorrect value | There are 4 examples of QVector and operator=:
auto value1 = (QVector<int>() << 1)[0]; //value is 1 (correct)
auto &value2 = (QVector<int>() << 1)[0]; //value is -572662307 (incorrect)
const auto value3 = (QVector<int>() << 1)[0]; //value is 1 (correct)
const auto& value4 = (QVector<int>() << 1)[0]; //value is -5726623... | Deep copy has nothing to do with it. Copy on write mechanism (this is related to "deep copy") of QVector is completely transparent to you and doesn't impact your scenario. For now ignore this feature.
First of all take a look what is returned by QVector::operator[].
It returns reference to element of QVector.
Now when ... |
66,101,230 | 66,101,358 | SFINAE using std::enable_if: type parameter vs non-type parameter | template<bool F, typename = std::enable_if_t<F>>
auto func1() -> int { return 0; }
template<bool F, typename = std::enable_if_t<!F>>
auto func1() -> int { return 0; }
template<bool F, std::enable_if_t<F, int> = 0>
auto func2() -> int { return 0; }
template<bool F, std::enable_if_t<!F, int> = 0>
auto func2() -> int { r... | Because in the first case, a SFINAE failure remove only the default for a template parameter.
// in case F is true, you have
template <bool F, typename = void>
int func1() { return 0; }
template <bool F, typename> // no more default but still available
int func1() { return 0; }
So doesn't disable the function, and... |
66,101,480 | 66,101,729 | Is this Singleton Implementation Thread-Safe? | I've read the question and answers here, and learned that a true thread-safe singleton can be implemented with correctly placed memory barrier, which is stated here in chapter 6. I've come up with my own version of singleton implementation, by reviewing the code I've seen no memory ordering problem so far, but it diffe... | It is hard to beat a simple
class Singleton { ... };
Singleton* get_instance()
{
static Singleton instance; // guaranteed to be thread safe in C++11
return &instance;
}
Any access to the pointer after it has been returned is still not thread safe, but neither is access in your implementation.
|
66,101,548 | 66,110,162 | Is it safe to use parallel execution policies with std::back_inserter? | I would like to know whether using execution policies std::execution::par and std::execution::par_unseq is safe when the output is std::back_insert_iterator. For example:
std::vector<std::string> src(100, "test"), dst;
std::move(std::execution::par_unseq, src.begin(), src.end(), std::back_inserter(dst));
Is it guarant... | Calling push_back on a std::vector does not match the requirements of par_unseq or par.
So no, it isn't safe.
By saying par you are promising that access to the iterators used for input and output contains no race conditions. That fails here.
par_unseq requires more promises from you; basically that you are both data-... |
66,101,573 | 66,102,125 | How to fix C++ error: terminate called after throwing an instance of 'std::bad_alloc'. what(): std::bad_alloc | My apologies, I know this type of question already has an answer over here but I couldn't figure out how to use it for my code.
I wrote a program for a problem-solving contest that accepts an array and tries to maximize the value of |Ax−Ay|+|Ay−Az|+|Az−Ax| over all triples of pairwise distinct valid indices (x,y,z). Th... | you have to do something like this: I am not getting data via cin I am just specifying the value.
void solve()
{
ll n =100000000;
vll v;
v.reserve(n);
//omitted
}
it runs fine,and it does not throw bad_alloc error. In your case, n may be uninitialized, and is not getting valid input so it pass n that ... |
66,101,774 | 66,101,920 | C++ appending to vector of strings efficiently (and idiomatically) | If I want to fill a vector of strings with lines from a file in C++, is it a good idea to use push_back with std::move?
{
std::ifstream file("E:\\Temp\\test.txt");
std::vector<std::string> strings;
// read
while (!file.eof())
{
std::string s;
std::getline(file, s);
strin... | Except for the eof misuse, this is the pretty much the idiomatic way to do it yes.
Below is the correct code:
std::string s;
while(std::getline(file, s))
{
strings.push_back(std::move(s));
s.clear();
}
Note the explicit s.clear() call: the only guarantee you have for a moved-from object std::string is that you... |
66,102,053 | 66,102,654 | Can pointers to different types have different binary representations? | I wonder if C++ implementations are allowed to represent pointers to different types differently. For instance, if we had 4-byte sized/aligned int and 8-byte sized/aligned long, would it be possible to represent pointers-to-int/long as object addresses shifted right by 2/3 bits, respectively? This would effectively for... | Yep
As a concrete example, there is a C++ implementation where pointers to single-byte elements are larger than pointers to multi-byte elements, because the hardware uses word (not byte) addressing. To emulate byte pointers, C++ uses a hardware pointer plus an extra byte offset.
void* stores that extra offset, but int... |
66,102,166 | 66,102,257 | Use of std::span<std::span<uint8_t>> | I use a lot this new functionality of C++20 : std::span<T>. This is useful for writing functions that usually took a pointer and a size.
#include <array>
#include <span>
#include <vector>
std::vector<uint8_t> v1 {1,2,3,4,5};
std::array<uint8_t, 4> v2 {1,2,3,4};
uint8_t v3[3] = {1,2,3};
void f(std::span<uint8_t> arr){... | That doesn't work because the vector doesn't contain spans. The mistake is somewhat analogous to trying to pass an int[x][y] into function accepting int**.
You should either:
Use a std::span<std::array<uint8_t,10>> to access the vector
void f2(std::span<std::array<uint8_t,10>> arr)
Or transform the vector into a ... |
66,102,274 | 66,145,732 | QProcess input string with accents | I have two programs each with QProcess and I have a different behavior concerning the QProcess input with accentuated characters
(more precisely I create a Qprocess to execute a dos copy command and the path takes accent).
The environnement of execution and development is Windows 10.
The first program is a simple proto... | I tried to recreate your behaviour with Qt 5.15 and could create a file with accent with
start("cmd",{args...})
start("cmd /c args...")
setNativeArguments("/c args...") + start("cmd")
Last one is recommended for "cmd" calls, see the remarks here:
https://doc.qt.io/qt-5/qprocess.html#start
The only thing, which did no... |
66,102,393 | 66,102,436 | Why is the destructor of the inherited class not called? | Why Circle destructor is not called?
#include "stdafx.h"
#include <iostream>
class Shape {
public:
Shape() {
std::cout << "Shape Constructor\n";
};
~Shape() {
std::cout << "Shape Destructor\n";
};
};
class Circle: public Shape {
public:
Circle() {
std::cout << "Circle... | By default, inheriting doesn't allow your derived class destructor to call the base class's destructor automatically. But defining the base class's destructor as virtual enables the derived class to call the base class's destructor implicitly before destruction.
|
66,102,425 | 66,103,367 | Ubuntu+CMake, Cannot static-build C/C++ android-ndk programs | my friend, I've come across the following problem that gives me a headache. Can you help me to point out where the problem is?
NDK r20b
Building the environment involves three libraries
C ++ 11/ STL
OpenSSL 1.1.1i
Boost 1.7.0
The above three libraries, through the static library link to the target-exe
A:
-DANDROID_ST... | According to NDK C++ library support:
In general, you can only use a static variant of the C++ runtime if you have one and only one shared library in your application.
Note: This rule applies to both your code and your third party dependencies.
So, it means that you need to compile all of your stuff with "-DANDROID... |
66,102,710 | 66,107,112 | Generating hash with Argon2 on Botan results in garbage data and 0xC0000005: Access violation reading location 0x0000000100000000 | I'm trying to hash passwords using the C++ cryptography library Botan. I've tried testing out the library using the code below:
#include <iostream>
#include <string>
#include <botan/argon2.h>
#include <botan/system_rng.h>
int main() {
Botan::System_RNG rng;
std::string password = "cool_password";
std::str... | After 4 hours of painful troubleshooting and rebuilding the library with different compilers over and over, I have found out that Botan does not work properly if "solution configuration" is not set to "Release" rather than "Debug" in Visual Studio.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.