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 |
|---|---|---|---|---|
69,823,127 | 69,823,666 | Why does this compile? cout<"Yes"; | #include<iostream>
using namespace std;
int main(){
cout<"Yes";
}
it compiles, but when it runs, it does nothing. this is a compilation error elsewhere.
compiler is gcc 4.9.2
compared with
#include<iostream>
using namespace std;
int main(){
cout<<"Yes";
}
it has a missing '<' but it still... | Default C++ standard in GCC<6.1 (which includes your 4.9.2) is gnu++98, while for GCC≥6.1 it's gnu++14 (as documented e.g. here). Thus the latter compiler won't accept this code by default, due to explicit operator bool() being present in the iostreams since C++11 instead of operator void*() in C++98 (see e.g. cpprefer... |
69,823,200 | 69,823,368 | GCC disagrees with Clang and MSVC when concept that's always true is used to implement a concept | The following code fails to compile with Clang 13 and MSVC v19.29 VS16.11 but successfully compiles with GCC 11.2.
template <typename...>
concept always_true = true;
template <typename T>
concept refable = always_true<T&>;
static_assert(refable<void>);
Clang 13:
<source>:9:1: error: static_assert failed
static_asser... |
static_assert(refable<void>);
As per [temp.names]/8, refable<void> is a concept-id:
A concept-id is a simple-template-id where the template-name is a concept-name. A concept-id is a prvalue of type bool, and does not name a template specialization. A concept-id evaluates to true if the concept's normalized constrai... |
69,823,481 | 69,830,250 | OpenCV - Accessing Mat data using for loop | I'm trying to create a convolution function but I'm having trouble during the access to the kernel data (cv::Mat).
I create the 3x3 kernel:
cv::Mat krn(3, 3, CV_32FC1);
krn.setTo(1);
krn = krn/9;
And I try to loop over it. Next the image Mat will be the image to which I want to apply the convolution operator and... | Instead of needlessly using memcpy, you can just cast the pointer. I'll use a C-style cast because why not.
cv::Mat krn = 1 / (cv::Mat_<float>(3,3) <<
1, 2, 3,
4, 5, 6,
7, 8, 9);
for (int i = 0; i < krn.rows; i += 1)
{
for (int j = 0; j < krn.cols; j += 1)
{
// to see clearly what's happeni... |
69,824,036 | 69,824,367 | Reading binary data from a .bin file into structs in C++ | I have a set of .bin files containing data in a formally specified format. I know exactly how many bytes there are for each field e.g. name = 40 bytes, version number = 2 bytes etc.
I also know the exact order they are stored in the file (e.g. name, then version number....).
So far I can load the data from a file into ... | No, you indeed cannot use bit pattern for std::string, you wouldn't want to anyway since it contains just a few pointers.
The usual approach I use in my projects is having POD structs for each record type.
Then the lowest layer responsible for {de}serialization converts only between PODs and bytes. Any C++ logic, like ... |
69,824,764 | 69,825,138 | How to create an object in C++ that can be referenced globally from C code? | I have a large program in C that I'd like to use certain C++ objects with such as maps.
I followed this post on how to call C++ from C and my two C++ look like this.
///map.cc
#include "map.h"
void* createMap()
{
std::map<int,int> *m = new std::map<int,int>();
return static_cast<void*>(m);
}
void putInMap(int ... |
//How do I let everyone use this pointer
void* ptr = createMap();
Not by declaring a global object with an initializer that is = createMap(). C doesn't allow the sort of dynamic initialization of globals that C++ has. The pointer must be initialized by a constant expression. And if you want to call createMap() in C ... |
69,825,453 | 69,825,650 | Rules for partial specialization of templates with nontype parameter(s) | Consider the following template
template <typename T, int v> void func(const T&x);
and I want to specialize it for some class A. Here is my try (by referring to this):
template <int v> void func<A, v>(const A&x);
However, that's illegal. My question is why this is illegal (which rule it breaks) and if that is against... | Function templates cannot be partially specialized, hence the error:
<source>:8:23: error: non-class, non-variable partial specialization 'func<A, v>' is not allowed
8 | template <int v> void func<A, v>(const A&x);
| ^~~~~~~~~~
You can for example partially specialize a type with operat... |
69,826,020 | 69,826,098 | Is it possible to insert a piece of code into an already existing C ++ program? | One of my programs generates a large file with c ++ code. Is there a way to call from another C ++ class to insert the generated code into it?
Here is a small example to make it clear what I am trying to achieve.
Generated file example:
FirstClass first = FirstClass();
first.add(*some data1*)
first.add(*some data2*)
..... | This is exactly the reason why #include exists: you write a piece of code in another file (functions, class definitions, constants, ...) and use them in another file.
More information can be found in this reference document.
|
69,826,919 | 69,827,194 | no overloaded function found | I have class KeyA that is from third party and will be the key in use. When I define a "<" operator, it complains:
error: no match for ‘operator<’ (operand types are ‘const KeyA’ and ‘const KeyA’)
some simplified code to show the issue:
#include <map>
using namespace std;
struct KeyA { // defined in somewhere else
... | One simple option is to just define your own comparator and supply that to the std::map template arguments instead:
struct config
{
using Key = KeyA; // type alias
struct KeyLess {
bool operator ()(const Key& lhs, const Key& rhs) const {
return lhs.a < rhs.a;
}
};
using Tab... |
69,826,969 | 69,827,294 | Why is std::mutex a standard-layout class? | [thread.mutex.class]/3:
[...] It is a standard-layout class ([class.prop]).
What is the reason for this requirement?
| Interoperability with the associated C interface. From N2320 (Multi-threading Library for Standard C++):
The C level interface has been removed from this proposal with the
following rationale:
As long as we specify that the key types in this proposal are standard-layout types (which we have done), WG14 is still free ... |
69,826,990 | 69,827,224 | std::construct_at which default initializes? | std::construct_at is equivalent to
template<class T, class... Args>
constexpr T* construct_at( T* p, Args&&... args ) {
return ::new (const_cast<void*>(static_cast<const volatile void*>(p)))
T(std::forward<Args>(args)...);
}
except that construct_at may be used in evaluation of constant expressions.
As you... |
In other words, is it possible to execute default initialization with placement new which can be used in constant expressions?
No, not without further language support. This is why P2283 proposes adding default_construct_at to be a magic library function that lets you do this.
|
69,827,109 | 69,827,185 | How is std::vector<bool>::reference assigned to bool type in c++? | I know std::vector<bool>::reference is a proxy class that is not apparent to users.
It is implicitly converted to bool when assigned to bool type.
How is it possible? type std::vector<bool>::reference is far far from the type bool.
Is there some compiler work under the hood?
Below is the code example
...
std::vecto... | std::vector<bool>::reference defines operator bool to allow implicit conversion to bool.
|
69,827,333 | 69,827,377 | container of string_view's - are they always null-terminated? | Let us give any data structure containing objects of std::string_view:
std::vector<std::string_view> v{ "abc", "def" };
std::deque<std::string_view> d{ "abc", "def" };
std::set<std::string_view> s{ "abc", "def" };
Is it guaranteed by cpp standard, that these containers store objects of class std::string_view which poi... | Yes, this is safe.
In general std::string_views don't have to be null-terminated, but here you explicitly initialized them with null-terminated strings.
The compiler is not allowed to remove null-terminator from a string based solely on the fact that it's assigned to a string_view.
The only case when it would be allowe... |
69,827,360 | 69,828,721 | If std::vector<bool> was rewritten to use the standard vector implementation, how would that break old software? | According to the answers in this question, std::vector<bool> implements "special" logic (to allow each boolean value to be stored in a single bit, rather than taking up an entire byte), and because of that, it doesn't quite fulfil the requirements of an STL container and its use is therefore discouraged. However, the ... | Firstly, that would be an ABI break. A major reason why changing anything from the standard library is difficult.
Secondly, anything using flip would break:
#include <vector>
int main() {
std::vector<bool> vec { true };
vec[0].flip(); // can't be done with regular bool
}
Thirdly, there would probably be other pro... |
69,827,899 | 69,833,394 | Save file dialog to save txt from array of numbers | I would save my 2 arrays of ints and floats respectively into a "csv style" .txt file using a TSaveTextFileDialog. I am trying to do that in C++ Builder with a Windows VCL application.
This is my attempt:
__fastcall TForm6::TForm6(TComponent* Owner)
: TForm(Owner)
{
saveTxtDlg = new TSaveTextFileDialog(this);
... | The dialog merely gives you filenames that the user has selected. You are responsible for actually opening those files and writing your data to them as needed.
For instance, have a look at things like TStringList::SaveToFile(), TFile::WriteAllText()/WriteAllLines(), TStreamWriter::Write()/WriteLine(), etc.
Try somethin... |
69,828,672 | 69,829,099 | For Loop That Starts At Middle Of Range And Loops Around | Is it possible to have a for loop that starts at the middle of a range and then loops around to the beginning of the range and continues until it loops through the whole range? For example, assuming we have a range of 0 to 63, I want the loop to start at 22, continue looping until it reaches 63, then start at 0 and lo... | I'd use two loop variables: one to count the number of repetitions and one to handle the desired index. Like this:
for (int i = 0, j = 22; i < 64; ++i, j = (j + 1) % 64)
// do something with j
Of course, in real code you'd replace the magic numbers (22, 64) with something that more clearly reflects the actual obje... |
69,828,955 | 69,829,052 | How to pass a class function to another within the same class? | I am using boost odeint in C++ to calculate a simple system of ODEs. Both the odesys and solver are methods of the same class. I pass the odesys as an argument to the integration function but I get a C2064 build error "term does not evaluate to a function taking 3 arguments" and refers me to an error in a library heade... | You should bind the object instance (e.g. this):
integrate_const(runge_kutta4<state_type>(),
std::bind(&myClass::odesys, this, _1, _2, _3), x, 0.0,
10.0, dt);
You can also use lambdas to achieve the same:
integrate_const(
runge_kutta4<state_type>(),
[this... |
69,829,760 | 69,829,812 | How can I invoke an overloaded () operator on the keyword this? | The following works but feels ugly when I do the (*this)(5) part.
struct MyStruct
{
void operator()(int a)
{
// Do something with "a"
}
void myFunc()
{
(*this)(5);
}
};
I will need to overload the () operator and use it from within other class methods.
| You have a few options:
(*this)(5)
this->operator()(5)
or just operator()(5)
Create a method that you call from within the operator(), e.g.:
void do_work(int a) { /* ... */ }
void operator()(int a) { do_work(a); }
void myFunc() { do_work(5); }
Whichever you choose is just a matter of personal taste.
Just for fu... |
69,829,913 | 69,830,155 | C++ find non-overlapping substring in string with position specifics | I am trying to figure out how to find count of non-overlapping substrings in string, but only those at the same distances. I managed to get number of non-overlapping substrings, but this is just subset of the requirement.
Example:
I have a string "aaaaaaaaaabaaaaaaba" and I want to count number of non-overlapping subst... | Your loop is doing a wrong thing: it tries to find substring starting from the last found offset + 2 (the length of aa).
After the first aa is found at the odd position, all subsequent attempts will also find odd positions.
This works:
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.fi... |
69,830,109 | 69,831,469 | Find an Edge by its vertices in an undirected graph [C++ BGL] | My question is very simple. I'm looking to find out an edge given the vertices it's connecting. The complicated way would be to iterate through all edges and compare each source and target with the vertices im using. I figured there would have to be a better way to do this which is why I'm asking
| It depends on your graph model: https://valelab4.ucsf.edu/svn/3rdpartypublic/boost/libs/graph/doc/graph_concepts.html
AdjacencyMatrix has what you want directly:
auto e = boost::edge(v, u, graph);
(where e, v and u are descriptors).
Assuming you have a non-bidirectional instance of AdjacencyList you will have to look... |
69,830,638 | 69,982,969 | Getting Oculus Quest Mac Address through c++ | I've been trying to get the Mac Address from an Oculus Quest 2, at first i found the FGenericPlatformMisc::GetMacAddress, and implemented that on a Blueprint Function Library exposing that as a Blueprint. Worked getting my windows mac address, but when i try to use this in a oculus build returns nothing. I know that th... | The Oculus runs Android 7+, so my guess would be that Oculus apps would be deliberately restricted from accessing it. From the Android developer docs:
MAC addresses are globally unique, not user-resettable, and survive factory resets. For these reasons, to protect user privacy, on Android versions 6 and higher, acces... |
69,831,043 | 69,831,075 | Why for loops beyond a point give unreasonable results in c++? | I'm trying to take the difference of the two rows using the for loop. There are total four rows, so the result would be simply 3 numbers after subtraction and summations. But the loop provide additional results which are unreasonable!! Does anyone know why it happens?
#include <iostream>
#include <vector>
using namesp... | Access to v at or past 4 in the first index or 3 in the second is undefined behavior.
If you are lucky, you get nonsense. If you are luckier, your program crashes when you test it. If you are unlucky, the program does any arbitrary action within its power.
In your case, you access up to v[4][5].
A programming executi... |
69,831,186 | 69,848,492 | VS2017 loads C++ project that was manually configured to x86 as a VS2010 project | I just changed a vcxproj file (C++) to have x86 as a platform for all solution build configurations instead of Win32, which seems to be the default for all C++ projects. The project loads fine but it shows up as a VS 2010 project in solution explorer. Based on discussions with my coworkers, my underlying assumption is ... | If you modified your .vcxproj Platform references to "x86", it won't work and is an "unknown platform" as far as Visual C++ is concerned. The actual 32-bit Platform name is "Win32" and has been for ages.
Only the "solution" system was updated to handle "x86" as an alias for "Win32".
TL;DR: Revert your changes to your v... |
69,831,285 | 69,831,354 | Pybind11 How to pass an n-dimentional numpy array from python -> c++ | I have a numpy array of numpy arrays of floats that I wish to pass to a c++ function that will read and modify the data as if it were a std::vector.
I am struggling to figure out how to do this.
What would the c++ argument type be for:
np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=float)
This type declaration: py:... | Pull in the Eigen library on the C++ side and use that for your matrix operations. std::vector is not a good abstraction for 2d matrices... either you have to write your own 2d indexing into a 1d vector, or you need something silly like std::vector<std::vector<>>, which performs very badly and is ugly besides.
pybind... |
69,831,385 | 69,833,388 | How to include a library which I installed with Homebrew | I have installed the boost library with homebrew and if I write:
include_directories(/opt/homebrew/Cellar)
link_directories(/opt/homebrew/Cellar/boost/1.76.0/)
add_executable(Project main.cpp)
target_link_libraries(Project boost)
And then include it in my script:
#include <boost/multiprecision/cpp_int.hpp>
using name... | To add a Boost header-only library, such as multiprecision with cmake, usually all you need to do is:
find_package(Boost)
link_libraries(Boost::headers)
In case Boost was not installed correctly, you might still add it with:
include_directories(/opt/homebrew/include)
or:
include_directories(/opt/homebrew/Celler/boos... |
69,831,646 | 69,831,950 | Cannot write an array in a Ubuntu device using C++ (Debug Assertion Failed. Expression (stream !=NULL)) | I am working on Windows and I am trying to write an array into a Ubuntu device using C++ in Visual Studio 2019. Here's a sample of my code:
int Run_WriteCalibTable(char *pcIPAddress, int iNumArgs, float *fArgs, int *iAnsSize, char *sAns)
...
...
...
char pcFolderName[256];
char pcFileName[256];
... | You never check that opening the file succeeds - and it most likely fails, which is why you get the debug pop-up. Your use of \ as directory delimiters may be the only reason why it fails, but you should check to be sure.
I suggest that you use std::filesystem::path (C++17) to build your paths. That makes it easy to cr... |
69,831,693 | 69,831,988 | Set the most significant bit | I'm trying to toggle the most significant bit of an unsigned int based on a bool flag. This is my code for an hypothetical K = unit64_t:
This is the Item class:
template<typename K>
class Item {
public:
K first;
Item() = default;
explicit Item(const K &elem, const bool flag = false) {
first = elem ... | An option using only bit operations:
template<typename T>
void Item(T& elem, bool flag = false) {
T mask = (T)1 << (sizeof(T) * 8 - 1);
elem = (elem & ~mask) | (flag ? mask : 0);
}
|
69,831,837 | 69,832,391 | How to multiply a sparse matrix and a dense vector? | I am trying the following:
Eigen::SparseMatrix<double> bijection(2 * face_count, 2 * vert_count);
/* initialization */
Eigen::VectorXd toggles(2 * vert_count);
toggles.setOnes();
Eigen::SparseMatrix<double> deformed;
deformed = bijection * toggles;
Eigen is returning an error claiming:
error: static assertion failed:... | The problem is you have the wrong output type for the product.
The Eigen documentation states that the following type of multiplication is defined:
dv2 = sm1 * dv1;
Sparse matrix times dense vector equals dense vector.
If you actually do need a sparse representation, I think there is no better way of getting one than... |
69,831,913 | 69,832,220 | C++ friend keyword not accessing non-static data member | I need to overload the ostream operator with new functionality for a doubly linked Skip List class.
When I cout the instance of my class, I want it to iterate through my the levels of my skip list, and wherever the head pointer is pointed to a nullptr I want it to print the level name and a status of empty.
Would look ... | SkipList::maxLevels_; refers to the static maxLevels_ member of the SkipList class.
So, if you need maxLevels_ to be the maximum level of all the instances of SkipList you have to declare it as static.
Otherwise in your overloaded friend function you have to use the private member of the list instance.
friend ostream& ... |
69,832,385 | 69,832,533 | Template type erasure | I am wondering whether there is a practical way of writing something like the following code using the C++17 standard:
#include <string>
#include <functional>
#include <unordered_map>
template <class Arg>
struct Foo
{
using arg_type = Arg;
using fun_type = std::function< void(Arg&) >;
fun_type fun;
... | Doing this with a compile-time check is, unfortunately, not feasible. You can, however, provide that functionality with a runtime check.
A map's value type can only be one single type, and Foo<T> is a different type for each T. However, we can work around this by giving every Foo<T> a common base class, have a map of p... |
69,832,507 | 69,832,881 | In OpenMP task dependencies does the dependency clause parameter need to point to an actual variable? | Consider this code:
include <iostream>
int main()
{
int x = 100;
#pragma omp parallel
{
#pragma omp single
{
#pragma omp task depend (in: x)
{ x += 1; }
#pragma omp task depend (out: x)
{ x *= 2; }
}
}
}
notice t... | The dependency x in your program is a storage location. This concept is not explicitly defined in the OpenMP 5.1 specification but the document states few important points about it ($1.4.1):
All OpenMP threads have access to a place to store and to retrieve variables, called the memory. A given storage location in the... |
69,832,684 | 69,832,757 | Nested virtual functions | Given the following situation:
struct A
{
const float x;
const float y;
A(float x, float y)
: x{x}, y{y} {}
};
class B
{
public:
B(const float& floating)
: floating{floating} {}
virtual float foo_x() const = 0;
virtual float foo_y() const = 0;
virtual A foo() const
{
return A... |
Am I invoking some undefined behavior by calling foo_x() and foo_y() inside the definition of foo() in B?
No. This is well defined and works the way you expect it to, as long as all regular preconditions for calling virtual functions are met.
The easiest mistake to make with regard to these preconditions is that the ... |
69,832,809 | 69,832,838 | Spawning a thread in derived class in C++ with factory pattern | I'm looking at using a factory pattern and spawning threads on instances.
Below is my code, and I get the following error:
error: invalid use of non-static member function ‘virtual void base::threadFunction()’
75 | thread t1(myClass1->threadFunction);
#include <memory>
#include <iostream>
#include <thread>
using... | Since those functions are non-static (i.e., they are called on objects), your threads need objects for them to call. Change this:
thread t1(myClass1->threadFunction);
thread t2(myClass2->threadFunction);
to this:
thread t1(&base::threadFunction, myClass1.get());
thread t2(&base::threadFunction, myClass2.get());
This ... |
69,833,084 | 69,833,147 | How would I make an underline exactly the length of any text inputted as well as capitalizing every letter | Sorry I'm really new to programming and need some assistance. How would I make this happen. This is the function I currently have.
void DisplayTitle(string aTitle) {
cout << "\t" << aTitle << endl;
cout << "\t--------------\n\n";
}
How would I go about making sure that no matter which title is inputted, every ... | You can use std::setfill combined with std::setw from <iomanip> as follows:
std::cout << std::setfill('-') << std::setw(title.size()) << "";
Here, you're telling the stream to use a padding character of '-', then a padded output size that's the length of your title, and then output an empty string. Because the string... |
69,833,705 | 69,833,818 | Least common multiple for 3 numbers in C++ | I've written some code to calculate LCM for 3 numbers. My question is:
why with line:
std::cout << "";
code does work, and without this line code doesn't work?
How it is possible that printing some text on screen, can affect on how program works? It is a matter of some buffering or smth. like this?
#include <iostream>... | In your NWD() function:
int NWD(int a, int b){
int r; // <-- notice this
while (r != 0){
if (a>b)
r = a-b;
else
r = b-a;
a = b;
b = r;
}
return a;
}
You declare r, but you didn't assign any value to r, so r is now uninitialized.
Then, you compare ... |
69,833,782 | 69,834,404 | member vector with base class pointers | I have a class with a vector as below:
#include <vector>
class Base{};
class Derived: public Base{};
class Foo{
private:
std::vector<Base*> vec;
public:
Foo() = default;
void addObject(const Base* b){
// vec.push_back(new Base(*b));
// vec.push_back(new Derived(*b));
... | If you want to create a clone of the object passed to addObject, you have essentially two options. 1) Have a virtual function clone in Base and Derived, or better 2) let the copy constructor handle it.
If you go for the second option, addObject need to the know the actual type of the passed object. This could be done w... |
69,834,681 | 69,839,645 | How to redirect a child component function into an child function in c++? | Hi I'm new on the platform (and I'm trully sorry for my bad english).
I'm trying to reduce the number of calls of a display by grouping them in a big Display function in a minigame.
Let me be more clear : I've got a display function in my sprite file
void SpriteComponent::Display(const Timing& timing)
{
impl->s... | I hope I've understood enough to produce a fine answer. So,
Is there any solution to get the SpriteComponent display to redirect on the LayerComponent display?
Yes, if you can inject those SpriteComponents (create an object and pass it to external code). Create a FakeSpriteComponent which is-a SpriteComponent and ove... |
69,834,682 | 69,834,787 | Specialization of function template without changing its prototype | Suppose A is some class and I have the following function template with a nontype argument:
template <typename T, int v> void func(const T& x);
Now I wish to have different implementations for different types T e.g. I want to have a general version of func for general types (general means types that do not have a spec... | Just let the type system do the work for you:
#include <iostream>
class A {};
// Default implementation
template <typename T, int v> void func(const T& x)
{
std::cout << x + v << "\n";
}
// Specialized for A
template <typename T, int v> void func(const A& x) //<-- matches A for argument T
{
std::cout << "Gro... |
69,834,685 | 69,837,358 | Can you forward declare an explicit specialization of undeclared template class? | In the class I am currently writing, I consider it to be very important that most of its private member variables remain const. As such, I have opted to use an initialization object that is not fully declared in the header file:
// foo.h
template<typename T>
class Foo {
const int *const memberVariable; // Importan... |
Foo(class FooInitializer<T> &&initializer);
Whereas you can declare (non-template) classes inside function declaration (int bar(struct S s);), I don't think you can for template classes.
I am trying to avoid introducing FooInitializer into the header's namespace due to essentially duplicate declarations of the membe... |
69,834,936 | 69,835,098 | Can't get Right aligned number triangle pattern giving space using setw in C++ | I want a right aligned number pattern using setw for giving spaces
either the spaces disappear when setw is less than no. of printed numbers or it makes any random pattern.
My Code is below:
#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
int space, n,i,j,k,l,m;
cin>>n;
for (k = ... | The first for loop is not necessary.
setw sets the field length for the next field (the field following setw). So if the next field is an empty string, setw(x) will just reserve x characters space. Also, the value x should be equal to n - i (if no. of characters to be printed is 1, you need (5 - 1) i. e. 4 spaces)
#in... |
69,835,146 | 69,835,475 | Best way to monitor for a key press without stopping a loop | I'm writing a program in C++ for Linux. I plan on using popen() to run another program. While I'm waiting for that program to finish, I want to be able to detect if the user presses keys on the keyboard so I know if they want to continue processing their files or if they want to pause after pclose(). What is the best w... | You can use a thread waiting for a key before calling popen, call popen, cancel the thread and check if any key was pressed before calling pclose.
An example using C (it is trivial to adapt it to C++), I'm ommiting error checks for brevity:
#define _XOPEN_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <unistd... |
69,835,349 | 69,835,370 | This declaration has no storage class or type specifier when Initializing static member | this is my code.
lib.hpp
class MainMenuDriver {
public:
static LiquidCrystal lcd;
static std::vector<std::string> menu_items;
static std::stack<std::string> menu_stack;
static std::stack<std::string> temp_stack;
// ...
main.cpp
#include "lib.hpp"
MainMenuDriver::lcd = LiquidCrystal(8, 9, 4, ... | You have to also specify the type when initializing the static data member lcd as shown below. Use
LiquidCrystal MainMenuDriver::lcd = LiquidCrystal(8, 9, 4, 5, 6, 7);
|
69,835,543 | 69,836,287 | Unclear on linking vs compilation | I am aware that many questions exist that address the same issue, but I have been unable to find one that answers my question. I understand the big picture difference between compilation and linking, the former translates each source file into machine code in the form of object files and the latter "links" these object... | Preprocessing happens before compilation. The preprocessor takes a one or more source files, and outputs another source file, which is then compiled. The preprocessor is a text-to-text transformer, it has nothing to do with linking.
It is conceptually possible to dump everything in one source file using a preprocessor,... |
69,835,935 | 69,837,305 | Is there a better object memory alignment for my class? | I have the following class and its alignment is 8 and the size is 40 bytes (compiled using gcc v11.2 64-bit).
class Foo
{
public:
inline Foo( ) = default;
/*
other member functions such as
move ctor and move assignment operator etc.
*/
private:
mutable std::vector< std::vector<char> ... | You can use bit-fields to control exactly how big your members are.
class Foo {
public:
Foo() = default;
~Foo() = default;
Foo(const Foo & other)
: matrix(std::make_unique_for_overwrite<char[]>(other.size())),
Y_AxisLen(other.Y_AxisLen),
X_AxisLen(other.X_AxisLen),
FillCharacter(othe... |
69,836,359 | 69,836,476 | how to call my boolean function so i can use if else for the cout in c++ | that my code
so in the main function I want to call the bool function but I don't know how
| You can use the following program:
#include <iostream>
using namespace std;
//forward declare the function
bool palindrome (string a);
int main() {
string a;
cout<<"Masukkan kata : ";
cin>> a;
if (palindrome(a) == true)//call the function and check the return value.
{
cout<<"Kata terse... |
69,836,479 | 69,836,568 | Vector push_back() and direct assignment using [] give different results | I'm trying to do this nQueens problem and my code looks like this:
class Solution {
public:
vector<vector<string>> ans;
bool canPlace(vector<string> &board, int row, int col, int n){
//upper left diagonal
int rowIndex = row;
int colIndex = col;
while(rowIndex >= 0 and colIn... | vector<string> board(n);
fills the vector already with n elements. If you now add additional! elements with push_back, you have a vector with two times elements. The first half are already in from the constructor of std::vector and the second half pushed in later.
If you use the default constructor
vector<string> boar... |
69,836,797 | 69,850,844 | Passing a class pointer as a function argument | Currently I am trying to create a function to implement modularization in the code like below.
[Code 1]
float CBitmapWaterMark::DrawPrintInfoText(HDC hDC)
{
StringFormat* stringFormat = new StringFormat();
// I'm trying to pass a stringFormat object to a member function of a class(CBitmapWaterMark).
str... | You'll need a using Gdiplus::StringFormat. The name "StringFormat" is fairly generic, so C++ has namespaces to prevent name collisions between 2 libraries. GDI+ puts its names in namespace Gdiplus.
|
69,837,162 | 69,845,956 | C++ double divided by double results in rounded number | I have the following calculation:
double a = 141150, b = 141270, c = 141410;
double d = (a + b + c) / 3;
cout << d << endl;
The output shows d = 141277, whereas d should be 141276.666667. The calculation consists of double additions and a double division. Why am I getting a result that is rounded up?? By t... | Here you can find multiple answers on the same problem with code snippets as examples. It does include what the guys said in the comments
|
69,837,169 | 69,837,257 | Does C++ guarantee this enum vs int constructor overload resolution? | Consider this example program:
#include <iostream>
typedef enum { A, B, C } MyEnum;
struct S
{
S(int) { std::cout << "int" << std::endl; }
S(MyEnum) { std::cout << "MyEnum" << std::endl; }
};
S f()
{
return A;
}
int main()
{
S const s = f();
}
Compiled with both clang and gcc this produces an execu... | Yes, S::S(MyEnum) wins in overload resolution because it's an exact match. While S::S(int) requires one more implicit conversion (integral promotion) from enum to int.
Each type of standard conversion sequence is assigned one of three ranks:
Exact match: no conversion required, lvalue-to-rvalue conversion, qualificat... |
69,837,224 | 69,837,465 | Is O3 a fixed optimization sequence? And how to change frame-pointer value in LLVM IR? | I use the following command to figure out the sequence of clang O3,
$ opt -enable-new-pm=0 -O3 -debug-pass=Arguments input.ll
and I get a very long optimization sequence.
Is that sequence same for all of code? Or O3 can change the order according to the source code?
And, I found that if I use -O0 flag to generate IR fi... | Yes, optimization sequence is the same for all inputs. But note that opt's -O3 may not be the same as clang's -O3.
As for disabling the frame pointer, you can remove it
with -fomit-frame-pointer when generating LLVM IR with clang:
$ clang input.c -emit-llvm -S -O0 -o fp.ll
$ grep frame-pointer fp.ll
attributes #0 = {... |
69,837,781 | 69,837,830 | how can i access private member += function in c++ | I learning c++ language to my currier.
The thing i have a question is how can i access private member value below code.
Fraction& operator+= (const Fraction& right);
Fraction& Fraction::operator+=(const Fraction& right)
{
numer = numer * right.denom + right.numer * denom;
denom = denom * right.denom;
normal... | The private scope in C++ prevents access from outside. It does not prevent access from objects of the same class. Therefore, the objects instantiated from class Fraction can access each other attribute without any prevention.
When you write
Fraction a, b;
a += b;
It is equivalent as
Fraction a, b;
a.operator+=(b);
T... |
69,837,916 | 69,837,941 | Using makefile in macOS terminal | I'm new to macOS terminal commands and have recently got introduced to makefiles while learning to program in C++.
The makefile that I was using had the following content:
fact:factorial2.o facth.o
c++ factorial2.o facth.o -o fact
facth.o:facth.cpp
c++ -c facth.cpp
factorial2.o:factorial2.cpp
c++ -c fact... | Makefiles use tab delimeters rather than 4 spaces. Replace the spaces with tabs on lines 2, 4, and 6.
|
69,838,047 | 69,838,637 | INET EnergyConsumer module's parameters new value never takes effect at runtime | I would request your help on this issue I'm facing on. Actually, I want to change the energyConsumer module's parameters at run time.
The scenario is that I should specify an amount of energy when the nodes are transmitting or receiving depending on the state of the radio.
I came through with the help of this piece of ... | The StateBasedEpEnergyConsumer module is not written in a way that it expects that certain parameters are changing during runtime (in fact almost none of the INET modules are). A parameter is usually read only once (usually during the initialization phase). After that point they usually store the value of the parameter... |
69,838,273 | 69,838,819 | Is it possible to use a union member as object storage? | I wonder whether we can use a union member as storage for an explicitly initialized and destructed object, such as in the following code:
struct X
{
X() { std::cout << "C"; }
~X() { std::cout << "D"; }
};
struct X_owner
{
union
{
X x; // storage for owned object
};
X_owner()
{
... | It is indeed valid.
[class.base.init]
9 In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then
[...]
otherwise, if the entity is an anonymo... |
69,838,353 | 69,887,316 | HeapAlloc hooking with miniHook, deadlock on Windows 10, works on Windows 7 | I have a most peculiar bug... I'm hooking HeapAlloc to log all calls and get the name the DLLs calling the API. The code works on Windows 7, but doesn't work on Windows 10. I use miniHook for hooking. Everything compiled with Visual Studio 2019, v142.
// BasicTest.cpp : This file contains the 'main' function. Program e... | So, answering my own question. I found the issue.
GetModuleHandleExA increments the module's reference count. Turns out, if you increment the reference count too much, there is a deadlock. I have no idea why... Adding the flag GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT fixes the issue.
|
69,838,583 | 69,838,897 | What are the advantages/disadvantages of std::optional over nullptr? | I looked several online std::optional documentary over the internet. However I could not be able to find any direct comparison between two cases below:
case 1:
SomePointer* foo::get_some_pointer(cont int value) {
auto result = myMap.find(value);
if (result != myMap.end()) {
return const_cast<SomeP... | The sole job of std::optional is to extend the type domain by an additional "null" value. Every pointer type T* already has a value considered "null" - nulltpr.
Thus, it's not a good idea to compare those two directly, because they answer different questions. Sometimes it's important to differentiate between "no result... |
69,838,615 | 69,839,119 | Storing different function pointers in one array? | If I have two functions like this:
void funcA(std::string str);
void funcB(int32_t i, int32_t j);
Can I store pointers to both of these functions in the same map? Example:
std::unordered_map<std::string, SomeType> map;
map.emplace("funcA", &funcA);
map.emplace("funcB", &funcB);
map["funcA"]("test");
map["funcB"](3,4)... | sorry for misunderstood, you can find a solution below.
#include <iostream>
#include <map>
typedef void (*customfunction)();
void hello() {
std::cout<<"hello" << std::endl;
}
void hello_key(std::string value){
std::cout<<"hello " << value << std::endl;
}
void hello_key_2(int value){
std::cout<<"... |
69,838,990 | 69,839,051 | How can I set 'null' value explicitly in integer array element in C++ | Like in Java, there's a way to set null values in array elements,
Integer[] arr = new Integer[5];
In here, arr is an Integer array with size 5 contains null by default
So can we do the same in C++?
| In Java, Integer is an object type, not a primitive type, so it's allowable to to set one to null. C++ doesn't have equivalent object types. A better analogue would be the following java:
int[] arr = new int[5];
Here you have a primitive int type which can't be set to a null value. In C++ it's the same thing.
The c... |
69,839,154 | 69,839,219 | How to split a string based on empty/blank lines? | I'm writing a c++ application (Qt Widgets) that is supposed to parse an .srt subtitle file. Each part of the file is separated by an empty line, like this:
1
00:00:08,000 --> 00:00:11,000
[Line]
2
00:00:56,034 --> 00:00:57,492
[Line]
[Another line]
3
00:01:13,676 --> 00:01:15,420
[Line]
Basically, I want to read the... | New lines are usually represented as \n.
To split the string when there are 2 new lines without anything between them, you can use \n\n as delimiter.
|
69,840,007 | 69,840,514 | Constexpr to initialize an array | I want to run a program (c++) where I keep an array of say size 10000 of the first 10000 primes which I call int prime[10000]. Now either I could start writing the first 10000 primes by hand and initialize the array like int prime[10000] = { 2,3,5....} but as you can imagine this would take a time.
Instead what I'm doi... | Instead of C-array, use std::array:
constexpr int prime_size = 10000;
constexpr bool is_prime(int i) {
for (int j = 2;j < i;j++) {
if (i % j == 0) {
return false;
}
}
return true;
}
constexpr std::array<int, prime_size> init_primes() {
std::array<int, prime_size> primes{};
... |
69,840,051 | 69,840,499 | I cannout out why I get the error "core dumped" C++ | I don't know why when I run this piece of code :
#include <iostream>
#include <cstring>
class Masina{
private:
long long putere;
int viteza;
double masa;
bool calificativ;
char* nume;
public:
Masina();//constuctor default
Masina(long long putere,int vit... | You're using c-style casts:
nume((char*)"o_marca")
That's dangeours. Don't. When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Simple c++: Live
#include <iostream>
#include <string>
struct Car {
long long mass = 2000;
int speed = 250;
double power =... |
69,840,060 | 69,840,226 | C++ Regex: Matching words after hyphens | I am a bit new to C++ regex and trying to make a regex work. Basically, I want to match "the pickle" in the following sentence:
I pick picked -- the pickle
To implement this, I am using the following regex --> std::regex reg3 ("(--)[\\s]*.+")
However,my output is the following:
-- the pickle
My desired outpu... | You can use the capture groups () to delineate submatches:
#include <regex>
#include <iostream>
int main() {
std::string txt = "I pick picked -- the pickle";
std::regex re(R"(--\s*(.+))");
std::smatch m;
if (std::regex_search(txt, m, re)) {
std::cout << "Full match: " << m.str() << "\n";
... |
69,840,271 | 69,851,831 | How to parse 8-digit date in C++? | I use std::get_time to parse dates from text. In most cases it is sufficient, but when reading dates with no separators (e.g. 31122021, with format "%d%m%Y") I always get a failure. I use this because I saw it described as an equivalent to python's strptime (https://stackoverflow.com/a/33542189/15061775) which does man... | This is a compiler specific issue. If this specific method needs to handle this specific input, then you have to use a different compiler.
Quoting this link ;
It appears that std::get_time in MSVC 14.0 does not parse undelimited date and time values, such as those found in the ISO-8601 basic format. The following cod... |
69,840,569 | 69,840,799 | How to find the 3rd bit of a number | I have a question with a problem in c++.
I have to create a program where I have to create one variable from Int and to cout<< on the screen "True" if the 3rd bit is 1.
My question is: How can I see what is the 3rd bit of that number; I've tried with bitset, but couldn't solve it. Please help me.
#include<iostream>
#in... | Checking if a given bit is set is a classic pattern that you will encounter in a great many codebase. So even if there are cleaner ways to do it in modern C++, it's still worth being able to at least recognise the old school pattern when it pops up:
// You will typically see bit masks predefined in constants or an enum... |
69,840,707 | 69,840,928 | cuda kernel gives incorrect results by grid size increase | I am testing a simple CUDA algorithm for timing and I came across a case that when I increase the grid size of the kernel it gives incorrect results:
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
/* we need these includes for CUDA's random number stuff */
#include <curand.h>
#include <curand_kernel.h>
#d... | There is a race condition in kernel myadd. The sum must only be set to 0 once. And it should not be set to 0 after some other threads added their value to it.
__global__ void myadd(const int *in, int *sum) {
if(threadIdx.x == 0){
sum[blockIdx.x] = 0;
}
__syncthreads(); // all threads wait until sum ... |
69,840,845 | 69,840,988 | How to use auto keyword in argument list in C++ 11? | How to replace auto keyword from the function parameter when there will be multiple type arguments called with this function? because I want to use -std=c++11 and I am getting this error in omnet++:
**error: use of auto in parameter declaration only available with -std=c++14 or -std=gnu++14**
void get_index(auto s_a... | void get_index(auto s_arra[], auto elem) {
//...
}
Would be valid only in C++20 (gcc error message is misleading)
previously, you use template the verbose way
template <typename T1, typename T2>
void get_index(T1 s_arra[], T2 elem) {
//...
}
and probably they use same type, so
template <typename T>
void get_i... |
69,841,145 | 69,841,232 | Destroy object in std::vector | I wan't to be able to destroy any object without loosing memory:
from:
`--------+--------+--------`
| item 1 | item 2 | item 3 |
`--------+--------+--------`
to:
`--------+--------+--------`
| item 1 | empty | item 3 |
`--------+--------+--------`
Used std::vector<T>::erase is what comes closest to it, but it doesn't... | You may not have destroyed objects in a vector. The vector will eventually destroy all elements and if any are already destroyed, then behaviour will be undefined.
Instead of a vector of MyClass, you could use a vector of std::aligned_storage and handle the construction and destruction of the MyClass objects onto the s... |
69,841,266 | 69,841,333 | Error "No Viable Conversion From Returned Value of Type 'int[2]' to function return type 'vector<int>'" | coder newbie here, I have an issue on HackerRank. It tells me to make a function which compares the elements of 2 arrays and returns 2 values in an array. However I get the "No Viable Conversion" error. When I change the type of 'scores' to vector, I get a compiler error, saying "Segmentation Fault". What I would like ... | The problem is that you created a vector of size 0(an empty vector) and then were trying to assign elements to its 0th and 1st index which didn't exist. You should use :
//pass the vector by reference instead of by value
vector<int> compareTriplets(const vector<int> &a,const vector<int> &b) {
int sA = 0, sB = 0;
vector... |
69,841,295 | 69,844,579 | In OpenMP how to specify task dependencies amongst functions invoked by different classes? Are global variables the only solution? | Lets say we have two classes:
class A
{
void run_all()
{
#pragma omp task
f1a();
#pragma omp task
f1b();
}
void f1a()
{ /*some code*/ }
void f1b()
{ /*some code*/ }
}
class B
{
void run_all()
{
#pragma omp task
f2a();
#pragma omp task
f2... | Using a global variable for such a use is probably not a good idea since it would create an hidden dependency (ie. "spooky action at distance") if multiple instance of A and B exist. One way to fix that is by using an explicit object to share a dependency between A and B. This explicit object can contain the storage lo... |
69,841,585 | 69,841,613 | ID:danglingTemporaryLifetime Using pointer to temporary.: C: conditionally change value of const char function parameter inside the function | Consider I have a C function:
MyFunction(const char *value, bool trigger)
Inside, depending on the value of the trigger variable, I'd like to either use a value provided to the function or simply overwrite it with some other const char string returned by a different function, e.g.:
MyFunction(const char *value, bool t... | No, you can assign to a function parameter exactly as you did. This doesn't affect the caller in any way.
|
69,841,743 | 69,842,085 | Code jumps into unreferenced shared object | My statically linked CryptoPP code (when called via Matlab mex on Linux) jumps into the libmwflcryptocryptopp.so binary (and then it freezes).
How can my code jump into a foreign .so instead of the statically linked library?
from function CryptoPP::SourceTemplate<CryptoPP::FileStore>::PumpAll2 in my vcpkg_installed/..... | TL;DR; your cryptocpp is getting LD_PRELOADed by Matlab, even if it is being linked statically.
A big hint towards what is going on is the path of the .so being loaded:
#3 0x00007ffff02e7129 [...] /usr/local/MATLAB/R2020b/bin/glnxa64/libmwflcryptocryptopp.so
Compared to the headers that were used during compilation:
... |
69,842,384 | 69,843,817 | C++: use std::string returned by a function: Using pointer to local variable that is out of scope | I've got the following function:
MyFunction(const char *value, bool trigger) {
if (trigger) {
std::string temporaryString = getTemporaryStringFromSomewhereElse();
value = temporaryString.c_str();
}
// do processing here
// I need `value` and `temporaryString.c_str();` to be alive and acc... | Simply move the declaration of the std::string out of the if block, up into the function block, eg:
MyFunction(const char *value, bool trigger) {
std::string temporaryString;
if (trigger) {
temporaryString = getTemporaryStringFromSomewhereElse();
value = temporaryString.c_str();
}
// d... |
69,842,416 | 69,844,778 | EVP_MD_CTX_destroy segfaults when linking to a dynamic lib using openssl 1.1 | Our application has always been using an in house developed shared lib which dynamically links to openssl 1.0 (the actual EVP_xxx symbols in our lib are undefined). So far so good.
This week I've been integrating a 3rd party shared library which has defined openssl 1.1 symbols in it, causing our openssl 1.0 code path t... |
How is this possible?
On Linux (and other UNIX) loading two different versions of openssl (or any other shared library) is unsafe and will almost always lead to bugs or crashes.
This is because (by design) UNIX shared libraries are not isolated from each other (unlike Windows DLLs). The first library to define any gi... |
69,842,447 | 69,842,569 | How to consume the soul of an object | I have a movable type that has no default constructor and I want to take away its internal data and destroy them. My thought was to std::move it to a temporary, and let the temporary destructor happen (to destroy the internal data), leaving the original now-empty object behind.
The closest I've got makes use of a litt... | Moving isn’t automatic, but non-const references are, so you can write
template<class T>
void dementor(T &t) {T(std::move(t));}
|
69,842,534 | 69,932,048 | Finding the heaviest path of an undirected graph | I am trying to solve a particular problem but i cannot find any suitable solution.
I'll explain ... I have a graph where each node has a numeric value.
Starting from a node of my choice, I have to find the path where the sum of the node values is the heaviest.
The peculiarity of this problem, however, is that I can onl... | I solved the problem using a dfs variant like this:
int dfs(vector<vector<int> >& g,
int* cost, int u, int pre){
vis[u] = true;
dp[u] = cost[u];
bool check = 1;
int cur = cost[u];
for (auto& x : g[u]) {
if (vis[x] && x != pre) {
check = 0;
}
else if (!vis[... |
69,842,635 | 69,842,789 | Where to put the custom exception classes? | Suppose that I have a class which you can see below (Please read the comments too):
Foo.h
#pragma once
namespace Bar
{
class Foo
{
public:
inline Foo( );
private:
char c;
inline static const std::unordered_set<char> CHAR_SET {'/', '\\', '|', '-'};
friend class Invalid_C_Exception;
};
} // end of na... |
1st question: Is the existence of this variable ok?
Globals are not generally a great idea, and since exception objects are copied to dedicated exception storage when thrown, I don't see any use for this particular global.
second question is that why does the compiler blame me for CHAR_SET being private
You have de... |
69,842,884 | 69,843,529 | Parsing Data chuck of a .wav file in c++ | I am using a SHA1 Hash to verify the authenticity of a .wav file. The SHA1 function I am using takes in three parameter:
a pointer to the authentication file with .auth extension
The data buffer read from the .wav file (which must be less than 42000 bytes in size)
The length of the buffer
for (int i = 0; i < size_bu... | You can put your shown for loop inside of another outer loop that runs until EOF is reached, eg:
size_t size;
int ch;
while (!feof(WavResult))
{
size = 0;
for (int i = 0; i < size_buffer; i++) {
ch = fgetc(WavResult);
if (ch == EOF) break;
DataBuffer[size++] = (char) ch;
}
if (s... |
69,842,907 | 69,843,047 | Why is this struct not the size I expect? | I am taking binary input from a file to a buffer vector then casting the pointer of that buffer to be my struct type.
The goal is for the data to populate the struct perfectly.
I know the size of all the various fields and the order they're going to come in.
As a result my struct needs to be tightly packed and be 42 by... |
Also, the first value lines up. After that, the data is incorrect.
uint32_t size: 24;
If you want to guarantee portably that this is three bytes with no padding before the next member, you're going to need to use a byte buffer and do the conversions yourself.
#pragma pack is an extension, and the packing of bitfield... |
69,843,231 | 69,843,304 | Reading a tab delimited text file with leading tabs on some lines | I am working to build a console-based spreadsheet app that takes in a UTF-8 encoded text file as input and outputs the results to the console.
Column values are separated by tabs and each new line is a new row. I am having some issues reading in the tab-delimited input text file where some of the lines (rows) are start... | You can use multiple std::getline() calls - one in the loop to read each line delimited by \n, and then put each line into a std::istringstream and use std::getline() on thaat stream to parse each column delimited on \t, eg:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main(int argc,... |
69,843,511 | 69,846,748 | Synchronization between two threads in shared folder | We have two threads one for writing and another for removing and one shared directory where one thread creates a new file and writes inside some message, but another scans this directory with a delay and reads the message from the new file and removes it.
So basically I understand that it should be synchronized because... |
if one created the file but has not written yet and another thread takes this empty file and will remove then we will have a problem
The solution to this problem is for the file to never be incomplete or invalid.
File creation followed by file population is not an atomic sequence. To make it atomic for readers, the w... |
69,843,859 | 69,845,465 | MFC(unicode): how do i convert a wstring filepath to a string path? | I have a application created with MFC, C++, and uses Unicode.
I have to load a texture with a wstring file path. This wstring file path is given by the system and I don't need to display it anywhere. I just need to pass it to a texture loading method. Unfortunately, the texture loading method(from a lib) only take a st... | I looked at the API stbi_load and it seems to take a const char* for the filename.
In that case, the laziest and best way is to use the CString classes.
#include <atlstr.h> // might not need if you already have MFC stuff included
CStringA filePathA(wstringPath.c_str()); // it converts using CP_THREAD_ACP
stbi_load(fi... |
69,844,240 | 69,844,489 | Can I assign a function pointer to a function with const parameters in C++? | If i have a funtion int foo(const int A), am I allowed to do the following coding?
int (*Mypointer)(const int);
Mypointer = &foo;
In addition, am i also allowed to do the following which is without const in the declaration of the function pointer ?
int (*Mypointer)(int);
Mypointer = &foo;
Another interesting case is... | They should both work.
const applied to a parameter passed by value has an effect ONLY in function body, making it immutable there.
|
69,844,567 | 69,844,745 | creating two outputs with Makefile | I want to create a makefile which runs program in C++ once with "CXXFLAGS = -std=c++11 -g -O3 -DTEST -fopenmp" and one time with: "CXXFLAGS = -std=c++11 -g -O3 -fopenmp"
at the end outputs two different files like P1-Test and P1. how can I edit this file?
CXX = g++
CXXFLAGS = -std=c++11 -g -O3 -fopenmp
ifdef code_cove... | My suggestion:
CXX = g++
CXXFLAGS = -std=c++11 -g -O3 -fopenmp
all: P1 P1-Test
@echo The program has been compiled
# implicit rule: create x from x.cpp
.cpp:
$(CXX) $(CXXFLAGS) $? -o $@
.PHONY: clean
clean:
$(RM) -r P1 *.dSYM
P1: main.o second.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o "$@" $^
P1-Test: CXX... |
69,844,585 | 69,844,786 | Read .dat binary file in c++ (depth map) | I'm very new to working with binary, so I don't know how to work with such files correcty.
I recieved a .dat file. I know it's a depth map - "The depth map is an array of double written to a binary file, 64 bits in size for each number.
The array is written line by line, the dimensions of the array are Width * Height, ... | You can't use >> to read the binary data. You need to use ifs.read. There are also different floating point formats, but I assume you and the creator of the map are lucky to share the same format.
Here's an example of how it could be done:
#include <climits>
#include <fstream>
#include <iostream>
#include <vector>
int... |
69,844,871 | 69,844,945 | CMake project with CPP and ASM | Try to make hello world project with external ASM function in CPP.
CMakeLists.txt
cmake_minimum_required(VERSION 3.11)
project(TestProject VERSION 0.1 LANGUAGES CXX ASM)
set_property(SOURCE foo.s APPEND PROPERTY COMPILE_OPTIONS "-x" "assembler-with-cpp")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED Tru... | You have declared foo to have C++ linkage but defined it to have C linkage. To fix this problem, declare foo to have C linkage instead:
extern "C" int foo(int x, int y);
|
69,845,195 | 69,846,112 | Why does location invariance matter for std::function? | I have been looking through GCC implementation of std::function (got there while debugging and went off on a tangent).
From what I can see it stores small types inside local storage and anything that does not fit it allocates via new operator.
However the constructor also does check the __location_invariant metafunctio... | It appears that libstdc++ uses the "location-invariant" property to simplify certain operations on std::function. Namely, the storage for the callable is provided by a union named _Any_data which contains a char array. This char array can either provide storage for a pointer to the actual callable (in case it's allocat... |
69,845,349 | 69,845,408 | Constructor from reference to parent class in polymorphism | Is it possible to make constructor in derived class which receives reference of the parent class pointing to another child class?
Child ch;
Parent &pr = ch;
Child ch1 = pr;
I guess it might be something like this:
Child(const Parent &pr){
*this = dynamic_cast<Child>(pr);
//Invalid target type 'Parent' for dynamic_cast... | It looks like you want to delegate to the Child's copy constructor:
Child(const Parent& pr) :
Child(dynamic_cast<const Child&>(pr))
// ^^^^^^^^^^^^
// note: const&
{}
If the Parent/Child relationship isn't the expected, you'll get a bad_cast exception.
Demo
|
69,845,570 | 69,859,753 | How to integrate Eclipse, systemc-2.3.3, and cygwin on Windows? | How to integrate Eclipse, systemc-2.3.3, and cygwin on Windows?
| Below I am going to share how I could integrate eclipse, systemc-2.3.3, and cygwin on a windows operating system.
Requirements:
Eclipse: you can download and install it from https://www.eclipse.org/downloads/
cygwin: you can download and install it from https://cygwin.com/install.html. Make sure to include the followi... |
69,846,283 | 69,855,064 | Visual Studio Code unable to compile cpp and Cuda (cu) files together | I have c++ program with multiple cpp files in VS code. Recently I learned some CUDA programming and tried to add a cuda functionality to this program. However, the nvcc compiler fails. If I try renaming the cu file to cpp I get an error:
expected primary-expression before ‘)’ token
cuda_hello<<<1, 1>>>();
I unders... | I was able to resolve this. Make sure that your nvcc is up to date (v 11) and update the tasks.json arguments as follows:
"args": [
"-std=c++17",
"*.cu",
"*.cpp",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
Make sure C... |
69,846,398 | 69,846,533 | How can I get VSCode to find gmp.h after it has been successfully installed on Windows 10? | After installing and following the instructions for GMP (using mingw64 since I am on windows) and verifying the installation was correct using make check I tried running the following code in VSCode using the command g++ -g \path\file.cpp -lgmpxx -lgmp -o \path\file.exe:
#include <gmp.h>
#include <iostream>
using name... | I don't know anything about GMP, but you seem to include the wrong header.
#include <gmpxx.h> worked for me.
|
69,846,437 | 69,846,487 | Why is this address 0xFFFFFFFF? | In my .h file:
extern std::vector<bool*> selectedContainer;
inline void InitSprite(Sprite* sprite)
{
bool* selected = new bool(false);
sprite->onMouseHover = [&](){
*selected = true;
};
sprite->onMouseNotHover = [&](){
*selected = false;
};
selectedContainer.push_back(selected);... | [&](){
The & means that the lambda captures its object by reference.
bool* selected = new bool(false);
This declares selected in automatic scope. This means that when this function returns selected goes out of scope and gets destroyed. Note that this means that the pointer itself is destroyed, and that has nothing to... |
69,846,749 | 69,847,225 | How to declare a concept for the member function and use it in the friend function | I came to the following example of using a concept, which checks if the member function is present in the class and then using this concept in the friend function. For example, to overload operator<< for a bunch of similar classes
#include <iostream>
#include <vector>
template<class T>
concept Sizable = requires(T a)
... | Concepts can't do that. They are part of the function template's declaration, and so are checked when you befriend the specialization for A<T>. The problem with that is that at the point of the friend declaration, the class is not considered completely defined. As a matter of fact, it's considered completely defined in... |
69,846,931 | 69,849,263 | __FILE__ gives different result when built with CMake/ninja than when built with CMake/make | __FILE__ gives either an absolute path (built with make) or a relative one (built with ninja). Here's a simple tester:
#include <iostream>
int main(int argc, char *argv[]) {
std::string thisFile = __FILE__;
std::cout << "thisFile = " << thisFile << "\n";
return 0;
}
And here's the equally simple CMakeLis... |
Does anyone know of a way to get the ninja build to behave in the same way that the make build does?
Use CMake 3.21, from 3.21 release notes:
The Ninja Generators now pass source files and include directories to the compiler using absolute paths. This makes diagnostic messages and debug symbols more consistent, and ... |
69,847,135 | 69,847,310 | CD Command in C++ command line | I'm trying to make a CD command for a shell I call POSH (Pine's own shell).
If the previous cd command didn't end in a /, it will append the two paths and throw (cd pine then cd src will error because path would be /home/dingus/pinesrc instead of /home/dingus/pine/src).
I know why this happens, but can't seem to fix it... | string(path).append(arg) is performing string concatenation. You are not appending any of your own slashes between filesystem elements. So, if the path is /home/dingus/, then cd pine would just append pine to the end producing /home/dingus/pine, and then cd src would just append src to the end producing /home/dingus/pi... |
69,847,204 | 69,850,315 | Cython: How to sort vector with closure | I'm using latest Cython with C++17 flag (above C++11 to have closure syntax) to GCC. This C++ sort in Cython doesn't seem allowing closure:
# File: myfunc.pyx
from libcpp.vector cimport vector
from libcpp.algorithm cimport sort
# cpdef to call from Python, it just wraps cdef anyway
cpdef myfunc():
# int is just ex... | In this case you don't actually need a "closure" - you don't capture any variables from the surrounding scope. Therefore for your particular example you could use a cdef function (which must be defined at the global scope):
cdef bool compare(double a, double b):
return a<b
sort(v.begin(),v.end(), compare)
That ob... |
69,847,787 | 69,865,098 | What is the idiomatic way to export a 3rd party static library dependency in CMake? | I have the following reduced CMake code for using Abseil in a library: (minimal repository to reproduce)
cmake_minimum_required(VERSION 3.20)
project(MyProject)
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules")
set(ABSL_PROPAGATE_CXX_STD ON)
find_package(absl REQUIRED)
add_library(MyStaticLibTarget... | TLDR: Follow the Conan docs, especially the cmake_find_package docs and skim the cheatsheet.
Following @Tsyvarev's advice in the comments, I used a different setup and made this work, you can see the final result in conan branch.
The steps are as follows:
Use Conan to download and install Abseil, using a project-local... |
69,847,862 | 69,847,972 | How to sort an array to start with 2 then 1 and then 3? | I've got this program that generates random numbers from 1 to 3 and put it into an array:
int main() {
int size;
cin >> size;
int *array = new int [size];
for(int i = 0; i < size; i++) {
array[i] = rand() % (2 + 1) + 1;
}
std::sort(array, array + size);
for(int i = 0; i < size; ... | You can create a custom compare function like this:
bool cmp(const int &lhs, const int &rhs)
{
std::map<int, int> compareValue{{1, 2}, {2, 1}, {3, 3}};
return compareValue[lhs] < compareValue[rhs];
}
int main()
{
int size{};
std::cin >> size;
std::vector<int> array(size); // using std::vector i... |
69,848,029 | 69,848,172 | is_copy_constructible typetrait gives wrong answer | In the below code, is_copy_constructible_v returns true, but MainClass' copy constructor is marked as deleted.
Trying to call the copy constructor is be a compilation error.
So how come that is_copy_constructible_v does not see it?
class BaseClass {};
class MainClass : public BaseClass {
public:
MainClass(MainClas... | MainClass has a MainClass::MainClass(const BaseClass& rhs), which makes constructing MainClass from a const lvalue possible, e.g.
const MainClass first{{}};
// This line will compile because MainClass::MainClass(const BaseClass& rhs) is usable
// a MainClass could be bound to const BaseClass&
MainClass second{first};
... |
69,848,231 | 69,848,281 | Can a non-aggregate class be a POD class C++ | From what I know if a class is not an aggregate then it is sure not a POD.
However in the following code
#include <iostream>
#include <type_traits>
class NotAggregate2
{
int x; //x is private by default and non-static
};
int main()
{
std::cout << std::boolalpha;
std::cout << std::is_pod<NotAggregate2>::val... | Prior to C++11, you'd be correct: POD types needed to be aggregate types, which in turn could not have private non-static data members. Post-C++11 however, POD types no longer need to be aggregates. Rather, they just need to satisfy the looser requirement of being a standard layout type, which only requires that all no... |
69,848,787 | 69,849,023 | How to implement the move function in C++? | I want to know the internals of the move function in C++.
For that, I aim to make my own implementation of the move function called move2.
Here is my implementation with prints to track memory allocation.
#include <iostream>
#include <vector>
using namespace std;
void * operator new(size_t size) {
cout << "New ope... | std::move() takes in a forwarding reference, and returns a T&& rvalue reference. Your move2() does neither. It takes in an lvalue reference, and returns a T by value.
Your code "works" due to copy elision avoiding a temporary object being created when your function returns a new object by value, thus allowing temp8 to ... |
69,849,126 | 69,849,225 | C++ how can i get the name in class to make it as a ranking system based on the time I input | Can I store my object in a class in a variable so that I can print the ranking name?
The question is to write a program that asks for the names of five runners and the time it took each of them to finish a race. The program should display who came in first, second, and third place. Only accept positive numbers for the ... | You can simplify your program by using std::multiset as shown below:
#include <iostream>
#include <string>
#include <set>
//using namespace std; //don't use this
class runner{
public:
std::string name; //use string instead of array of char
float time;
void input(){
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.