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 |
|---|---|---|---|---|
70,265,274 | 70,265,838 | C ++ using multiple cores breakes output , code for a math problem | So, for start im just starting to learn c++, and i had to resolve this problem: Find the numbers with the propriety : 5 * 5 = 25 , 25 * 25 =625(25squared), 6*6 =36(6squared) ( 25 is the ending of 625, 5 is the the ending of 25 ). So i've got my code to find all the numbers lower than 30k , but then i wanted to push it ... | So i've resolved it , special thanks to Raymond Chen for his comment and the blog he directed me to, http://supercomputingblog.com/openmp/tutorial-parallel-for-loops-with-openmp/
This site explained it really well.
I declared the variables as late as possible, also changhed to LLInt_Max as openmp doesnt want to work wi... |
70,265,335 | 70,265,417 | Assert function in C++ using cassert function - How can I declare the variables in the test function? | #include <iostream>
#include <string>
#include <cassert>
using namespace std;
void test();
void test() { //my attempted test function in order to ensure the program works correctly
string answ1 = "noooooob";
string answ2 = "saaaaaadie";
string answ3 = "trish";
assert(answer(answ1) == "nob"); //this is where i get ... |
Either you forgot to include a header where you define a class or a function with name answer
or you don't need it and just comapre strings:
assert(answ1 == "nob"); // operator== kicks in
assert(answ2 == "sadie");
assert(answ3 == "trish");
You should be aware that assert is a debug-only feature. It compiles to noth... |
70,265,716 | 70,266,355 | Can't understand the task of given function | New to Cpp. In the given code, I don't know what change_val(int k) = 0; means and why the compiler prints
error: cannot declare variable 'ob1' to be of abstract type 'B'
B ob1(10);
error: invalid new-expression of abstract class type 'B'
ob2 = new B(100);
To my knowledge, neither B nor A has been d... | We'll start with a quick review of your code:
#include<iostream>
using namespace std; // Bad practice
class A{
int x;
public:
A(){x=0;} // Bad practice; utilize default member initialization
explicit A(int x){ cout<<"Constructor of A called"<<endl; // Bad practice; utilize initialization section
... |
70,265,748 | 70,265,844 | why is there a race condition in this multithreading snippet | I have this code in c++ using multithreading but I am unsure why I am getting the output I am getting.
void Fun(int* var) {
int myID;
myID = *var;
std::cout << "Thread ID: " << myID << std::endl;
}
int main()
{
using ThreadVector = std::vector<std::thread>;
ThreadVector tv;
std::cout << std::t... |
I am wondering if there is a race condition for the i variable
Yes, most definitely. The parent thread writes to i, which is a non-atomic variable, and the child threads read it, without any intervening synchronization. That's the exact definition of a data race in C++.
and if so, how does it interleave?
Data rac... |
70,266,813 | 70,267,093 | how to implicitly convert a foo<const bar> into a const foo<bar> in C++ template? | I'm making my own vector container and I'm trying to implement an iterator that works like the real one, using the C++98 standard.
This is homework so I don't want the answer just a hint as to where I should look and what I should learn to be able to tackle this problem.
So basically I'm trying to make this code work:
... | It seems from your comments in your code about what is failing that you are missing a comparison function for when iterator is to the left and the const_iterator is to the right. You could add this free function:
template<typename T>
bool operator==(const iterator_vector<T>& lhs, const iterator_vector<const T>& rhs) {
... |
70,267,209 | 70,267,258 | C++ Compile time specification of array size | I'm attempting to create a struct to hold a file header within the declaration section of a class in a header file. This involves calculation of a value that is known at compile time, and I want to use it to size an array within the header.
This is an extract from a header file of what I've most recently been trying:
... | The modern way would be to use a constexpr, to tell the compiler it is an actual compile-time constant. See a simpler example:
constexpr int Size = sizeof(long) * 7;
class Foo
{
int t[Size];
};
or
class Foo
{
static constexpr int Size = sizeof(long) * 7;
int t[Size];
};
|
70,267,323 | 70,267,694 | Insert integer into the middle of string c++ | I am trying to replace the W with the number 5 (in this example). However, when I try, I only get the the ascii value of 5 to replace the W, instead of the number 5 itself. How would I fix this?
NOTE: I this is a shortened example from a longer project. I need to access the number in nums[1].
#include <iostream>
#... | You can convert a digit to an ASCII character: char c = '0' + 5 (gives you '5').
This is your code fixed:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nums[3] {4,5,6};
string str = "HELLO WORLD";
cout << str << endl;
str[6] = '0' + nums[1];
cout << str << endl;
... |
70,267,387 | 70,278,120 | Why is is_trivially_copyable_v different in GCC and MSVC? | When running this simple program, different behaviour is observed depending on the compiler.
It prints true when compiled by GCC 11.2, and false when compiled by MSVC 19.29.30137 with the (both are the latest release as of today).
#include <type_traits>
#include <iostream>
struct S {
int a;
S() ... | GCC and Clang report that S is trivially copyable in C++11 through C++23 standard modes. MSVC reports that S is not trivially copyable in C++14 through C++20 standard modes.
N3337 (~ C++11) and N4140 (~ C++14) say:
A trivially copyable class is a class that:
has no non-trivial copy constructors,
has no non-trivial mo... |
70,267,454 | 70,267,560 | Why copy/move assignment operator should be declared non-virtual? | According to CppCoreGuidelines C.60 and C.63, copy assignment operator (e.g Foo& operator=(const Foo& x)) and move assignement operator (e.g Foo& operator=(const Foo&& x)) should be declared non-virtual.
Can you explain me the reason of this recommandation ? As suggested by this answer, I imagine that this is to avoid ... | There is no reason why a copy or move assignment operator should be virtual. Making it virtual possibly incurs costs associated with having virtual functions (e.g. the requirement to allocate a vptr within each object of the class) for no benefit.
Let's say you have a class Base, which has a virtual copy assignment ope... |
70,267,659 | 70,286,053 | Problem with display function inside circular queue | #include <stdio.h>
# define MAX 3
int queue[MAX]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{
front=0;
rear=0;
queue[rear]=element;
... | So... here's a working solution.
#include <stdio.h>
# define MAX 3
class CircularQueue
{
private:
int queue[MAX]; // array declaration
int front;
int rear;
public:
CircularQueue() :
front(-1),
rear(-1)
{ }
// function to insert an element in a circular queue
void enqueu... |
70,267,685 | 70,269,309 | Generic constructor template called instead of copy/move constructor | I've designed a simpler wrapper class that adds a label to an object, with the intent of being implicitly convertible/able to replace the wrapped object.
#include <string>
#include <type_traits>
#include <utility>
template < typename T, typename Key = std::string >
class myTag{
T val;
public:
Key key;
te... | It isn't shadowing the copy and move constructors. It is just beating them in overload resolution in some cases.
If you pass a myTag<float>&, the forwarding constructor is used.
If you pass a const myTag<float>& the copy constructor is used.
If you pass a myTag<float>&&, the move constructor is used.
If you pass a con... |
70,267,801 | 70,267,981 | C++ concatenate from two arrays to one dynamic erray that are initialized from 2 input text files using filestream | I'm trying to concatenate two arrays that were initialized from file input into one dynamic array and returning it to an output file but while testing I found out that the returned dynamic array is initialized with random numbers. I'm sorry for my lack of experience as I am a beginner.. These are my input text files
In... | If you're using c++ you should consider using vectors instead of arrays.
They make operations like these way easier.
Here's for reference:
https://en.cppreference.com/w/cpp/container/vector
https://www.geeksforgeeks.org/vector-in-cpp-stl/
You can referer to this post to see how to concatenate two vectors. Concatenati... |
70,267,950 | 70,271,188 | How can I fix the argument type conversion compiler errors in this method using a lambda function? | I am programming for the ESP32 (a sort of Arduino like chip). However, to easier/faster find compiler errors/warnings and later make a sort of virtualization on the PC, I like to compile the code also on a PC (using Visual Studio).
However, I cannot get the following code to compile on a PC (while it compiles in the Ar... | I've checked your reference github, it seems that the origin AsyncWebServer class has such signature:
AsyncCallbackWebHandler& on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest);
And ArRequestHandlerFunction is actually:
typedef std::function<void(AsyncWebServerRequest *request)... |
70,268,197 | 70,268,237 | Overloading a function by return type? | One of the most viewed questions here on SO is the question that deals with overloading of various operators. There is something I don't understand about the overloading of brackets operator operator[]. My question is about the following code:
class X {
value_type& operator[](index_type idx);
const value_type... | For overloading to work the functions need to have different signatures (the return type does not count).
In methods the this pointer to the object also counts as an implicit (first) argument. Static methods of course don't have a this pointer, so they can be treated like global functions.
In your example the two metho... |
70,268,201 | 70,268,246 | Techniques for cutting down on verbosity when do polymorphism via std::variant rather than inheritance | Say you have entities in a 2D game framework or something similar -- e.g. a GUI framework -- where there are various types of entities that share common properties like position and rotation but where some of these properties must be handled on a per-entity type basis e.g. rotating a simple sprite is performed differen... | Just use a visitor:
#include <variant>
struct state_a{};
struct state_b{};
struct actor
{
std::variant<state_a, state_b> state;
};
// basically no need to declare them as members.
void rotate(state_a, double deg)
{
// do a
}
void rotate(state_b, double deg)
{
// do b
}
void rotate(actor& a, double deg)
{
... |
70,268,250 | 70,290,923 | ImportError when accessing static variables from class in same namespace [C++/pybind11] | First of all, I am relatively new to C++ programming and pybind11. The following example should explain my problem:
a.h:
namespace test {
class A {
public:
static int something;
};
void setSomething(int input);
}
a.cpp:
#include <pybind11/pybind11.h>
#include "a.h"
int test::A::something;
void test::setSo... | Presumably you have used the above code to build two modules. Something like a.so and b.so that you would import into Python with separate import a and import b statements.
That's not going to work: You need to access the static variables through the same binary object. Even if you got the linking to work right, ::test... |
70,268,429 | 70,268,868 | Creating t* array with adresses to t array fields | Can the following code be shortened?
size_t n_arr{4};
int arr[4]{1, 4, 5, 6};
int* arr_p[4];
for (; n_arr—; )
arr_p[i] = &arr[i];
The adresses are all chained together, so is there a more efficient way of grabbing a block of adresses and storing them in another array?
| You could do
#include <numeric>
...
std::iota(std::begin(arr_p), std::end(arr_p), arr);
where std::iota is typically used to generate a sequential range of integers, it's generic and so generates a sequential range of pointers starting from arr (which itself is short for &arr[0]).
More explicitly,
#include <algorithm>... |
70,268,546 | 70,328,438 | Need a faster way to create an adjacency list in c++ | I'm trying to create an adjacency list from an input of vertices, edges and single connections. The input looks like this:
3 2 (vertices, edges)
1 2 (connection)
1 3
Right now, my code is
int vertices, edges;
scanf("%d %d", &vertices, &edges);
vector<vector<int>> storage[vertices+1];
for (int i = 0; i < edges; i++) {
... | It's nearly impossible to give a general answer to this kind of question, because the execution time is going to depend on factors that may be orders of magnitude apart. For instance, it could be that the cost of populating the data structure is insignificant compared to what you do with it afterwards. See also this an... |
70,268,598 | 70,268,915 | Should you return a reference using operator+ for adding two classes together? | From the examples I have seen when people use the operator+ when adding two instances of a class, the usual pattern is to return an object. Suppose we have a Vector class with attributes u and v, an implementation of operator+ could be,
Vector2 Vector2::operator+(const Vector2& other) {
return Vector2(this->u + oth... |
Should you return a reference using operator+ for adding two classes together?
No.
Why is the standard pattern not to return a reference?
Because the binary + operator conventionally returns a new object.
Vector2 v = Vector(10,20) + Vector(30, 40), would v later be pointing to a garbage collected variable?
No. C+... |
70,268,804 | 70,269,188 | How does std::visit handle multiple variants? | Related to, but not the same question as How does std::visit work with std::variant?
Implementing std::visit for a single variant conceptually looks like this (in C++ pseudocode):
template<class F, class... Ts>
void visit(F&& f, variant<Ts...>&& var) {
using caller_type = void(*)(void*);
caller_type dispatch[] = {d... |
For multiple variants, it seems to be more complicated, as for this
approach you'd need to compute the Cartesian product of all the
variants' alternatives and possibly template thousands of functions.
There are currently two implementations of multi-variant visitation.
GCC constructs a multi-dimensional function tabl... |
70,268,991 | 70,269,262 | What's "pitch" in cudaMemcpy2DToArray and cudaMemcpy2DFromArray | I'm converting the deprecated cudaMemcpyToArray and cudaMemcpyFromArray into cudaMemcpy2DToArray and cudaMemcpy2DFromArray. Rather than size of the deprecated calls, the new API calls for width, height, and pitch. The descriptions of spitch and dpitch are correspondingly "Pitch of source memory" and "Pitch of destinat... | It should be:
pitch=sizeof(float)*W
width = sizeof(float)*W
height = H
The above is for cudaMemcpy2DToArray, and assumes you are transferring from host to device, which would most likely involve an unpitched allocation in host memory as the source.
The pitch of a pitched allocation is the size in bytes of one line of ... |
70,269,418 | 70,269,625 | Copy all files .doc or .docx in folder and subfolder into another folder | I am new to C++ and winapi, currently working on a project to create a winapi application with a function to copy all files .doc and .docx in one drive to another folder.
Below is what I have done and it doesn't seem to work:
Can anyone show me how to do this properly ?
void cc(wstring inputstr) {
TCHAR sizeDir[MA... | if (!wcscmp(FileSearch.c_str(), L".doc") || !wcscmp(FileSearch.c_str(), L".docx"))
This is comparing the whole file name. We only need to compare the file extension. PathFindExtension can be used to find the file extension:
const wchar_t* ext = PathFindExtension(findfiledata.cFileName);
if (_wcsicmp(ext, L".doc") == 0... |
70,269,593 | 70,269,682 | C++ Get name of a template function argument | I want to replace all glXXXX calls to GL_CALL(N, ...) so that I can print function and arguments to trace the calls.
For example, replace glClearColor(0.0f, 0.0f, 0.0f, 1.0f) to GL_CALL(ClearColor, 0.0f, 0.0f, 0.0f, 1.0f) and in console I get [GL_CALL] glClearColor(0, 0, 0, 1)
#include <iostream>
template <class T>
vo... | You can pass the string name of the function into GL_INVOKE, something like this:
template <class F, typename ...Args>
auto GL_INVOKE(const char* fname, F f, Args && ...args) {
std::cout << "[GL_CALL] " << fname << '(';
GL_TRACE_PRINT(std::forward<Args>(args)...);
std::cout << ")\n";
return f(std::forward<Args>... |
70,269,889 | 70,282,968 | How can I back up to an earlier value in Depth-First Search c++? | Here, I'm implementing Depth-First Search (DFS) in c++. However, I can't seem to find a way to back up to the previous place (i.e. 1->2->3 if 3 is end of line go back to 2)
Can I use vectors or stacks to track my movements?
int searcher(int line[3], int lineNumber) {
int value = 0;
if (line[0] == 1) {
i... | Use a vector and add a new movement everytime you switch to a different position.
|
70,269,944 | 70,270,105 | Casting base class to derived class when derived class only adds non-virtual functions | Suppose I have something along these lines:
class Base {
public:
Base(int value) : value_(value) {}
int getValue() const { return value_; }
private:
int value_;
};
class Derived : public Base {
public:
// Derived only has non-virtual functions. No added data members.
int getValueSquared() const { return valu... | In practice, most compilers will convert a non-virtual member function into a static function with a hidden this parameter. As long as the function doesn't use any data members that aren't part of the base class, it will probably work.
The problem with UB is that you can't predict it. Something that worked yesterday ... |
70,270,325 | 70,280,019 | How to reduce the size of the executable? | When I compile this code using the {fmt} lib, the executable size becomes 255 KiB whereas by using only iostream header it becomes 65 KiB (using GCC v11.2).
time_measure.cpp
#include <iostream>
#include "core.h"
#include <string_view>
int main( )
{
// std::cout << std::string_view( "Oh hi!" );
fmt::print( "{}"... | As with any other library there is a fixed cost and a per-call cost. The fixed cost for the {fmt} library is indeed around 100-150k without debug info (it depends on the compiler flags). In your example you are comparing this fixed cost of linking with the library and the reason why iostreams appears to be smaller is b... |
70,270,538 | 70,270,577 | Setting all items in an array to a number without for loop c++ | Right now, to set all items in an array to, say, 0, I have to loop through the entire thing to preset them.
Is there a function or shortcut which can defaultly set all values to a specific number, when the array is stated? Like so:
int array[100] = {0*100}; // sets to {0, 0, 0... 0}
| If you want to set all the values to 0 then you can use:
int array[100] = {0}; //initialize array with all values set to 0
If you want to set some value other than 0 then you can use std::fill from algorithm as shown below:
int array[100]; //not intialized here
std::fill(std::begin(array), std::end(array), 45);//all ... |
70,270,749 | 70,272,863 | Emplace a std::array of non-movable objects that cannot be default constructed | I have a class that contains a std::mutex so it is not movable or copiable.
struct MyObject {
MyObject(std::string s_) : s(s_) {};
std::mutex lock;
std::thread worker;
std::string s;
};
I can easily add this object to this map:
std::map<int, MyObject> my_map;
my_map.emplace(std::piecewise_construct,
... | With custom array, you might do
template <typename T, std::size_t N>
struct MyArray
{
template <typename... Us>
MyArray(Us&&... args) : arr{ std::forward<Us>(args)...} {}
std::array<T, N> arr;
};
void foo()
{
std::map<int, MyArray<MyObject, 3>> my_map;
my_map.emplace(std::piecewise_construct,
... |
70,270,823 | 70,278,551 | Why don't compilers call destructor automatically when an object is declared using new operator? | #include<iostream>
using namespace std;
class b {
public:
int *a;
b (int val) {
*a = val;
}
~b() {
cout << "destructor" << endl;
delete a;
}
};
int main() {
b *obj = new b(1);
cout << "end" << endl;
return 0;
}
Expected output:
destructor
end
Receiv... | There are at least three different reasons for creating an object with new; depending on why you do it, it may or may not be appropriate to delete it when done.
The primary one is that you want to manage its lifetime:
int *create(int i) {
int *result = new int(i);
return result;
}
Here, you don't want to destr... |
70,270,927 | 70,271,403 | How to manage various types of functions as containers | I am trying to manage function list through c++ template.
template<typename T, typename... Args>
std::map<std::wstring, std::function<T(Args...)>> mFuncs;
Above code is not the correct sentence, but like above code concept, I want to manage various types of functions as a List.
void RegisterFuncs()
{
mFuncs.emplace... | use std::any
std::map<std::string, std::any> f;
int i = 3;
void RegisterFuncs()
{
f.emplace("func1", std::function<double(int)>([&](int k){i = k; return 5.0; }));
f.emplace("func2", std::function<bool()>([](){return false; }));
// ^^^^^^^^^^^^^^^^ cant use lambda type becuase any_cast ... |
70,271,468 | 70,272,669 | c++ enum characher from integer value | So my problem goes like this, i have to enter a number from 1-7 and for each respective number i have to print a letter from the word english(e is for 1, n is for 2, etc.)
Here is my idea:
#include <iostream>
using namespace std;
int main()
{
enum eng {e='e', n='n',g,l,i,s,h}
};
int x;
cout << "dati x\... | Discussing enums is somewhat beyond the scope of the question, because an enum is just the wrong tool here. The values of the letters in the word "english" are not consecutive and the names of an enums named constants are not easily accessible, hence the enum does not help to map an index to a character.
The tool to ma... |
70,272,799 | 70,273,923 | Cannot create a socket in QT in windows | I am trying to open a socket in QT Creator and it compiles successfully but returns -1 when calling socket function (fails to create the socket).
I am using the following code:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned int sockfd = socket(AF_INET, SOCK... | I was not calling WSAStartup. The following code is working.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h> // Needed for _wtoi
int main()
{
WSADATA wsaData = {0};
int iResult = 0;
SOCKET sockfd;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0... |
70,273,072 | 70,275,024 | How to use c++20 <ranges> in xcode 13? | I'm trying to use c++20 library in Xcode 13.1
#include <ranges>
I have set Apple Clang - Languages - C++ to -std=c++20 and compiler default, but it still throws 'ranges' file not found.
| According to this feature list
https://en.cppreference.com/w/cpp/compiler_support/20
Clang 13 claims "Partial" support, while Apple Clang seems to have none.
(Don't be confused by version numbers. Apple 13.1 doesn't have to be later than LLVM 13.0).
|
70,273,437 | 70,273,659 | C++- Filling a 2D array from user input | I'm new to programming and was finding transpose of a matrix.
However, I want the input of the matrix from the user and by writing the following code, the complier doesn't take any input values and immediately stops.
I looked into previous questions posted here about the same but found non useful.
#include<iostream>
us... |
You can't use variables in array length if they aren't defined as one of the comments mentioned.
arr[i][j] inside your nested for loop isn't declared so that would also give an error, I guess you wanted to use num array which you declared.
The rest is all looking good
|
70,273,826 | 70,274,707 | Reference Initialisation and Expression expected errors on for loop in cpp | Hoping that someone could provide some insight into the below 'error' that VS code is flagging in my C++ code.
I recently got a new laptop (Macbook Pro M1 Pro chip) so I have set up my environment now. Everything looks good, however I seem to be getting reference initialisation and expected expression errors in a for l... | Apologies for the stupid question - as @molbdnilo advised in the comments, my configuration in vs code was set to too low of a standard - updated to c++11 and all looks good.
Thanks I'll try to refrain from stupid questions in future :)
|
70,273,948 | 70,276,092 | std::remove_reference clarification with code snippet | I am trying to understand how to use the std::remove_reference functionality in type_traits.
This is the piece of code that I made
template <class T>
class example {
public:
T some_int;
example(T inty) : some_int(inty){std::cout << "constructor called!" << "\n";}
~example(){std::cout << "destructor called!"... | When you return a copy of the object, that creates a new object, which is what you want.
So one destructor is the for the copy, and one is for the original.
In other words your code works, but you can't see the copy constructor, add the line
example(const example& cp) : some_int(cp.some_int){std::cout << "copy cons... |
70,273,951 | 70,309,736 | How to sign data using ECDSA algorithm, in C++ with OPENSSL? | I have a 32bytes SHA256 digest data and need to sign it with ECDSA. The private key is in a .pem file. I've already made it in console using the command: openssl.exe dgst -sha256 -sign ecc.pem -out %sigfile% %data_file%. Now i need to do it in c++ and the results I have been getting isn't the same as in console.
What a... | I found the solution I've been searched for. Reading some project examples that used ECDSA from OpenSSL, I realised that I needed to convert the ASN1 encoded signature to raw signature bytes. So, here is the approach I used to get the wished result:
After sign the data by EVP_DigestSignFinal() function the code below w... |
70,274,134 | 70,275,010 | Merge two bitmask with conflict resolving, with some required distance between any two set bits | I have two integer values:
d_a = 6 and d_b = 3, so-called distance between set bits.
Masks created with appropriate distance look like below:
uint64_t a = 0x1041041041041041; // 0001 0000 0100 0001 0000 0100 0001 0000
// 0100 0001 0000 0100 0001 0000 0100 0001
uint64_t b = 0x92492492492... | If target is uint64_t, possible d_a and d_b can be converted into bit masks via look-up table. Like lut[6] == 0x2604D5C99A01041 from your question.
Look up tables can be initialized once per program run during initlalization, or in compile time using macro or constant expressions (constexpr).
To make d_b spread, skippi... |
70,274,287 | 70,274,328 | Is there any method to use 'delete' more efficiently instead of deleting one-by-one? | I'm trying to make function that gets only int parameters. So when other types(double, char, bool) are included I used delete to exclude that like this code:
#include <iostream>
using namespace std;
int add_int(int x, int y){
return x + y;
}
int add_int(double, double) = delete;
int add_int(int, double) = delete... | Yes, you can use a function template that deletes everything.
template<class X, class Y>
int add_int(X, Y) = delete;
Now, when the compiler is resolving a function call, it will select the template unless there is a function overload where implicit type conversion is not required. An overload that requires no convers... |
70,274,364 | 70,274,933 | Generate constexpr array (error: the value of 'sum' is not usable in a constant expression) | The Problem
I need to generate all possible partitions of an integer m into the sum of j elements a_k, where each a_k can be -1, 0, or 1. This is a deterministic algorithm and as such it should be able to implement it at compile time. I would like to return a std::array with all possible combinations as constexpr.
My A... | You're confusing the purpose of constexpr function. A constexpr function can be executed both at runtime and as part of constant expression, that depends on how you use the function (and probably if the compiler wants to optimize things at compile time).
You don't need all these templated functions, since the whole pur... |
70,274,623 | 70,275,067 | I have problem with least privilege principle. incrementing a member when an object is created | I want to keep track of the number of students in my system so, My idea was to make a static datamember in the "StudentController" class called "_numOfStudents" and increment it with the Student's constructor but it didn't work so, I moved it into the "Student" class and made that when a Student object is created the n... | When you try to do StudentController::_numberOfStudents++; in the constructor, the StudentController class is not yet defined, therefore the compiler doesn't know about that class and its static member.
|
70,275,112 | 70,275,240 | C++-Output multiplication of two matrices using 2D matrix | I am new in programming and was doing a question about multipliaction of two matrix which are inputted from the user.
I think I wrote the correct code for it. However, the output is a null matrix and I cannot pin point the mistake.
#include<iostream>
using namespace std;
int main(){
int row1,col1,row2,col2,val;
... | When you are setting up your matrices (arr1 and arr2) you are using an incorrect index.
for(int j=1;j<=col1;j++){
arr1[row1][col1]
should be
for(int j=1;j<=col1;j++){
arr1[i][j]
Also, as mentioned, indices in C and C++ go from 0 to N-1, so you are accessing one value out-of-bounds. You should use:
for (int j ... |
70,275,235 | 70,275,897 | C++ - Implicit conversion of unsigned long long to signed long long? | I'm having a rather strange warning being reported by clang-tidy 12.0.1. In the following code:
#include <vector>
int main()
{
std::vector<int> v1;
const auto a = v1.begin() + v1.size();
return 0;
}
I see this warning being triggered:
error: narrowing conversion from 'std::vector<int>::size_type' (aka '... | To show the actual types involved :
// Operator+ accepts difference type
// https://en.cppreference.com/w/cpp/iterator/move_iterator/operator_arith
// constexpr move_iterator operator+( difference_type n ) const;
#include <type_traits>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> v1;
a... |
70,276,228 | 70,276,348 | Why does for cycle in vector of unique_ptr require default delete? | I am working in vs2019 and following code worked fine:
std::vector<Foo*> foos;
// fills vector
for (Foo* foo : foos) {
//do stuff
}
However, if i try to use unique_ptr like this:
std::vector<std::unique_ptr<Foo>> foos;
// fills vector
for (std::unique_ptr<Foo> foo : foos) {
//do stuff
}
then both vs and compiler ... | Try changing:
for (std::unique_ptr<Foo> foo : foos)
to
for (std::unique_ptr<Foo>& foo : foos)
because as mentioned in the comments by @drescherjm and @dave, the compiler should be complaining about the copy constructor being deleted (aka copying a unique_ptr is not allowed). The loop tries to copy each vector element... |
70,276,314 | 70,276,792 | Erasing the first entry of a vector, after the maximum is reached | I have a vector in which i save coordinates.
I perform a series of calculations on each coordinate, thats why i have a limit for the vector size.
Right now i clear the vector, when the limit is reached.
I'm searching for a method, that let's me keep the previous values and only erases the very first value in the vector... | As suggested by @paddy, you can use std::deque, it is most performant way to keep N elements if you .push_back(...) new (last) element, and .pop_front() first element.
std::deque gives O(1) complexity for such operations, unlike std::vector which gives O(N) complexity.
Try it online!
#include <deque>
#include <iostream... |
70,276,777 | 70,277,008 | specialization of variadic template function for std::tuple as return type | I'm implementing a template function which parses a string and returns a tuple of objects, like
template <typename... Objects>
std::tuple<Objects...> convert2data(const std::string_view& input) {
return std::tuple<Objects...>{ internal::popNext<Objects>(input)... } ;
}
// usage
auto data = convert2data<int, double... | Something along these lines, perhaps:
template <typename Tuple, size_t... Is>
Tuple convert2dataHelper(const std::string_view& input,
std::index_sequence<Is...>) {
return std::make_tuple(
internal::popNext<std::tuple_element_t<Is, Tuple>>(input)...);
}
template <typename Tuple>
Tuple c... |
70,276,951 | 70,278,076 | Why doesn't automatic move work with function which return the value from rvalue reference input? | I already know automatic move is not woking with the function which return value from Rvalue Reference input. But why?
Below is example code which automatic move is not working with.
Widget makeWidget(Widget&& w) {
....
return w; // Compiler copies w. not move it.
}
If the function input is from copy by value, aut... | Relevant part of the C++17 standard [class.copy.elision/3]:
In the following copy-initialization contexts, a move operation might be used instead of a copy operation:
If the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in th... |
70,277,307 | 70,277,530 | 64-bit version of GCC not compiling 64-bit exe | I am beginner regarding gcc command line compilation.
I need a help regarding -m64 flag.
I installed gcc compiler using MinGW.
I checked for gcc version by following,
gcc -v command, which shows Target: x86_64-w64-mingw32.
So I assume, 64-bit version of gcc is installed.
Objective: I wrote a small program to check, if ... | As others have said in the comments, the size of long can be 8 or 4 bytes on a 64bit system. You can try sizeof(size_t) or sizeof(void*). Even this might not be reliable on every system (but should work for Windows, Linux, macOS).
|
70,277,378 | 70,277,617 | Use of const and & in functions C++ | I am trying to understand the useage of 'const' and '&' in the following function declaration. I know that the last 'const' means the function cannot change member variables in the class and that 'const std::string& message' means the variable passed to the function cannot be changed, but I don't understand the meaning... | So const Logger& is the return type of log. const means you will not be able to edit the return value at all. The return type Logger& means you'll get a reference to a Logger and not a copy of it.
|
70,277,561 | 70,277,658 | Will asigning a variable to another variable result in it using a copy constructor or being a reference? | I am a little confused with the copy constructor and references in c++.
Kat kat("hello kitty");
Kat newKat = kat;
Will Kat use its copy constructor or will newKat just become a reference to Kat.
Edit: sorry for the confusion, I mean for custom types.
| Kat kat("hello kitty");
Kat newKat = kat;
Will use the copy constructor
Kat kat("hello kitty");
Kat& newKat = kat;
Will create a reference
|
70,279,213 | 70,279,605 | C++ [Error] invalid conversion from 'int' to 'int (*)[2]' [-fpermissive] | I am a beginner and I keep getting an error when I am calling my function. I am trying to get the user to input a value for the array and then get it to display it in a table format. Also, I am trying to display a 3x3 matrix in the end.
void DMMatrix(int DM[2][2]){
int number;
cout << "Input 0's and 1's to the DM... | There are 3 problems in your program.
Mistake 1
You are calling the function DMMatrix incorrectly. The correct way to call DMMatrix would be:
DMMatrix(DM);//CORRECT WAY OF CALLING DMMatrix
Mistake 2
Your 2D array DM has 2 rows and 2 columns and you're accessing 3rd row and 3rd column of the array DM. But since the 3rd... |
70,280,141 | 70,280,294 | How to figure out the length of the result of `fmt::format` without running it? | While answering this question about printing a 2D array of strings into a table, I realized:
I haven't found a better way to determine the length of the result of a fmt::format call that to actually format into a string and check the length of that string.
Is that by design, or is there a more efficient way to go about... | Straight from the API documentation:
template<typename ...T>
auto fmt::formatted_size(format_string<T...> fmt, T&&... args) -> size_t
Returns the number of chars in the output of format(fmt, args...).
|
70,280,595 | 70,280,779 | How to bind numbers together into an integer without addition? | For example:
If I end up with multiple digits and all of those numbers are generated randomly (1-9) up to 7 digits total and I want them all to end up as a whole integer, how do I go by doing this?
Here is something I have tried:
static void generate_key(std::map<std::string, int>& key, std::string c_user)
{
unsign... | If you want to generate a 7 digit number where all of the digits are unique, then you can store the valid digits in a vector and then shuffle that vector and take the first 7 elements as the digit to make the number with. That could be done like:
std::vector<char> digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',... |
70,280,815 | 70,280,890 | What is calculated earlier in vector element assignment | If i have that line of code:
vec[f1(x, y)] = f2(a, b);
What would compiler run first: f1(x, y) or f2(a, b)?
| f2(a, b) is computed first, per [expr.ass#1]1 (emphasis is mine):
[...] In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.
The right operand is sequenced before the left operand. [...]
Note 1: that this i... |
70,280,839 | 70,298,657 | Getting a signed angle value | I'm having an issue with finding an angle between two vectors. I have this code (pic below) in blueprints, which uses dot product in order to find cos of the angle between two vectors.
However, it seems that this method does not give me full information - I still cannot determine if the object, which position I am tra... | Dot product will only give you the cosine of the angle formed by the two vectors. It is positive of they are facing the same direction, negative for opposite directions and 0 if they are perpendicular.
Simply check the "RightDirection" to get the sign that corresponds to the original dot product.
By doing this, you wil... |
70,281,216 | 70,281,906 | IEntity* wLocalEntity pointer example code snipet | what does this C++ code snippet do?
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
I'm not sure how it's related to a template creation. Can someone explain to me what this code does?
Thank you.
| Here's the code.
IEntity* wLocalEntity= const_cast<IEntity*>(BaseSimSystem::getEntityRef());
if(wLocalEntity!=0){
mEntitySpeed=wLocalEntity->getSpeed();
}
If you actually get asked about this code, the first thing I'd do is complain about the if-clause. that 0 should be nullptr as so:
if (wLocalEntity != nullptr) ... |
70,281,393 | 70,281,449 | How to store an instance of class in a vector? | I have made a class for a student with course and grade, the program keeps asking for a new student until the name given is stop. To store these instances I want to use a vector, but I didn't find any other way to store them than creating an array for the instances first and then pushing them back into the vector.
Is i... | Instead of creating an array then pushing back, simply keep one instance around and reassign it:
Student student;
vector<Student> students;
cout << "Name?" << endl;
getline(cin,student.name);
while((student.name) != "stop")
{
student.addcoursegrade();
// this line copies the student in the vector
students... |
70,281,420 | 70,283,383 | QRegExp a filename but its not matching | I'm trying to parse date time from a PNG file but can't quite get it with QRegExp
this_png_20211208_1916.png
QDateTime Product::GetObstime()
{
QDateTime obstime;
QString filename = FLAGS_file_name.c_str();
QString year, month, day, hour, minute, second;
QRegExp regexp = QRegExp("^.*\\w+_... | You have the following errors in your code:
month = dt_bits.at(1).mid(5, 2); should be month = dt_bits.at(1).mid(4, 2); because the index is 0-based, not 1-based
day = dt_bits.at(1).mid(8, 2); should be day = dt_bits.at(1).mid(6, 2);
minute = dt_bits.at(2).mid(3, 2); should be minute = dt_bits.at(2).mid(2, 2);
second ... |
70,281,499 | 70,281,593 | how to use emplace_back to insert a new element into a vector of vector? | I'm confused by the syntax of some C++ concepts.
Let's say I have a vector of vector:
vector<vector<int>> data;
I can use push_back() to insert a new element:
data.push_back({1, 1});
In this way, I list initialized a new element, then a copy of this element is pushed to data?
I can also do it in this way:
vector<int>... |
I can use push_back to insert a new element: data.push_back({1, 1}); In this way, I list initialized a new element, then a copy of this element is pushed to data?
exactly.
data.emplace(1, 1);
vector<Type>::emplace_back forwards its arguments to the constructor of Type. Now, std::vector<int> has a constructor that t... |
70,281,683 | 70,281,937 | Inherit from boost::matrix | I would like to inherit from boost::matrix to enrich with some methods. I started with this :
#include <boost/numeric/ublas/matrix.hpp>
using namespace boost::numeric::ublas;
class MyMatrix : public matrix<double>
{
public:
MyMatrix() : matrix<double>(0, 0) {}
MyMatrix(int size1, int size2) : matrix<double>(... | You don't need any of your additions to make this work:
MyMatrix matA(3, 3);
MyMatrix matB(3, 3);
MyMatrix matC(matA);
MyMatrix matD(matA * 2);
MyMatrix matE(matA + matB);
You only need to bring the boost::numeric::ublas::matrix<double> constructors and assignment operators into your derived class:
#include <boost/nu... |
70,281,975 | 70,282,519 | Steal the 3 least significant bits from a double? | I am working on a programming language and in short I need to steal the 3 least significant bits from a double, when working with an integer I can do the following
long long int make(long long int x)
{
return x << 3;
}
long long int take(long long int x)
{
return x >> 3;
}
However when doing that to doubles (... | Since type punning isn't allowed in C++, here's a version copying the double to a unsigned char array and clears the 3 least significant bits in it and then copies it back into the double:
#include <bit>
#include <cstring>
#include <limits>
double take(double x) {
static_assert(std::endian::native == std::endian::... |
70,282,341 | 70,282,592 | How do I read in a string and transfer to an array? | In this c++ code, I am taking a string from std::cin and transferring each char item into a char array.
int length; // length of the string
cin >> length;
char charList[length]; // list of the characters
string sequence; // string sequence
cin >> sequence;
for (int i = 0; i < length; i++) {
charList[i] = sequence[... | First of all, to answer your doubt about the type: sequence[i] is of type char.
Next, concerning your implementation: to start with, as many people have suggested in the comments, I recommend not getting the length of the string separately from the string itself, because the length of the input string may be different ... |
70,282,443 | 70,283,169 | How can one construct an object from a parameter pack in a C++ template? | Given the following, how can I correctly construct an object of an unknown type from a parameter pack?
template < typename... Types >
auto foo( Types&&... types ) {
auto result = Types{ }; // How should this be done?
// Do stuff with result
return result;
}
I expect the template function to only be called... | Since all the types in the parameter pack are the same, you can first use the comma operator to expand the parameter pack, then use decltype to get the type of the last operand.
template<typename... Types>
auto foo(Types&&... types) {
auto result = decltype((Types{}, ...)){ };
// Do stuff with result
return resul... |
70,282,477 | 70,316,577 | Partially updating D3D11 constant buffer | In my spare time, I am working on a 3D engine using D3D11. To get the 3D effect, I use the typical model view projection matrix multiplication in my HLSL shaders. These matrices are uploaded to a d3d11 constant buffer. The projection matrix only changes when the viewport is resized but the model and view matrix can cha... | You have several options to manage those.
The simplest ones is to create one constant buffer per update rate (so you would have one buffer for world matrices, which changes per object, one for view which would update once per frame, and one for projection which updates very sporadically.
That said, I never found the fa... |
70,282,521 | 70,283,786 | Error decomposing gcc command into separate compile and link steps | I am getting a linker error building a simple project using scons. The example commands show integrated compiling and linking of program binaries, which scons does not do (though I probably could force it to, I'd rather not if possible).
This command works fine:
gcc -o main.exe main.cpp C:\raylib\raylib\src\raylib.rc.d... | I would try to get gcc's library search path:
]$ gcc -x cpp-output -E -v /dev/null 2>&1 | grep LIBRARY_PATH | sed 's/:/\n/g'
LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/
/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/
/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/
/lib/x86_64-linux-gnu/
/lib/../lib/
/u... |
70,282,552 | 70,283,249 | How to erase certain element of a vector of pointers | Hello i'm curently coding a fonction that erase element from a vector of pointer(to class object), but i cant quite make it work.
I get this error
error: no matching function for call to ‘std::vector<biblio::Reference*>::erase(biblio::Reference*&)’
std::vector<Reference*> m_vReferences; //Reference is a class
... | Don't use auto-range loops when you want to delete the element from the container.
I would use std::remove_if as it is available in standard library.
m_vReferences.erase(std::remove_if(m_vReferences.begin(),m_vReferences.end(),[p_id](Reference* x){
return x->reqId() == p_id;
}),m_vReferences.end());
or you may loop... |
70,282,687 | 70,282,772 | How to reconstruct a 4 byte uint8 array into a uint32 integer | I have a web app (javascript) that needs to send a arduino(ESP32) a 12bit value (0x7DF).
I have a websocket connection that only accepts a Uint8_t payload, so I split the value into 4 bytes (Uint8_t).
I can send the array to the arduino, but how do i reconstruct it back into a 32bit value?
This is the code i am using t... | On Arduino, ints are 16 bit, so id[0] << 24 (which promotes id[0] from uint8_t to int) is undefined (and wouldn't be able to hold the value anyways, making it always 0).
You need some casts beforehand:
return (static_cast<uint32_t>(id[0]) << 24)
| (static_cast<uint32_t>(id[1]) << 16)
| (static_cast<uint32_t>(... |
70,283,216 | 70,283,451 | Correct way to use WideCharToMultiByte when using unicode | I asked a question recently about using unicode and the problems that arose here:
argument of type "WCHAR *" is incompatible with parameter of type "LPCSTR" in c++
In solving one problem, I encountered another one that has taken me now a literal rabbit hole of differences between ansi and unicode. I have learnt a lot b... | Most likely your problem is that you're compiling with UNICODE defined. In this case PROCESSENTRY32 will actually be PROCESSENTRY32W.
But you're calling the ASCII-Version of Process32First instead of the unicode-version Process32FirstW.
Most of the winapi functions that accept both ascii & unicode arguments have 2 sepa... |
70,283,504 | 70,283,574 | Program doesn't run functions repeatedly (C++) | I am making an autoclicker. The "ClickLoop" function I found on another SO post works, but I am trying to add a key to toggle the autoclicker on and off.
This is my code so far:
#include <windows.h>
#include <iostream>
#include <chrono>
#include <thread>
#include <random>
bool on = false;
void tick () {
if(GetKey... | void tick () {
...
tick();
}
This is an endless recursion loop. Once main() calls tick(), the program is stuck in this loop and never reaches ClickLoop().
void WINAPI ClickLoop(int delay) {
...
ClickLoop(delay);
}
This is also an endless recursion loop.
You need to get rid of these recursive loops.
A... |
70,284,279 | 70,284,362 | Overriding a virtual function but not a pure virtual function? | I'm attempting to derive a class C from two classes, A and B; after reading this answer, I attempted to write using B::<function> in order to override a pure virtual function in A with the implementation in B.
However, the approach in that answer does not work for pure virtual functions; in that case, I found that I ne... |
I attempted to write using B::<function> in order to override a pure
virtual function in A with the implementation in B.
You misunderstood. It is not possible to override a function this way. All that using B::h; does: it introduces B::h into the scope of struct C, so that X.h(); in main() becomes equivalent to X.B::... |
70,284,505 | 70,284,611 | Is possible to create Java generics class depending on int value? | We can create a generic class in Java like this
public class MyClass<T> {
...
but, now that i'm translating a (very large) C++ code to Java, i need a class to be different from other depending on its size, like in this c++ code:
template<size_t size> class MyClass {
...
so every class is a different type, there stati... | No, you can't use values as parameters instead of a generic type in Java. You should probably just take the size as a parameter in the constructor and implement safety checks taking the size into account.
|
70,285,043 | 70,286,649 | the n should be inclusive or exclusive when using std::nth_element? | Hi I have a question on the usage of std::nth_element.
If I want to obtain the k-th largest element from a vector, should it inclusive or exclusive?
int k = 3;
vector<int> nums{1,2,3,4,5,6,7};
std::nth_element(nums.begin(), nums.begin()+k-1, nums.end(), [](int& a, int& b){return a > b;});
int result = nums[k-1]
or
int... | This is the type of question that is best to figure out and understand by playing around with a bunch of examples on your own.
However, I'll try to explain why you're getting the same answer in both of your examples. As explained in cppreference, std::nth_element is a partial sorting algorithm. It only guarantees that,... |
70,285,762 | 70,286,123 | Perform Operations like add, sub, mul, div, mod on 2 integers with their bytes | I have got the bytes of 2 integers (say 32 bit int) now is it possible to add them using the bytes?
I have like
char b1[4], b2[4];
int a= 2311;
int b= 233134;
memcpy(b1, &a, 4);
memcpy(b2, &b, 4);
My question is is there any algorithm to add, mul, sub the numbers from bytes and the number of bytes of number is not fix... | Your question is in its heart not about the implementation in C++, but about algorithms to do simple arithmetic.
For all the operation you mention, remember how you did it in primary school. Apply that algorithms, replacing single decimal digits by bytes. The principle stays the same. It's all mathematics.
You need to ... |
70,285,888 | 70,287,213 | SDL2: Sometimes make segement fault while Rendering and Event Polling in the different thread | So in my project I make a Event thread to catch the sdl event and may be pass it to the main thread to rander. But sometimes I get the Segementfault.
this is my test code.
#include "SDL2/SDL.h"
#include <SDL2/SDL_timer.h>
#include <iostream>
#include <thread>
using namespace std;
int main() {
SDL_Init(SDL_INIT_E... | Fundamentally, you should try to call SDL from a single thread. Even if you decide you need to multithread your program, you should do work in other threads and then synchronize that work to the main thread, which should use SDL to render / event-handle / etc.
Your program may be segfaulting because you're attempting t... |
70,285,938 | 70,286,275 | Unknown string from Dynamic Loaded Golang to CPP | So, I tried to run my go code on C++ project with dynamic loading. It's working great, except there is some unwanted string on returned value. As I explained down, I got some information from Go that unwanted.
My go code:
package main
import "C"
func main() {}
//export GetTestString
func GetTestString() string {
... | When passing strings via pointer to C you need either use length (n) in GoString to fetch right number of characters as string at p is not \0 terminated. Or you can return *C.char instead of string and use C.CString() to allocate copy on C heap (which you then are responsible for freeing after use). See Cgo documentati... |
70,285,955 | 70,291,536 | Advantages of aggregate classes over regular classes | In my use case I needed to initialize a class variable using an initializer list. I learnt that an aggregate class is a class that just has user defined data members in it.
The advantage of aggregate is that we can use initializer list like this
struct fileJobPair {
int file;
int job;
};
fileJobPair ob... |
What are the advantages <...> of aggregates
Unlike "usual" classes, aggregate types:
have pre-defined "constructor" (your example)
need no tuple-like interface boilerplate for structured bindings:
struct { int field1, field2; } aggregate;
auto&& [_1, _2] = aggregate;
have designated initializers:
Aggregate{.some... |
70,286,284 | 70,314,730 | clang-format: how to change behavior of line break | Using clang-format, I want the result somewhat like this:
value = new MyClass(variable1, variable2, mystring + "test",
another_variable);
But I don't want the result below:
value =
new MyClass(variable1, variable2, mystring + "test", another_variable);
How can I do?
| You could try the following parameters in your .clang-format file (How do I specify a clang-format file?):
AlignOperands: true
PenaltyBreakAssignment: 21
PenaltyBreakBeforeFirstCallParameter: 1
AlignOperands: you want to align the operands after a break line (as you align another_variable below)
PenaltyBreakAssignmen... |
70,286,610 | 70,286,971 | invalid initializer for structured binding declaration | How should I fix this error? Should I use a const std::tuple<int, int, char> instead?
constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36, 168, ' ' };
This gives errors like:
error: structured binding declaration cannot be 'constexpr'
434 | constexpr auto [ Y_AxisLen, X_AxisLen, fillCharacter ] { 36,... |
structure binding isn't allowed to be constexpr now.
structure binding can only be applied to the following cases.
array
tuple-like
structure data members
ref: https://en.cppreference.com/w/cpp/language/structured_binding
If you must use structure binding, use std::make_tuple
const auto [ Y_AxisLen, X_AxisLen, fil... |
70,286,980 | 70,287,110 | Iterate through a vector of shared_ptr | I have two classes (sheep and wolf) derivating from one (animal).
I created a vector of shared pointer like that:
std::vector<std::shared_ptr<animal>> animals;
for (int i = 0; i < n_sheep; i++) {
auto my_sheep = std::make_shared<sheep>();
animals.push_back(std::move(my_sheep));
}
for (int i = 0; i < n_wol... | "The best" depends on several things. For example, who controls the definition of the class Animal?
I really like to do something akin to:
class Animal
{
public:
virtual std::string what() = 0;
};
class Wolf : public Animal
{
public:
virtual std::string what() { return "wolf"; }
};
class Sheep : public Animal
{
pu... |
70,287,188 | 70,288,201 | Linking together dlls built with different gcc, error : file not recognized: File format not recognized | I am trying to build with GCC 4.6.1 a project in C++0x that links with a C++17 dll generated with GCC 11.2.0.
I am using Netbeans IDE 7.4 (I think it doesn't matter).
So, the compiling (with GCC 4.6.1) output is the following:
libdriver17.dll: file not recognized: File format not recognized. libdriver17.dll is indeed m... | I was compiling driver17 in 64bits, and main_cpp0x.cpp in 32bits.
|
70,287,257 | 70,288,129 | What are the adavantages and use cases of CRTP compiletime polymorphism? | I see we could introduce some sort of compiletime polymorphism using CRTP, however I wonder how this can be better than good old virtual functions. In the end we have to call static_cast<const T*>(this)->implementation(); which is one level of indirection exactly like a vtable does.
How are they different? Are there an... | The reason is performance.
static_cast<const T*>(this)->implementation(); is resolved at compile-time to the address of the corresponding T::implementation() overload:
CALL <fixed-address>
A virtual member call on the other hand, is generally resolved at run-time using an indirect call via an offset in a vtable. I... |
70,287,259 | 70,287,537 | How Precedence of Relational Operator handled in C++ | According to precedence rules <, >, <=, >= has precedence over !=, ==
I am so confused that how the following statement will be executed
int a=3, b=3;
cout<< (a != b || a <= b);
I know short circuit evaluation and according to precedence rules I guess that compiler will execute a <= b first as it has precedence over !... | Precedence of operators is only relevant to how expressions are bound, not to how they're executed. Execution order is dependent on the "happens-before" relationship and otherwise subject to arbitrary reordering by the compiler.
Relative precedence of two operators also only matters if they are directly adjacent. In a ... |
70,287,587 | 70,292,047 | Type definitions dependent on template parameters | I am currently working with template classes in C++. In these classes, I am using types that are again dependent on the template parameters. In order to not type the parameters all the time, I did something along the lines of
template<typename T>
class A
{
using someName = someClass<T>;
}
There are some more examp... | Create a struct which defines each common alias:
template<typename T> struct Aliases {
using value_type = T;
using reference = T&;
};
...and inherit from it:
template<typename T> class Foo: public Aliases<T> {};
template<typename T> class Bar: public Aliases<T> {};
template<typename T> class Baz: public Aliase... |
70,287,726 | 70,292,336 | QStateMachine is not emitting started() signal in release mode | I am using QStateMachine framework for a device controller class. It works fine in debug mode. But, in the release mode QStateMachine::started() signal is not being emitted. A simple widget project for the problem (form is empty) is below.
Qt Version 5.14.1
Compiler : MSVC 2017, MinGW (both are 64-bit and results are s... | In release mode, it is likely that the connection is not made because you wrapped it inside a Q_ASSERT macro.
See Q_ASSERT release build semantics for more informations.
|
70,287,876 | 70,292,244 | Why are member variables modifyable even after object is destroyed? | If the shared_ptr is destroyed, what happens to "this" if captured in a lambda to be run on a thread? Shouldn't it have thrown an exception in the below case since the object Test was destroyed before the thread could finish running.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
using na... | In practice, The hardware that executes your program knows nothing about objects or member variables or references or pointers. What was a variable in your C++ source code becomes a virtual memory location in the executable, and what was a reference or a pointer becomes a virtual memory address. When an object is "dest... |
70,288,446 | 70,289,317 | Keep boost asio io_service | I usually keep one io_service object for the whole application and use a number of threads to call run on them. Creating sockets or timers use the io_service by reference. What happens when all threads finish at application exit and there is, lets say a shutdown or cancel operation called on a tcp socket. The io_servic... | There is never a copy of io_service (or the more recent io_context that replaces the deprecated io_service). That's because it's not copyable.
If you don't maintain the lifetime while async operations have not completed, the behaviour is indeed undefined. However, it's not too hard to make sure no async operations/comp... |
70,289,221 | 70,299,077 | Ignore 'long' specifier for custom type in c++ | I have a type and a template class
#ifdef USE_QUAD
using hybrid = __float128;
#else
using hybrid = double;
#endif
template<typename T>
struct Time {
int day;
long T dayFraction; // This is an example, I need both in here, T and long T;
};
And to make things complicated: A nesting class
template<typename T>
st... | You can't actually write long T and expect that to be interpreted as long double when T is double. If it works for you, that's a non-portable quirk of your compiler.
If you want "regular" and "long" versions of a type, different for double but the same for float128, one way to do it would be to define a template like t... |
70,289,544 | 70,290,080 | Confusion about _Lock_policy in libstdc++ | I'm reading the implements of std::shared_ptr of libstdc++, and I noticed that libstdc++ has three locking policies: _S_single, _S_mutex, and _S_atomic (see here), and the lock policy would affect the specialization of class _Sp_counted_base (_M_add_ref and _M_release)
Below is the code snippet:
_M_release_last_use() n... | Some of this is answered in the documentation and at the URL shown in the code you quoted.
When using the _S_mutex locking policy, the __exchange_and_add_dispatch function may only guarantee atomicity, but may not guarantee that it is fully fenced, am I right?
Yes.
and because of 1, is the purpose of '__atomic_th... |
70,290,311 | 70,290,339 | What is the use case for c++20 template lambdas? | We had the generic lambdas before C++20 and could write something like this.
auto l = [](auto a, auto b)
{
return a+b;
};
And then C++20 introduced template lambdas where we can write something like this
auto l = []<typename T>(T a, T b)
{
return a+b;
};
Or this
auto l = []<typename... | auto l = [](auto a, auto b)
This lambda can be called with two completely different parameters. a can be an int, and b can be a std::string.
auto l = []<typename T>(T a, T b)
This lambda must be called with two parameters that have the same type. T, like in a regular template, can only be a single, specific, type.
Th... |
70,290,457 | 70,290,487 | Accessing elements in a vector of tuples C++ | I have the following body of code.
#include <iostream>
#include <vector>
#include <tuple>
int main() {
std::vector<std::tuple<int, int>> edges(4,{1,2});
for (auto i = std::begin (edges); i != std::end (edges); ++i) {
std::cout << std::get<0>(i) << " "<< std::get<1>(i)<< " ";
}
}
In my eyes... | I would change to a range-based for loop
for (auto const& edge : edges) {
std::cout << std::get<0>(edge) << " "<< std::get<1>(edge)<< " ";
}
Otherwise to access each edge, you need to dereference your iterator using * to get the actual tuple itself
for (auto iter = std::begin(edges); iter != std::end(edges); ++ite... |
70,290,957 | 70,291,237 | std::copy doesn't copy vector in C++ | To find all sequences of fixed length which contain only 0 and 1 I use this code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void print_array(vector<string> arr) {
cout << '[';
int n = arr.size();
for (size_t i = 0; i < n; i++) {
cout << arr[i];
if ... | You are writing to temp.end() and result.end(). These iterators represent "one past the end", and therefore writing to these iterators is Undefined Behavior.
You seem to be looking for std::back_inserter. This will create an iterator that will insert a new element to your container when it is written through.
std::co... |
70,291,281 | 73,419,766 | GetPixel Function Doesn't Work in Qt C++ LNK2019 undefined reference to __imp_GetPixel | I tried to use some win32 function in Qt Application but all of them work except GetPixel function I tried to use MSVC 2019 compiler MSVC Compiler has problems with all the functions (error LNK2019) but when I added win32:LIBS += -luser32 to the .pro file all of them work except GetPixel function,
here is my code:
#inc... | add win32:LIBS += -lGdi32 to .pro file
|
70,291,690 | 70,292,255 | Why QPainterPath::contains() is not thread-safe, despite being const? | While I understand that QT states that only specifically stated classes are thread-safe, I'd like to understand why a "const" marked method - QPainterPath::contains() - breaks when it is being called in a parallel loop without any concurrent write operation:
#include <QPainterPath>
#include <omp.h>
#include <iostream>
... | The answer is in the first line of code you linked to:
if (isEmpty() || !controlPointRect().contains(pt))
controlPointRect() has the following:
if (d->dirtyControlBounds)
computeControlPointRect();
and computeControlPointRect() does the following:
d->dirtyControlBounds = false;
...
d->controlBounds = QRectF(minx,... |
70,291,939 | 70,292,379 | C++ new keyword in inheritance with different types | I recently started learning OOP. Forgive me if this is a noob question. My question is,
I have thought new keyword is used with only same datatypes such as:
char* p = new char; // OR
int* myArr = new int[i] //etc...
While studying inheritance and virtual functions I've come across this:
#include <iostream>
using names... | Note that in your case, the class Human is accessible class of Asian and
$11.2/5 states -
If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class (4.10, 4.11). [ Note: it follows that members and friends of a class X can implicitly convert an X* to a point... |
70,292,760 | 70,293,090 | C++ vector insert implementation crash | I'm trying to reproduce the behavior of vector and a weird crash occurs when I try to use vector::insert(iterator, size_type, const T &), my code looks like this:
iterator insert(iterator pos, size_type count, const T &value) {
return _M_insert_size(pos, count, value);
}
//with
iterator _M_insert_size(iterat... | if (_capacity < size) reserve(size); // reserve if larger than capacity
// here `end()` is still using old size
std::copy(pos, end(), pos + count); // move [pos;end()[ to (pos + count)
If you're debugging this, you should know whether you called reserve() here, right? Because you're single-stepping throug... |
70,292,795 | 70,294,331 | How to convert variant to string in C++ | I'm new in C++, and I wanted to know how to convert a variant to string:
variant<string, int, float> value;
if (!value.empty()) {
// do something
}
| Well, you will need custom code for the different cases...
The following function would do as you want:
string stringify(variant<string, int, float> const& value) {
if(int const* pval = std::get_if<int>(&value))
return to_string(*pval);
if(float const* pval = std::get_if<float>(&value))
return... |
70,292,905 | 70,294,473 | VS code - Hide build/echo task for cpp | I'm using VS Code for running c++ code.
Whenever I Ctrl + Shift + B to build my .cpp file, an 'echo' tab pops up, which makes the entire bottom panel appear and then I am asked to "Terminal will be reused by tasks, press any key to close it."
I don't want the tab or the panel to pop up at all and want the entire build ... | This can be configured using "presentation": {...}. Following worked for me:
{
"version": "2.0.0",
"tasks": [
{
"label": "Test task",
"type": "shell",
"command": "echo Hello world",
"presentation": {
"echo": true,
"reveal": ... |
70,293,264 | 70,293,591 | Would it be possible to run the same C++ code simultaneously? | Say I compile some code and make it run. It will take 10 minutes to finish.
In the meantime, if I change some parameters in the code and compile it again using a separate terminal window and run it too (so there's now two programs running simultaneously using the same code), does the second run affect the first running... | There are three possible scenarios:
On Windows, an executable file will get locked for writing and removal while it is being executed so the build will just fail.
On Linux, an executable file is not necessary protected from modification or removal while it is being executed.
2.1. If a file is deleted from the file ... |
70,293,337 | 70,293,467 | How to #include <whatever.h> installed with apt in Ubuntu | I have just installed hidapi in my Ubuntu 20.04 following the instructions, i.e. by doing
sudo apt install libhidapi-dev
I wrote my program in the file mwe.cpp which contains only this line:
#include <hidapi.h>
and now I want to compile it with
g++ -o mwe.o mwe.cpp
but I get
mwe.cpp:1:10: fatal error: hidapi.h: No s... | On Ubuntu based systems, the system package libhidapi-dev installs the include files to /usr/include/hidapi, so either include this (-I/usr/include/hidapi) in your command line or #include <hidapi/hidapi.h>
|
70,293,605 | 70,294,188 | Debugging the use of std::string in a thread pool C++ | I'm in the process of trying to figure out multithreading - I'm pretty new to it. I'm using a thread_pool type that I found here. For sufficiently large N, the following code segfaults. Could you guys help me understand why and how to fix?
#include "thread_pool.hpp"
#include <thread>
#include <iostream>
static std::m... | Destructors are called in the order opposite to variable declaration order. i.e. v will be destructed earlier than pool, therefore at the moment when some threads from pool will call to printString(), the argument string will not be a valid object, because v and its content are already destroyed. To resolve this, I'd r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.