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 |
|---|---|---|---|---|
72,306,706 | 72,307,118 | How to use Intel C/C++ Classic Compiler in VSCode debugger? | I'm setting up a C environment on a Mac to implement some numerical codes for my phd.
I'm using the Intel C/C++ Classic compiler instead of the default clang.
So far, I manage to generate some debugging information evoking a command like icc -std=c17 -o code -g code.c
When I call the Run and Debug option in VSCode it s... | I think you are mixing compiling and debugging up, according to the documentation, choosing C/C++: gcc build and debug active file from the list of detected compilers on your system is just helping you to generate some configuration like this:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"lab... |
72,306,739 | 72,306,854 | bit manipulation to specific subset | Considering the following code snippet.
for (int state = 1; state < 1 << n; state ++ )
if (state & 1)
for (int t = state; t; t &= t - 1)
The first for-loop is to enumerate all subsets of n elements, but what subset does the t represent.
| for (int t = state; t; t &= t - 1)
This loop is removing the least-significant 1 bits from t, one by one.
So an initial value of state like 63 (binary 111111) would go to 62 (111110), then 60, (111100), 56 (111000), 48 (110000), 32, (100000), and finally 0.
|
72,306,753 | 72,307,070 | g++ cannot change include path with -I | I'm on kubuntu using g++ 7.5.0 / GNU make for C++. My file structure:
bin
| .o files
header
|archiver.h
source
|main.cpp
|archiver.cpp
makefile
I want my source files to be able to detect header files without having to do #include "../header/archiver.h". I've tried using:
g++ -I/header
but this does not work. I ge... | The command
g++ -I<header-dir>
doesn't change any default settings for the g++ include search paths with subsequent calls, as you seem to assume.
You'll need to pass that compiler flag for each individual c++ call, which are issued by make according the rules defined in your makefile.
The latter is what you need to ad... |
72,307,566 | 72,308,036 | should a function return the pointer of a newly created object, or a unique_ptr of that object? | I remember watching Herb Sutter on conference talks, some years ago, trying to make a guideline along these lines:
if a function creates a new object on the heap, then it should always return it as a unique_ptr.
The idea was that it was safer, and intention-revealing.
To my surprise, this guideline seems to be missin... | It is covered in the C++ Core guidelines under I11:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i11-never-transfer-ownership-by-a-raw-pointer-t-or-reference-t
What you should be doing is:
MyObject create(Params p) {
return MyObject(p);
}
Only when you absolutely need reference mechanics, i.e. when c... |
72,307,679 | 72,308,749 | Creating Your Own Matrix Class | I am creating my own Matrix class. I wrote a copy constructor, but it works correctly only for primitive classes (namely, memory allocation for data). How can the constructor be rewritten (it is possible to overload the new operator) so that it works correctly not only for primitive data types, but also for complex str... | You can simply make the memory management automatic:
#include <cstddef>
template <typename T, std::size_t rows, std::size_t cols>
class Matrix {
public:
Matrix() { }
T * operator[](std::size_t x) {
return data[x];
}
private:
T data[rows][cols]{};
};
But if you must use dynamic memory allocatio... |
72,307,874 | 72,308,048 | Why disabling copy elision for std::atomic doesn't work using C++17? | For std::atomic the copy constructor is deleted, and this should only compile with C++17 and higher due to copy elision:
std::atomic<int> t_int = 1;
I expected that it does not compile using -fno-elide-constructors flag, but it still compiles:
https://godbolt.org/z/nMvG5vTrK
Why is this?
| C++17 doesn't simply say that the previously optional return value optimizations are now mandatory. The actual description of the language changed so that there is no creation of a temporary object anymore in the first place.
So, since C++17, there is no constructor call that could be elided anymore. Hence it makes sen... |
72,308,295 | 72,309,369 | save IR signals(like 89KZ3H) into a variable(like string) | I want to start an IR remote controlled car, but since I'm not very good at programming with c++ in Visual studio code I wanted to know how to save a signal that is transmitted by the remote control to my arduino and save it into a string variable.
I copied this code from internet to get the IR signals:
#include <Ardui... | String myString = String(results.value);
|
72,309,122 | 72,309,432 | Is it okay to pass a temporary regex object to regex_match? | Most examples using boost::regex_match construct the boost::regex object before calling match; e.g.
boost::regex pattern("(...)");
boost::smatch match;
if (boost::regex_match(text, match, pattern)) {
// use the match object here
}
(See https://github.com/boostorg/regex/tree/develop/example/snippets for other examp... | Firstly, from a design perspective it wouldn't make sense to store a reference to boost::regex in boost::smatch.
Having a look at the implementation confirms that:
template <class BidiIterator, class Allocator>
class match_results
{
// ...
vector_type m_subs; // subexpressions
... |
72,309,221 | 72,311,285 | This assignment is designed to explore linked lists so you will implement a singly linked-list to hold a collection of bids loaded from a CSV file | I need help please It keeps giving me the same number and not a different one.
Bid LinkedList::Search(string bidId) {
// FIXME (6): Implement search logic
// special case if matching node is the head
// make head point to the next node in the list
//decrease size count
//return
// ... | Just remove everything with a holder. And at the end throw an exception when nothing was found. Alternatively return std::optional<Bid>.
|
72,309,935 | 72,314,832 | Zero sized array in struct managed by shared pointer | Consider the following structure:
struct S
{
int a;
int b;
double arr[0];
} __attribute__((packed));
As you can see, this structure is packed and has Zero sized array at the end.
I'd like to send this as binary data over the network (assume I took care of endianity).
In C/C++ I could just use malloc to all... |
I'd like this memory to be handled by std::shared_ptr.
Is there a straight forward way of doing so without special hacks?
Sure, there is:
shared_ptr<S> make_buffer(size_t s)
{
auto buffer = malloc(s); // allocate as usual
auto release = [](void* p) { free(p); }; // a deleter
shared_p... |
72,310,048 | 72,310,359 | std::filesystem::last_write_time to FILETIME | I am attempting to send over the FILETIME of a file to my server, which is written in C#. From there, I can use the function DateTime.FromFileTime() to parse the file's time. I am aware there is a Win32 API called GetFileTime(), but in the interest of saving lines of code, I was wondering if it was possible to use std:... | You can convert the last_write_time() value to std::time_t via std::chrono::file_clock::to_sys() and std::chrono::system_clock::to_time_t(), and then convert time_t to FILETIME using simple arithmetic.
For example:
#include <windows.h>
#include <filesystem>
#include <chrono>
void stdFileTimeType_to_FILETIME(const std:... |
72,310,464 | 72,310,747 | Is there a more idiomatic way to specialise behaviour using flags passed via template? | Apologises for the ambiguous title.
Here is my code:
struct LowHigh
{
};
struct HighLow
{
};
template < class LookupScheme>
struct ladder_base
{
using value_type = price_depth;
using ladder_type = std::vector< value_type >;
template < class T >
struct lookup;
template <>
struct lookup<... | These algorithms take a comparison object as their last parameter - so you can use that to your advantage.
template < class Compare >
struct ladder_base
{
using value_type = price_depth;
using ladder_type = std::vector< value_type >;
void
insert(value_type v)
{
auto iter = std::upper... |
72,310,617 | 72,310,756 | template argument deduction for a allocating Matrix | I have this Matrix class that allocates the data on the heap and a helper class M that is a Matrix with the data as C-style array, no allocation. Template argument deduction works for the helper class automatically. But not for the Matrix class.
I can construct a Matrix from that with template argument deduction:
M m{{... | You can get rid of helper class M and have your Matrix template parameters automatically deduced by changing the type of your constructor parameters to (l- and r-value references to) C-style arrays:
//Matrix(const M<T, rows, cols>& other) {
Matrix(const T (&other)[rows][cols]) {
// ... same implementation ...
}
//... |
72,311,314 | 72,311,361 | C++ variadic template: typeid of it, way to optimize | So, I learn variadic templates and usage of it. Now I made that code below. The question is does some other methode exist for getting type of "Params" without any arrays or inilialized_list?
template<class Type, class... Params>
void InsertInVector(std::vector<Type>& v, const Params&... params)
{
const auto variadi... | In C++17 and later, you can do something like this:
template<class Type, class... Params>
void InsertInVector(std::vector<Type>& v, const Params&... params) {
static_assert((std::is_convertible_v<Params, Type> && ...));
v.insert(v.end(), {params});
}
|
72,311,585 | 72,311,744 | Variables in Google Test Fixtures | Why TEST_F can access the member variable in a class without using any scopes? e.g.,
class ABC : public ::testing::Test
{
protected:
int a;
int b;
void SetUp()
{
a = 1;
b = 1;
}
virtual void TearDown()
{
}
};
TEST_F(ABC, Test123)
{
ASSERT_TRUE(a == ... | TEST_F is a macro which defines a new class publicly inheriting from the first argument (in this case, 'ABC'). So it has access to all public and protected members of the test fixture class.
You can inspect the source for this macro in the header file to get a better idea of what it's doing.
TEST_F macro, which if you ... |
72,311,819 | 72,315,649 | Doxygen generates a strange error for base class function about nonexisting function in the derived class | Here is the code:
namespace Test {
/// Base class
class Base
{
public:
/// Method foo
/// @param a ParamA
/// @param b ParamB
virtual void foo(char a, int b);
/// Method foo
/// @param a ParamA
/// @param b ParamB
/// @param c ParamC
virtual void foo(char a, int b, char c);
///... |
With the doxygen versions till doxygen 1.9.1 (inclusive) I was able to reproduce the problem.
The problem is gone with the versions 1.9.2 and higher.
The current doxygen version is 1.9.4 (5d15657a55555e6181a7830a5c723af75e7577e2)
The solution for this problem is to update your doxygen version to the current doxygen v... |
72,311,949 | 72,311,987 | Visual Studio keeps using wWinMain() as the entry point instead of the main() function I want it to | I started my Visual Studio project as a windows application, however I've come to realize that if I want to use GLFW then I'm supposed to open a GLFW window instead of a standard wWinMain window. I have a wWinMain function but since it kept running every time I ran the program instead of my int main() function with the... | Windows knows two types of program that are relevant to you: Console and graphical.
Console programs automatically get a console (and you can get their output in a command line, for example) and their entry point is main or wmain.
Graphical programs don't get a console automatically, which is what you want. They don't ... |
72,312,246 | 72,312,468 | C++ - Undefined reference to octomap::OcTree::OcTree(double)' | I'm trying to use the library octomap and have installed according to the instructions in their GitHub. However, when I try to build and run this simple code with VSCode build task (with g++) I get the error: undefined reference to `octomap::OcTree::OcTree(double)' and other undefined references to Octomap related cod... | your problem is the program wasn't linked with octomap library
use cmake and include some lines like:
find_package(octomap REQUIRED)
include_directories(${OCTOMAP_INCLUDE_DIRS})
target_link_libraries(${OCTOMAP_LIBRARIES})
or from command line with g++ <source files> -loctomap -loctomath
refer : http://wiki.ros.org/oc... |
72,313,352 | 72,313,480 | Timing a class function in C++ | A previous post, Timing in an elegant way in C, showed a neat method for profiling using a wrapper function. I am trying to use one of the profiler to profile my class functions.
#include <cmath>
#include <string>
#include <chrono>
#include <algorithm>
#include <iostream>
template<typename Duration = std::chrono::micr... | You can use std::bind to create a callable object for invoking a class method on a class object.
Then you can pass this callable to your profile function as you would pass any function/lambda.
Note that using std::bind supports also fixing one or more of the method parameters.
Using std::placeholders (as you can see be... |
72,313,410 | 72,321,334 | Why do I need multiple mutexes? | I am currently looking at a code example below (also can be found here).
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
std::mutex m_a, m_b, m_c;
int a, b, c = 1;
void update()
{
{ // Note: std::lock_guard or atomic<int> can be used instead
std::unique_lock<std::mutex> lk(m_a);
... | Assume you have more code, code that modifies only b and code that only reads only c.
Now both of those can run in parallel. If you only have one mutex protecting b and c as a pair then they would block each other.
Overall this looks like an example how to acquire multiple locks and other code that shows why multiple l... |
72,313,808 | 72,381,654 | cannot convert 'ListNode*' to 'ListNode**' C++ | #include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
void printList(ListNode *head) {
ListNode *curr = head;
whil... | Like Armin pointed out in the comments, you are referencing the array beyond the range.
if you replace
node = head[5];
with
node = head[4]; //this is the 5th element of the array.
you would probably get the output you were expecting.
|
72,314,094 | 72,315,521 | What is the Difference between accessing a Pointer whose value is Null and accessing what it points to? |
I've heard that accessing a pointer whose value is null is safe since you are not setting any data to it or from it, you are just accessing it.
But I also heard that accessing what it points to (when it's null) isn't safe, why is that?
If you are accessing to what it points to (when it's null) aren't you accessing n... | The sample code (as it's exposed by OP in this moment) got a bit confusing.
Thus, I would like to add some examples to the accepted answer what's allowed and what not:
#include <iostream>
int main()
{
int x = 0; // make some storage
int* px = &x; // px initalized with address of x -> OK.
int* pn = nullptr; /... |
72,314,253 | 72,314,789 | How COVERITY cov-build coverage mechanism works? | I am new to a c/c++ and I have recently came across coverity static analysis tool and at the build end I can see that it says number of files that got emitted and it will also have a percentage of files emitted.
I just want to know how it concluded that this is the percentage. Because if we can calculate the total fil... | When cov-build reports its final status, something like:
933 C/C++ compilation units (62%) are ready for analysis
(example taken from this random build-log.txt), it means that the Coverity compiler (cov-emit) successfully compiled 933 files. The percentage 62% means there was a larger number of compilation attempts (... |
72,314,747 | 72,315,075 | What can be done to prevent misleading assigment to returned value? | After many years of using C++ I realized a quirk in the syntax when using custom classes.
Despite being the correct language behavior it allows to create very misleading interfaces.
Example here:
class complex_arg {
double r_;
double phi_;
public:
std::complex<double> value() const {return r_*exp(phi_*std:... | Ordinarily we can call a member function on an object regardless of whether that object's value category is an lvalue or rvalue.
What can be done to the class definition to prevent this behavior?
Prior to modern C++ there was no way prevent this usage. But since C++11 we can ref-qualify a member function to do what y... |
72,314,918 | 72,315,205 | Does future in c++ corresponding to promise in javascript? | I am a c++ programmer and tried to study std::future and std::promise these days. When I randomly search some information about future/promise, I found some discussion about future/promise in javascript and promise in javascript has then function. In c++, even though std::future don't have then function now, but some p... |
Yes.
std::future<T> stands for a future result of T, i.e. the object will at some point in the future hold a T. std::promise<T> is an object promising to provide a T at some point in the future.
Which language got the naming right is debatable.
|
72,315,517 | 72,315,543 | How to write a function which returns complex in C++? | I am trying to do numerical calculations with C++. Here is the sample code
#include <complex>
using namespace std;
complex<double> complexDo(float a, float b){
return (a+b,a-b);
}
int main(){
cout << "complexDo="<<complexDo(3,2) <<'\n';
return 0;
}
The terminal will show after compiling
complexDo=(1,... | The expression (a+b,a-b) is equivalent to (a-b) because it's just a parenthesized use of the common comma expression.
To create an object you must use curly-braces {} as in
return {a+b,a-b};
|
72,316,273 | 72,316,459 | Call constructor inside a call to another constructor | Suppose I have classes A, B:
class A
{
int a;
public:
A(int a) : a(a) { }
};
class B
{
A a;
public:
B(A a) : a(a) { }
};
And I want to create an instance of B as:
int i = 1;
B b(A(i));
But when I actually try to use b, I get the problem described here. That is, b is not an instance of B, it's a fun... | The problem is that B b(A(i)); is a function declaration and not a declaration for a variable named b of type B.
This is due to what is called most vexing parse. In particular, the statement:
B b(A(i)); //this is a declaration for a function named `b` that takes parameter of type A and has no return type
the above is... |
72,316,393 | 72,316,460 | (Windows)Can I get the program to be changed or be stopped while it is running? | I am now writing a win32 program in C++.
I want to show my running process on the window, just like time is flowing.
For example, this code
int a=0;
for(int i=0;i<10;i++)
{
a++;//The change in "a" can be seen on the window.
Sleep(1*1000);
}
But I've found that if I want to show this process, like clicking a button... | You want to create a timer with SetTimer. Then watch for the WM_TIMER messages and update the screen then. This is the standard way of achieving what you described.
|
72,317,263 | 72,317,339 | Output of map of set custom objects c++ | So I have a map that has user defined keys and the values in it are sets of objects too. So I'm trying to write some print function but I have no idea how to do that. (I'm kind of new to maps and sets).
My problem function:
void print() const
{
for (auto& itr : my_mmap)
{
std::cout << "... | The problem is that we cannot use indexing on a std::set. Thus itr.second[i] is not valid because itr.second is an std::set.
To solve this you can use a range-based for loop as shown below:
for (const auto&elem:itr.second)
{
std::cout << elem << std::endl;
}
|
72,317,296 | 72,317,347 | how to deal with a function pointer problem? | i'm implementing a normal function pointer.
so this is the function that i want to call:
WndDyn* Punkt2d::pEditPunkt(WndInfo& wi, Int32 AnzSichtChar, Bool WithUnit,
const DecimalsConf& DecConf)
{
WynDyn_callback Dyncallback;
Dyncallback.AnzSichtChar = AnzSichtChar;
Dyncallback.WithUnit = WithUni... | Because pEditFeldX is a member function you can't just call pEditFeldX(Dyncallback). You must call the function on some Punkt2d object, using e.g. meinPunkt2d.pEditFeldX(Dyncallback).
If you write pEditFeldX(Dyncallback) inside the Punkt2d class then it means (*this).pEditFeldX(Dyncallback). The compiler adds (*this). ... |
72,317,757 | 72,318,013 | How to properly use >> to get columns of an input file in cpp? | I'm pretty new to cpp and I've been struggling on this for hours, none of my research attempts were lucky.
I have a few .txt files with the following structure:
07.07.2021 23:11:23 01
08.07.2021 00:45.44 02
...
I want to create two arrays, one containing the dates and one containing the times. However all I've accompli... | Your issue is that you use while and std::getline for no reason. Combining std::getline and << leads to issues, and you also try to read whole file into first elements of your vectors because of the while loop.
Since unsuccessful read will return empty string (which are already in your vectors), you can skip any checks... |
72,318,794 | 72,319,491 | How to use clock_cast? | I would like to convert time points from different clocks. Currently I follow the suggestion from here.
static auto ref_sys_clk = std::chrono::system_clock::now();
static auto ref_std_clk = std::chrono::high_resolution_clock::now();
auto to_sys_clk(std::chrono::high_resolution_clock::time_point tp)
{
//return std:... | std::chrono::high_resolution_clock does not participate in the std::chrono::clock_cast facility. The reason for this is that high_resolution_clock, has no portable relationship to any human calendar. It might have one on some platforms, notably if it is a type alias for system_clock. But it definitely does not on al... |
72,319,088 | 72,322,687 | C++ prioritize data synchronization between threads | I have a scenario, where I have a shared data model between several threads. Some threads are going to write to that data model cyclically and other threads are reading from that data model cyclically. But it is guaranteed that writer threads are only writing and reader threads are only reading.
Now the scenario is, t... | The way I would approach this is to have two identical copies of the dataset; call them copy A and copy B.
Readers always read from copy B, being careful to lock a reader/writer lock in read-only mode before accessing it.
When a writer-thread wants to update the dataset, it locks copy A (using a regular mutex) and upda... |
72,319,906 | 72,321,752 | How to use an argument as return value in gmock | I have the following call:
EXPECT_CALL(myMock, myFunction(someSpecifiedParameter, _, _))
.WillOnce(DoAll(SaveArg<2>(&bufferSize), Return(make_pair(Success, bufferSize))));
I'm trying to return whatever value that is passed as the second _ as my second element in the pair. Is it the best (or at least right) way t... | Your way is right, you deanonymize the value in the third parameter. In my opinion using a lambda or a custom actions is the more preferable way. A stored lambda or an action can be reused in other expectations.
EXPECT_CALL(myMock, myFunction(someSpecifiedParameter, _, _))
.WillOnce(WithArgs<0, 2>([](Type1 Success, T... |
72,319,915 | 72,364,662 | Why can't `std::experimental::make_array` use `std::reference_wrapper`? | template <class D, class...>
struct return_type_helper
{
using type = D;
};
template <class... Types>
struct return_type_helper<void, Types...> : std::common_type<Types...>
{
static_assert(
// why can't I use reference wrappers?
std::conjunction_v<not_ref_wrapper<Types>...>,
"Types cannot contain ... | Checking the proposal N3824 confirms my initial suspicion.
Namely, the static_assert check was added to explicitly disallow type deduction of a std::array<std::reference_wrapper<T>, N> from make_array, because the proposal’s author has deemed this usage error-prone.1
That is, with the following code:
auto x = 42;
auto ... |
72,320,584 | 72,320,686 | binary search tree by smart pointers | I used row pointers to implement the binary search tree data structure and it worked perfectly, but when I replaced the row pointers with shared_ptr it compiles successfully but the program crashes due to unknown run-time error. Could you please help in this?
#include<iostream>
#include<memory>
class node{
public:
int ... | #include<iostream>
#include<memory>
class node
{
public:
int data;
std::shared_ptr<node>left;
std::shared_ptr<node>right;
};
std::shared_ptr<node>CreateNode(int x);
void print_tree(const std::shared_ptr<node>&x);
int main()
{
auto root = CreateNode(12);
root->left = CreateNode(9);
root->right... |
72,320,649 | 72,320,849 | Assigning general classes as null in C++ | I am having kind of a trouble adapting a program from C# to C++. It's very commom given a class to assign it the null value. But C++ is not accepting the equivalent form 'nullptr'
class Point{
public:
int x,y;
}
//...
Point p = nullptr;
There is some way of solving it?
| You cannot assign nullptr to a class because a class is a type and not a variable. What you're doing by typing Point p = nullptr; is that you're asking the compiler to find a constructor of Point which accepts a nullptr.
You can either create an object of Point as an automatic variable by doing this:
Point p = Point{1,... |
72,321,144 | 72,321,261 | Error: Binding reference of type .. to const | I'm trying to overload operator<<. When trying I got an error saying
Error: Passing const as this argument discards qualifiers
So I added const to my functions but now I'm getting this error:
Binding reference of type .. to const.
Main.cpp
ostream& operator<<(ostream& ostr, const Student& stud){
float mo = 0;
i... | get_grade is a const member function meaning that the type of this pointer inside it is const Student* which in turn means that the data member grade is treated as if it were itself const. But the problem is that the return type of your function is an lvalue reference to non-const std::vector meaning it cannot be bound... |
72,321,166 | 72,381,292 | C++ multithreaded program work fine in windows, throws "resource temporarily unavailable" in Linux | Edit:
Based on Jonathan's comment, I tried to create a standalone program to reproduce this issue. I was unable to recreate the issue.
Then I switched to Jeremy's comment to make sure I really am calling this only once. Turns out, there was a bug in the upstream code which was calling this in a loop when a specific con... | Turns out there was a bug in the upstream code which was making repeated calls to setStartTime.
The reason why the issue showed up only in Linux is because it is a much faster OS. Windows would probably have the same experience if I let the code run for a few days. (in case anyone's curious, the program tries to find t... |
72,321,576 | 73,762,419 | using `[[gnu::noinline]]` in header-only library | Functions in a header-only library should be declared as inline to prevent multiple definitions in the different translation units. That is, for example, I wrote a header-only library mylib.hpp:
void do_something(int) {}
And I used this header in two different cpp file:
// a.cpp
# include "mylib.hpp"
void func1() {do_... | The 'proper' way to get rid of the warning is to split your code into a header (.h) and source (.cpp) file.
// mylib.h
[[gnu::noinline]]
void do_something(int);
// mylib.cpp
void do_something(int)
{
// Implementation
}
// a.cpp
#include "mylib.h"
void func1()
{
do_something(1);
}
// b.cpp
#include "mylib.h"
vo... |
72,321,943 | 72,322,086 | Is there a reason to use zero-initialization instead of simply not defining a variable when it is going to be updated before the value is used anyway? | I came across a code example learncpp.com where they zero-initialized a variable, then defined it with std::cin:
#include <iostream> // for std::cout and std::cin
int main()
{
std::cout << "Enter a number: "; // ask user for a number
int x{ }; // define variable x to hold user input (and zero-initialize it)
... |
Is there any reason that on line 7 you wouldn't just not initialize x?
In general, it is advised that local/block scope built in types should always be initialized. This is to prevent potential uses of uninitialized built in types which have indeterminate value and will lead to undefined behavior.
In your particular ... |
72,322,122 | 72,322,800 | Which libraries are available to link in cmake? | I was learning CMake for a project and feel confused when linking libraries.
I find it easier to ask with an example, as using terms I am not familiar could be misleading.
The questions are (also commented in the example codes)
how can I know what are the library name I can link to my target? Can I tell that from the ... | Your question is too broad. Either ask a question about the list of libraries in cmake, or ask a question about how to compile and link with hermes, or ask a question about a specific problem with your build about including a third party. These should be 3 separate questions on this site.
how can I know what are the l... |
72,322,537 | 72,323,474 | Any way to build an array of pointers from a tuple of different objects (but derived from the same base class)? | Good morning all!
reading stack overflow for a long time, but this is my first post here.
For some reasons I would like to do something like this:
class Base{
...
}
class A : public Base{
...
}
class B : public Base{
...
}
std::tuple<A, B> myTuple{A{}, B{}};
std::array<Base*, 2> myArray{...};
Briefly - I... | It is possible to create an array of pointers to tuple members using various compile time programming techniques. Below is one implementation. There may be a less verbose way of doing this, but I am no expert on this kind of stuff:
#include <iostream>
#include <string>
#include <array>
#include <tuple>
class Base {
pu... |
72,322,612 | 72,322,954 | Garbage when converting character to string using concatenation | I am converting a character to a string by concatenating it with an empty string (""). But it results in undefined behaviour or garbage characters in the resultant string. Why so?
char c = 'a';
string s = ""+c;
cout<<s<<" "<<s.size()<<"\n";
| Let's look at your snippet, one statement or a line at a time.
char c = 'a';
This is valid, assigning a character literal to a variable of type char.
Note: since c is not changed after this statement, you may want to declare the definition as const.
string s = ""+c;
Let's refactor:
std::string s = ("" + c);
Let's add... |
72,322,958 | 72,765,708 | cannot capture the struct value inside of the kernal function | It is so strange and I am struggling with this problem for the whole week. I just want to use the variable which is defined inside of the struct constructor, but fail to do that. The simple code is here:
#include <CL/sycl.hpp>
#include <fstream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#define ghost 3... | According to 4.12.4. Rules for parameter passing to kernels from SYCL 2020 Specification the array of scalar values can be passed as a kernel parameter. But the problem is in the capturing of struct member:
[lsq = this->ls]
is equivalent to
auto lsq = this->ls;
In this case, the type of lsq is int* and it will contai... |
72,323,050 | 72,323,801 | How do I store the tmp object in a map, to acess the object outside of it's creation context | I am relatively new to C++. I tried to break down the problem.
All code is also here: https://onlinegdb.com/wAmLAONkF (can be executed)
Basically, I have a function where temp objects are created. The objects are pushed to a std::vector:
vector<Student> GetStudents(int some_params)
{
vector<Student> students;
... | The vector<Student> returned by GetStudents() needs to be stored in a variable that is in the same scope as (or in a higher scope than) the std::map that refers to its Students, eg:
map<int, vector<Student*>> m;
vector<Student> students; // <-- move it up here!
{ //start of new context
int some_params = 5;
st... |
72,323,481 | 72,323,705 | Struct template and constructor with initializer list | I'm trying to better understand templates and for this purpose I made an educational struct:
template<typename T, size_t N>
struct SVectorN
{
SVectorN(const T(&another)[N]);
private:
T components[N];
};
Constructor that I made allows me to make an instance, like this:
double input[4] = { 0.1, 0.2, 0.3, 0.4 };
... | Both approaches are possible, initialization in C++ is tricky simply because of how many ways there are and their subtle differences.
I would recommend something like this:
#include <cstdint>
#include <utility>
template <typename T, std::size_t N> struct SVectorN {
SVectorN(const T (&another)[N]);
template <t... |
72,323,821 | 73,214,277 | 'QMainWindow' file not found | the program works, but I don't like these errors
in mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow> //'QMainWindow' file not found
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget... | I have already found answer there: https://stackoverflow.com/a/58737644/18282426
so, select from above help -> About modules... and disable ClangCodeModel
|
72,324,033 | 72,325,297 | C++ Unordered Set string hash time complexity? | Why the worst case complexity of insert into set is linear constant of size of container and not the size of element itself?
I am specifically talking about string. If I have a string set of size m, then if I insert a new string of size x, I assume that the insert operation will need to read string of size x in order t... | This is a great question and it hits at some nuances in the way we analyze the cost of operations on hash tables.
There are actually several different ways to think about this. The first one is to think about the runtimes of the operations on a hash table measured with a runtime perspective that purely focuses on the s... |
72,324,668 | 72,325,774 | Define type alias between template and class declaration in order to inherent from it | I have a class template which uses some type alias through its implementation, and also inherits from the same type:
template<typename TLongTypename,
typename TAnotherLongTypename,
typename THeyLookAnotherTypename>
class A : SomeLongClassName<TLongTypename,
TAnotherLongTy... | You could declare the type alias Meow as a default template parameter, directly in the template parameter list, which means you only have to spell it out once:
template<typename TLongTypename,
typename TAnotherLongTypename,
typename THeyLookAnotherTypename,
// declare Meow once here
... |
72,325,015 | 72,325,034 | I am using ifstream and I need to read in two words as one string instead of splitting them | I need to read in a line from a file, but I need to save two strings as one. For example, if the file's line had someone's name like Bernie Sanders, I would want to save the entire name into a string variable instead of just the first name.
| I assume you are doing
std::string nameString;
fs >> nameString;
this will read to the end of a word.
do this instead
std::string nameString;
std::getline(fs, nameString);
this will read the whole line
|
72,325,434 | 72,325,460 | How to use if commands with sentances | I am currently learning c++ and creating an assistant for myself. I need to make sure the if command checks for a sentence, not a word in a string how do I do that.
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
const string YES = "yes";
const string NO = "no";
//ignore this
int main (... | In this:
if (Question == whats the weather?)
Add quotes around the sentence. You want to write
if (Question == "whats the weather?")
Also, since you're using namespace std, you don't need std:: before anything.
|
72,325,472 | 72,325,491 | Define a different function for each instance of a class | Say I have this class:
class Object {
public:
int x;
int y;
void update(SDL_Event);
void start();
};
I want to be able to make start and update change behavior from instance to instance.
I have tried using function pointers, like so:
class Object {
public:
int x;
int y;
void (*update)... | You would need to pass your functions a pointer/reference to the Object instance, eg:
class Object {
public:
int x;
int y;
void (*doupdate)(Object*, SDL_Event);
void (*dostart)(Object*);
void update(SDL_Event event) { if (doupdate) doupdate(this, event); }
void start() { if (dostart) dostar... |
72,325,515 | 72,325,533 | Why is the std::vector not giving any outputs in c++ | I don't understand why but the std::vector is not giving anything after i put a class pointer in the array.
// runs at start
void States::AssignState(GameState* state) {
_nextVacentState++;
_states.push_back(state);
}
// executes in a loop
void States::ExecuteCurrentState() {
// protection incase there is ... | This is one of the reasons I'd suggest getting in the habit of using curly braces for all if statements, even ones that live on a single line.
A problem line:
if (_nextVacentState == 0) std::cout << "Error: There is no states, setup some states then try again" << std::endl; return;
Let's add some newlines to make it c... |
72,325,783 | 72,325,795 | What is the `(... && TraitsOf())` mean in C++ | I am trying to understand this C++ syntax:
constexpr auto all_deps_type_set =
(... | TraitsOf(types::type_c<HaversackTs>).all_deps);
What does the (...| part mean?
Example: https://github.com/google/hotels-template-library/blob/master/haversack/haversack_test_util.h
| HaversackTs is a parameter pack, which means it contains some variable number of types given to the template. ... expands a template parameter pack, using a given binary operator (in our case, the bitwise |) to fold over it. So if, in a particular instantiation of this template, HaversackTs happened to be int, std::str... |
72,325,907 | 72,326,806 | Is there a way to create an array of combined functions compile-time in c++? | I'm working on an NES emulator in c++ and figured that the most efficient way to run opcodes would be to call a function pointer in an array of functions that do exactly what the opcode does.
The problem is that each opcode has a specific operation and memory address. While searching for a solution, I stumbled upon lam... | I'd say that when you want to write generics for functions that it's kind of a "design pattern" to switch to functors: Compilers are desigined to handle types easily, but handling function pointers for stuff you want to mis-match and keep optimised at compile-time gets ugly!
So we either write our functions as functors... |
72,326,082 | 72,326,125 | Question about the thread-safety of using shared_ptr | As it's well known that shared_ptr only guarantees access to underlying control block is thread
safe and no guarantee made for accesses to owned object.
Then why there is a race condition in the code snippet below:
std::shared_ptr<int> g_s = std::make_shared<int>(1);
void f1()
{
std::shared_ptr<int>l_s1 = g_s; // r... | std::shared_ptr<T> guarantees that access to its control block is thread-safe, but not access to the std::shared_ptr<T> instance itself, which is generally an object with two data members: the raw pointer (the one returned by get()) and the pointer to the control block.
In your code, the same std::shared_ptr<int> insta... |
72,326,940 | 72,327,235 | Sum of the two lowest positive numbers in a vector | I made a function sumOfTwoSmallestNumbers() that takes an integer vector (containing only positive values) and it returns the sum of the two lowest positive numbers stored in that vector. Unfortunately, my function fails for a few test cases (I do not have access to the inputs of those test cases). Please help me find ... | Your code has a couple of issues:
If the smallest number in the vector is the first, position will be uninitialized and cause UB (Undefined Behavior).
If you'll initiazlie position to 0 as required, then again if the smallest number in the vector is the first, this line numbers.erase(numbers.begin() + position - 1) wi... |
72,327,344 | 72,327,376 | How to check that they belong to the same class in c++ test Visual Studio? | I want to check if the constructor is initialized correctly, but I don't know which assert method to use
TEST_METHOD(testInitNavigator)
{
Room room;
INavigator navigator(room);
Assert::AreSame(room, navigator.getLocalRoom());
}
| I think it is correct so
TEST_METHOD(testInitNavigator)
{
Room room;
INavigator navigator(room);
Assert::IsTrue(typeid(room).name() == typeid(navigator.getLocalRoom()).name());
}
|
72,327,932 | 72,327,992 | Random Characters being stored in a file | I have created an Admins class with three data members (adminID, adminName, adminPhone) and an array of objects for that same class. The data of each object is to be stored in a .txt file.
There is no run-time error and the program works as expected but upon opening the file in notepad, I found that there are random ch... | Concept
Those are not random character, instead they are the raw bytes of your class stored on stack-memory for a single instance and will be completely random in another instance of your application. In short, those "random" characters are garbage bytes beyond null terminating ('\0') character in your string.
FIX
fout... |
72,328,292 | 72,328,812 | cmake, scribus - List all required libraries | I'm trying to build Scribus (1.5.8 and 1.7) from source in Ubuntu 20.04. It uses cmake as its build system. I have no experience with cmake.
Is there a way to get a list of all the required and/or optional libraries from cmake or any command line tool?
Right now, my "workflow" is the following:
Run cmake . in source d... |
Is there a way to get a list of all the required and/or optional libraries from cmake or any command line tool?
Not in an automated way. Generally that is not possible. There may be dependencies not managed by CMake, outside of CMake code, there may be dependencies of dependencies, and many corner cases. Also, there ... |
72,328,810 | 72,330,784 | How to check for current CMake build type in C++? | A little background: I'm writing a game in SFML and I want certain lines of code to be ommitted in Release build. I want to check during compile time for build type, so that is doesn't impact game's performance.
void Tile::draw(sf::RenderTarget& target, sf::RenderStates states) const {
states.transform *= getTransf... | That's how you might do it in general (working for any generator):
add_executable(${PROJECT_NAME} main.cpp)
target_compile_definitions(${PROJECT_NAME} PRIVATE "DEBUG=$<IF:$<CONFIG:Debug>,1,0>")
If you need it for every target you can use the following in the top CMake file (in case you have multiple with add_subdirect... |
72,329,326 | 72,330,028 | How to pass a 2D array by Reference to a function in C++ | How do i pass array b1 in the function dfs, b1 is a 2D integer array used to track whether the node was visited. Sorry for the poor code readability. i want to pass it by reference as it needs to be modified by the function called recursively.Currently getting this error.
Line 33: Char 94: error: 'b1' declared as array... | Since you already use vector<vector<char>>& board as one parameter, the simplest way to fix this error is to use vector<vector<int>> b1 instead of int b1[m][n].
Please take care of VLAs like int a[n][m], it's not easy to maintain and also not recommended. See more at Why aren't variable-length arrays part of the C++ st... |
72,329,370 | 72,329,607 | GLM linking in CMakeLists.txt | I cannot link glm library with my executable. I tried link via
${GLM_INCLUDE_DIRS}, ${GLM_LIBRARIES} and ${GLM_LIBRARY_DIRS} cmake variables but it does not work.
How can I link libraries and inludes of glm with my executable?
I am using find_package() method :
find_package(glm REQUIRED PATHS "${GLM_BINARY_DIR}" NO_DEF... | Config script for GLM defines IMPORTED target glm::glm.
So the correct way for use GLM in CMake code is to link with that target.
This is explicitly written in the documentation:
set(glm_DIR <installation prefix>/lib/cmake/glm) # if necessary
find_package(glm REQUIRED)
target_link_libraries(<your executable> glm::glm)
... |
72,329,441 | 72,329,564 | Not Displaying Spaces | I'm very new to c++ and everything in general. I dont understand why my code doesn't work:
#include <cstdio>
int main(){
int a;
scanf("%d", &a);
for(int i = 1; i < a; i++){
printf(" ");
}
printf("*");
}
what I'm trying to do is make the number of spaces as the value inputted by the user minus and add a * at t... | You will have to use 3 for-loops (two of them nested inside one). The parent for loop for each row. And the nested two are for spaces and stars.
#include <cstdio>
int main()
{
int a;
scanf("%d", &a);
for(int i=1; i<a; i++)
{
for(int j=i; j<a; j++)
printf(" ");
for(int k=0;... |
72,329,583 | 72,329,635 | concept std::derived_from when the argument is a smart pointer | I have a few functions like so
bool RegisterModel (std::shared_ptr<DerivedA> model) { }
bool RegisterModel (std::shared_ptr<DerivedB> model) { }
and i would like to make use of c++ 20 concepts and implement it like this:
bool RegisterModel (std::derived_from<BaseClass> auto model) { }
This does not work, because i'm... | Deduce the T from a std::shared_ptr<T> and constrain that:
template<std::derived_from<BaseClass> T>
bool RegisterModel (std::shared_ptr<T> model) { }
|
72,329,682 | 72,329,806 | How to define static method in a cpp file. (C++) | I wan to have my class in a separate .h file, and the implementation in a .cpp file. The problem I run into is "Multiple definition of methodname". If I put the content of both files in a .hpp file it works, but I'm not sure if I should use that.
The .h File:
#pragma once
class Nincs;
class Sugar
{
public:
... | The problem is that you're including the source file(Sugar.cpp) instead of the header file(Sugar.h).
To solve this inside main.cpp, change #include "Sugar.cpp" to:
#include "Sugar.h"
Also it is recommended that we should never include source files.
Working demo
|
72,329,739 | 72,329,812 | Assigning std::minmax result to new variables | auto [x, y] = std::minmax(a, b) defines x and y as references to a and b (or b and a).
How do I make x and y new variables initialized with min and max values respectively (as if minmax returned pair of values instead of pair of refs)?
| You can use the overload of the std::initializer_list version, which returns pair<T, T>.
auto [x, y] = std::minmax({a, b});
|
72,329,759 | 72,331,822 | Constexpr function returning member of union: g++ vs. clang++: no diagnostics vs. error | Consider this code:
typedef union { float v; unsigned u; } T;
constexpr T x = { .u = 0 };
constexpr float f(void)
{
return x.v;
}
Is this code valid?
Invocations:
$ g++ t506a.cpp -c -std=c++20 -pedantic -Wall -Wextra
<nothing>
$ clang++ t506a.cpp -c -std=c++20 -pedantic -Wall -Wextra
t506a.cpp:3:17: error: co... | Both compilers are correct, even though the code is ill-formed, because no diagnostic is required in the program you've shown. It's true that f can never be evaluated as a core constant expression, but in that case dcl.constexpr#6 applies:
For a constexpr function or constexpr constructor that is neither defaulted nor... |
72,329,888 | 72,330,013 | Linker error: /usr/bin/ld: cannot find -lcudart_static while trying to compile CUDA code with clang | I tried to compile a axpy.cu file as specified in the official docs here:
clang++ axpy.cu -o exec --cuda-gpu-arch=sm_60 -L/usr/local/cuda -lcudart_static -ldl -lrt -pthread
But that gave a linker error and warning:
clang: warning: Unknown CUDA version. cuda.h: CUDA_VERSION=11060. Assuming the latest supported version... | So I found a solution. Apparently the linker wasnt able to locate libcudart binary. So used find to get its location:
find /usr/ -name libcudart_static*
Got its path as:
/usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudart_static.a
(might be different for you).
Just linked this path by using -L flag in the compila... |
72,330,319 | 72,498,375 | error: cannot open source file "winrt/WIndows.Foundation" showed up when I follow a microsoft's tutorial | I'm a complete beginner in Visual Studio and C++.
And now, I'm trying to follow this tutorial by Microsoft.
So I installed "c++/WinRT templates and visualizer" in my Visual Studio 2019 from the "Extension" menu above the visual studio and created a core app project.
However, when I run the project, visual Studio shows ... | As @IInspectable said in the comment, I need to compile my codes at least once when I create C++/winRT project.
After I compile my project, NuGet package generates C++/winRT headers automatically!
|
72,330,356 | 72,330,615 | Converte int to char* | int num = 123;
char num_charr[sizeof(char)];
std::sprintf(num_char, "%d", num);
how to convert int the same way without using sprintf?
I Only Need The Code To Convert Without print.
| char num_charr[12]; // space for INT_MIN value -2147483648
itoa( num, num_charr, 10 );
Note: itoa is not supported on all compilers.
|
72,330,697 | 72,331,392 | Opengl only binds buffers from function that created them | I'm trying to write a very barebones game engine to learn how they work internally and I've gotten to the point where I have a "client" app sending work to the engine. This works so far but the problem I am having is that my test triangle only renders when I bind the buffer from the "main" function (or wherever the buf... | You seem to not bind the vertex buffer to the GL_ARRAY_BUFFER buffer binding point before calling glVertexAttribPointer.
glVertexAttribPointer uses the buffer bound to GL_ARRAY_BUFFER in order to know which buffer is the vertex attribute source for that generic vertex attribute.
So, you should bind the vertexBuffer bef... |
72,331,168 | 72,344,118 | c++ windows application edit the main window | I'm trying to create a simple windows application in cpp. Opening Visual Studio 2019, I noticed that there is, in fact, a project like that, so I opened up a new one.
This is the window I get when I run it. Completely normal, as expected from a brand new project.
But... I can't figure out how to edit the main window? W... | 1.Right click on your project and Add resource -> Dialog.
IDD_DIALOG1 is created by default.
2.Modify the code in InitInstance() :
HWND hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), GetDesktopWindow(), (DLGPROC)WndProc);
3.There is a IDD_DIALOG1 in the Resource View and it can be edited by double clic... |
72,331,247 | 73,897,665 | How to get all tags from a tiff file with libtiff? | I have a tiff file and would like to get a list of all tags used in that file. If I understand the TiffGetField() function correctly, it only gets the values of tags specified. But how do I know what tags the file uses? I would like to get all used tags in the file. Is there an easy way to get them with libtiff?
| It seems to be a very manual process from my experience. I used the TIFF tag reference here https://www.awaresystems.be/imaging/tiff/tifftags.html to create a custom structure
typedef struct
{
TIFF_TAGS_BASELINE Baseline;
TIFF_TAGS_EXTENSION Extension;
TIFF_TAGS_PRIVATE Private;
} TIFF_TAGS;
With each subs... |
72,331,290 | 72,332,623 | gcov produces different results on Clang and GCC | I'm trying to understand how to properly structure a C++ project by using CMake, googletest, and gcov for test coverage. I would like to build a general CMakeLists.txt that would work for any platform/compiler.
This is my first attempt. However, if I try to build the project and then run lcov (to generate the report), ... | You are actually asking two questions, here.
Why do the coverage results differ between these two compilers?
How do I structure a CMake project for code coverage?
Answer 1: Coverage differences
The simple answer here is that you are building in Release mode, rather than RelWithDebInfo mode. GCC does not put as much d... |
72,331,313 | 72,331,344 | C++ raw string with special char | I want to output a string like this: onclick="func()". So I wrote the following code:
std::string s = R"(
onclick="func()"
)";
But here two )" let the compiler confused.
Please forgive me if it's a silly question.
I googled but found nothing (I don't know which keyword I should use when I googled).
| Simply add a unique string outside the ()
std::string s = R"anystring(
onclick="func()"
)anystring";
|
72,331,773 | 72,331,819 | Declaration of template specialization on a template function | I'm getting undefined reference to ´long long fromBigEndin<long long>(unsigned char*)´ for a template specialization.
See code here: https://onlinegdb.com/AagKTQJ2B
I have this structure:
util.h
template <class T>
T fromBigEndin(uint8_t *buf);
template <>
int64_t fromBigEndin<int64_t>(uint8_t *buf);
template <>
long l... | Method 1
You need to put the implementation of the function template into the header file itself. So it would look something like:
util.h
#pragma once //include guard added
template <class T>
T fromBigEndin(uint8_t *buf);
//definition
template <> int64_t fromBigEndin<int64_t>(uint8_t *buf)
{
return 53;
}
//defini... |
72,331,799 | 72,331,836 | Best way to implement fixed size array in C++ | I am trying to implement a fixed size array of 32 bit integers, but the size is determined at runtime so it has to be heap allocated. Would it be more efficient to use a c++ std::vector and use vector.reserve() or should I use the conventional way of doing it using new int32_t[size]? Additionally, would it be worth usi... | You would just be re-implementing std::vector. Probably badly because it takes years to figure out all the little corner cases and implement them correctly.
|
72,332,210 | 72,332,272 | Passing c++ map by reference and see changes after insert | Hey guys!
I'm just getting into c++ and after learning stuff about reference and value pass I've come across a problem.
So basically I'm trying to copy a map and I do so in my method. So far the size of the 2 maps are the same.
The problem comes when I insert some new values into the original map because it doesn't cha... | map and copyMap are separate objects and so changing one won't affect other. Moreover, you're returning the map by value from the function passMapByReference. Instead you could return the map by reference from passMapByReference as shown below:
#include <iostream>
#include <map>
#include <string>
//-------------------... |
72,332,376 | 72,332,788 | Debian, cmake, connot compile c++ program, missing config cmake file | Trying to compile dot11decrypt on debian, installed apt-get install libtins4.0 and apt-get install libtins-dev, but cmake .. can't find package libtins, heres the error:
CMake Error at CMakeLists.txt:4 (FIND_PACKAGE):
By not providing "Findlibtins.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a packa... | You don't need to compile from source... find_package is a very flexible configuration point! You'll just need to provide your own find module that is sufficient for the build. Fortunately, this is very simple. Here's what I did:
$ https://github.com/mfontanini/dot11decrypt
$ cd dot11decrypt
$ mkdir _patches
$ vim _pat... |
72,332,387 | 72,332,550 | Is this a correct implementation of ConvertsWithoutNarrowing | I am currently learning about concepts in C++20, and came across this example:
template <typename From, typename To>
concept is_convertible_without_narrowing = requires (From&& from) {
{ std::type_identity_t<To[]>{std::forward<From>(from)}} -> std::same_as<To[1]>;
};
I am curious if the following can be considered a... |
I am curious if the following can be considered a correct alternative
implementation of the above:
The simple answer is no.
In the second version, To{std::forward<From>(from)} can be regarded as constructing To through initializer_list, so is_convertible_without_narrowing<int, std::vector<int>> will be true.
Similar... |
72,332,678 | 72,332,971 | How to access the data member of one function into another function inside same class in c++ | I wanted to declare the array of string to the limit provided by user. So I take limit in getData(), and declare the string inside getData function. As a whole I want to take students name and display it in the same class. Sorry for basic question and thank you in advance.
class student
{
int limit;
public:
vo... | One problem with your code is that string name is defined in getData() but not in showData(). What I would do is declare a member variable vector<string> name like you did with int limit. I would use a vector instead of an array because it's easier to code for me.
#include <iostream>
#include <vector>
using namespace ... |
72,332,949 | 72,333,039 | How to make functions behave differently for different templates in C++? | A part of my C++ homework is to make the FooClass for this main:
int main()
{
const int max = 10;
int x[] = {10, 20, 7, 9, 21, 11, 54, 91, 0, 1};
FooClass<int> xl(x, max);
int x2[] = {10, 20, 7, 9, 21, 11, 54, 91, 0, 1};
FooClass<int, std::greater<int> > xg( x2, max);
xl.sort();
xg.sort()... | First of all, you are not using F. You need to pass an instance of F to std::sort:
void sort()
{
std::sort(mItems, mItems + mItemsSize, F{});
}
Secondly: Your default F would make both your instances in your example sort the array in the same way. To get the expected result, you should make the default F use std::... |
72,333,232 | 72,333,262 | how to round a number to N decimal places in C++? | I want to round a number to 10 decimal places , but it returns '6.75677', although it could returns '6.7567653457'
#include <iostream>
#include <cmath>
using namespace std;
double rounded(double number, int N)
{
return round(number * pow(10, N)) / pow(10, N); // i've chanched float to double
}
int main()
{
do... | cout << fixed << setprecision(10) << value << endl
|
72,333,353 | 72,333,731 | Linux kernel function returns 1 instead of EINVAL | I'm trying to add a new system call to linux kernel:
asmlinkage long sys_set_status(int status) {
if ((status != 0) && (status != 1))
return -EINVAL; //-22
current->status = status;
return 0;
}
in syscall_64.tbl it is declared:
334 common set_status sys_set_status
in syscalls.h it is declare... |
long r = syscall(334, status);
From man syscall:
The return value is defined by the system call being invoked. In
general, a 0 return value indicates success. A -1 return value
indicates an error, and an error number is stored in errno.
You are not calling the system call directly, you are calling it via the ... |
72,333,443 | 72,333,469 | Bitwise XOR on unsigned char is terminating program without error | I'm trying to create a 64 bit integer as class in C++, I know this already exists in the C header stdint.h but I thought it could be a fun challenge.
Anyway, I am trying to perform a bitwise XOR operation on three unsigned chars, and the program keeps stopping without warning, it just pauses for a split second and then... | You're trying to dereference invalid pointers. You want to get rid of a lot of those *s.
unsigned char a = 1;
unsigned char b = 2;
unsigned char c = 3;
unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char));
std::cout << "Trying" << std::endl;
*result = a ^ b ^ c;
std::cout << "Done!" << std::endl;
W... |
72,333,601 | 72,350,128 | SFML sf::View::move inconstancy | UPDATE:
I couldn't figure out the exact problem, however I made a fix that's good enough for me: Whenever the player's X value is less then half the screen's width, I just snap the view back to the center (up left corner) using sf::View::setCenter().
So I'm working on a recreating of Zelda II to help learn SFML good en... | There's a clear mismatch between the movement of the player and the one of the camera... You don't show the code to move the player, but if I guess you don't cast to int the movement there, as you are doing on the view.move call. That wouldn't be a problem if you were setting the absolute position of the camera, but as... |
72,333,605 | 72,334,439 | Partial specialiszation of a template class with string template argument | #include <iostream>
template<unsigned N>
struct FixedString
{
char buf[N + 1]{};
constexpr FixedString(const char (&s)[N])
{
for (unsigned i = 0; i != N; ++i)
buf[i] = s[i];
}
};
template<int, FixedString name>
class Foo
{
public:
auto hello() const { return name.buf; }
};
... |
What is the proper way to specialise template classes with string template arguments?
The given code is well-formed(in C++20) but fails to compile for gcc 10.2 and lower. It however compiles fine from gcc 10.3 and higher. Demo
Might be due to that not all C++20 features were fully implemented in gcc 10.2 and lower.
|
72,334,552 | 72,713,903 | pybind11 - ImportError: undefined symbol: _Py_ZeroStruct | I'm following the pybind11 documentation and trying to create Python bindings for a simple function Creating bindings for a simple function, but after compiling my C++ code with the following command:
g++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cc -o example$(python3-config --extens... | Well after trying a lot of methods I finally decided to add pybind11 as a submodule in my project and use Python3.9 and it seemed to work this time.
Anyone struggling with the same problem can try my method, it may work and don't expect help from this cruel community.
|
72,334,734 | 72,334,776 | Impact of a mutable member on a complete const object and UB | A complete const object cannot be replaced per basic.life. Placement new will result in UB. This is a complete const object:
struct A {int i{};};
const A cco;
However, this, because it isn't a complete const object and only the subobject is const, may be replaced as of c++20:
struct A {const int i{};};
A o;
But what ... | dcl.stc#9 says:
[Note 4: The mutable specifier on a class data member nullifies a const specifier applied to the containing class object and permits modification of the mutable class member even though the rest of the object is const ([basic.type.qualifier], [dcl.type.cv]).
— end note]
(emphasis mine)
This means that... |
72,334,826 | 72,334,841 | Is it possible to define a custom cast on an object to become the result of a method call? | Is it possible to define a custom cast on an object so that the objects casts to the result of a method call?
class Foo {
public:
...
int method() { return 3; }
};
Foo foo;
int bar = foo + 7; // 10
| Agh. I was overthinking it.
#include <iostream>
#include <string>
class Foo {
public:
Foo() { _data = 3; }
int method() { return _data; }
operator int() {
return method();
}
int _data;
};
int main()
{
Foo foo;
int bar = foo + 7;
std::cout << bar << std::endl;
}
|
72,335,246 | 72,335,488 | c++ missing construction and destruction of an object | The following code:
#include <iostream>
#include <string>
using namespace std;
void print(string a) { cout << a << endl; }
void print(string a, string b) { cout << a << b << endl; }
class A {
public:
string p;
A() { print("default constructor"); }
A(string a){ p = a; print("string constructor ", p... |
Where is the construction/destruction of the whereDidThisGo variable defined in main?
You do not see the ouptut for this due to named return value optimization(aka NRVO).
it's not a good optimization for people like me who are trying to learn constructors
You can disable this NRVO by providing the -fno-elide-constr... |
72,335,279 | 72,335,331 | Why is static_cast<Object&&> necessary in this function? | Trying to understand std::move, I found this answer to another question.
Say I have this function
Object&& move(Object&& arg)
{
return static_cast<Object&&>(arg);
}
What I think I understand:
arg is an lvalue (value category).
arg is of type "rvalue ref to Object".
static_cast converts types.
arg and the return t... |
the static_cast is unnecessary.
It may seem so, but it is necessary. You can find out easily by attempting to write such function without the cast, as the compiler should tell you that the program is ill-formed. The function (template) returns an rvalue reference. That rvalue reference cannot be bound to an lvalue. T... |
72,335,652 | 72,335,724 | how to round a number to N decimal places in C++? (correction) | I want to round a number (6.756765345678765) to 10 decimal places , but it returns '6.75677', although it could returns '6.7567653457'
#include <iostream>
#include <cmath>
using namespace std;
double rounded(double number, int N)
{
return round(number * pow(10, N)) / pow(10, N); // i've chanched float to double
}
... | You can use setprecision(10) function of <iomanip>.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double value = 6.756765345678765;
cout << setprecision(10) << value;
}
Output:
6.756765346
|
72,336,395 | 72,336,746 | How to convert string expression to boolean in c++? | How can I convert the string "a > b" to bool?
#include <iostream>
using namespace std;
float condition(float a, float b)
{
bool cond;
/*
i'd like to see a function converting string "a > b" to bool
*/
return cond
}
int main()
{
if (condition(7, 6))
{
... | In C++, you can utilize lambda functions to achieve something similar:
#include <iostream>
using CmpFunc = bool(float, float);
CmpFunc* condition(char op) {
switch (op) {
case '>':
return [](float a, float b) { return a > b; };
case '<':
return [](float a, float b) { return a < b; };
case '=... |
72,336,579 | 72,337,044 | Good way of popping the least signifigant bit and returning the index? | I am new to C++ and I'm trying to write a function that will pop the least significant bit and then return the index of that bit. Is there a way to do this without creating a temporary variable?
Right now I have a function for finding the index and one for popping the bit but I'd like to combine the two.
inline int LSB... | There's nothing wrong with using a temporary variable. However modern architectures are superscalar and out-of-order so to better adapt for them you should only use that for the return value and don't use it to clear the least significant bit to avoid an unnecessary dependency chain
int popLsbAndReturnIndex(uint64_t *b... |
72,337,435 | 72,337,995 | error on do while loop condition in C++ with condition to continue the loop | I am making c++ program using do while loop but after inserting the condition while ( x =='y'|| x == 'Y'); I got an error where the loop is continued without letting me to insert the input again.
I can't insert the input until I stop the program.
#include <iostream>
using namespace std;
int main()
{
char str[30];... | The problem you are seeing is that there is are leftover characters in the cin buffer, so the next time through the loop it reads those and doesn't ask the user for input. If you clear the buffer out at the end of the loop then the subsequent runs work.
do {
//...
std::cout << "Ingin teruskan? (Y-yes, N-No): ... |
72,337,723 | 72,338,137 | I just started c++ and made a calculator. What or how can I improve my code/ learn more? | So I tried making a simple calculator that can input 2 floats and do basic operations (addition, subtraction, division, multiplication). This is the first time I'm writing a code without copying the entire thing from a tutorial. I did copy some bug fixes and other things but mostly I did it myself. I want criticism and... |
function don't need to return 0, simply declare those as void return.
except int main()
the cin>>num; while(!cin){cin>>num;} can be merged as while(!(cin>>num))
ignore 256 char may not be enough
use std::numeric_limits<std::streamsize>::max() instead
for ctype.h, the corresponded c++ header is cctype (relevant ... |
72,338,190 | 72,338,657 | className SerialNow = *((className*)ptr); vs className &SerialNow = *((className*)ptr); | What is difference between using or not reference when casting pointer to object?
void someClass::method() {
xTaskCreatePinnedToCore(someTaskHandler,"SerialNowTaskTX",XT_STACK_MIN_SIZE*3,this,4,&taskHandleTX,0); // passing 'this' to task handler
}
void someTaskHandler(void *p) {
SerialNow_ SerialNow = *((Seria... | Preliminary remark
First, keep in mind that casting void* pointers is in C++ a rather dangerous thing, that can be UB if the object pointed to is not compatible with the type you're casting to.
Instead of a C-like cast between parenthesis, prefer a C++ more explicit cast, that shows better the level of danger. If p wo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.