question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,944,767 | 70,947,619 | warning: control reaches end of non-void function [-Wreturn-type] removed when declaring method inline | With this code
enum EnumTypes
{
one,
two
};
int enum_to_int(EnumTypes enum_type)
{
switch(enum_type)
{
case one: return 1;
case two: return 2;
}
}
I get the following warning:
: In function 'int enum_to_int(EnumTypes)':
:14:1: warning: control reaches end of non-void function [-Wr... | In contrast to a non-inline function with external linkage, an inline function or a function with internal linkage (static) is guaranteed to be defined in every translation unit (odr-)using the function (or else the program is ill-formed).
The compiler is therefore just being "lazy" and doesn't emit a definition for th... |
70,944,859 | 70,946,713 | Memory leaks using JNI: are we releasing objects property? | IMPORTANT NOTE: This snippet of code is not a native function called from Java. Our process is written in C++, we instantiate a Java VM, and we call Java functions from C++, but never the other way around: Java methods never calls native functions, but native functions instantiate Java objects and call Java functions o... | Note the section Implementing Local References from the JNI specification:
To implement local references, the Java VM creates a registry for each transition of control from Java to a native method. A registry maps nonmovable local references to Java objects, and keeps the objects from being garbage collected. All Java... |
70,944,880 | 70,945,389 | Correctly move from a data member of a temporary object | Consider the following C++-Code
#include <iostream>
using namespace std;
struct WrapMe
{
WrapMe() { cout << "WrapMe Default Ctor of: " << this << endl; }
WrapMe(const WrapMe& other) { cout << "WrapMe Copy Ctor of " << this << " from " << &other << endl; }
WrapMe(WrapMe&& other) noexcept { cout << "WrapMe M... | WrapMe&& data()&& { return std::move(member); }
This doesn't actually move anything. It just returns a rvalue reference to the member. For example I could do
auto&& wrapMe2 = Wrapper2().data();
and now wrapMe2 will be a dangling reference or
auto w = wrapper2();
auto&& wrapMe2 = std::move(x).data();
Now I have a ref... |
70,945,481 | 70,945,678 | directory_iterator skip over inaccessible files folders Windows | I am trying to iterate over all the folders in my C:\ directory, and ONLY in the C:\ directory. Not in any subfolders. My current problem is that it includes inaccessible files and folders like swapfile.sys or System Volume Information when iterating. How can I check the flags or whatnot to exclude such objects?
for (c... | You can use fs::status(entry).permissions() to get the permissions of the current entry and choose whether to skip it according to its flag value.
for (const auto& entry : fs::directory_iterator(dir)) {
auto p = fs::status(entry).permissions();
if ((p & fs::perms::owner_read) != fs::perms::none)
directory.empla... |
70,946,223 | 70,946,553 | Why is constexpr of std::wstring().capacity() not equal to std::wstring().capacity()? | I'm not sure if I'm too naïve or simply too unknowing.
But why does the following differ?
constexpr auto nInitialCapacity1 = std::wstring().capacity();
const auto nInitialCapacity2 = std::wstring().capacity();
In Visual Studio 2022/17.0.5 the code above results in:
nInitialCapacity1 = 8
nInitialCapacity2 = 7
Why ... | Microsoft's STL disables short string optimisation in constant evaluated contexts, so it allocates memory instead.
The allocations are always one more than a power of two, so the capacity (which excludes the last L'\0') is always a power of two.
In the non-constant-evaluated version, the short string buffer can hold 8 ... |
70,946,268 | 70,947,984 | Is it possible to find the seed for GoogleTest to run a specific order if the order is known? | I have been given a list of 25 tests and a order to run them in that is supposedly causing a failure in the last test. Unfortunately the tool that was used to find this failure does not save the seed that was used by GoogleTests shuffle to trigger this order.
So I can of course just run the tests with shuffle and repea... | There is no such option to specify the order of the tests.
However, By default (i.e. if --gtest_shuffle is not enabled), they run in the declaration order.
I can think of three ways of achieving what you want:
Use your favorite scripting language (e.g. bash, python, nodejs, etc) and regular expressions to modify the ... |
70,946,571 | 70,947,634 | How can I parse a char pointer string and put specific parts it in a map in C++? | Lets say I have a char pointer like this:
const char* myS = "John 25 Lost Angeles";
I want to parse this string and put it in a hashmap, so I can retrieve the person's age and city based on his name only. Example:
std::map<string, string> myMap;
john_info = myMap.find("John");
How can I do this to return all of John... | I'm going to show you one way to do it using Boost:
Live On Coliru
#include <map>
#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>
#include <iostream>
namespace x3 = boost::spirit::x3;
using Name = std::string;
struct Details {
unsigned age;
std::string city;
};
using Map = std::map<N... |
70,946,996 | 70,978,374 | VSCode marks GPIO_TypeDef in HAL library as unknown | I have some functions that refer to GPIO_TypeDef struct from STM32_HAL library and in Keil I recieve no errors in compilation, but VSCode marks it as "unknown identificator" error. I fixed it with adding
#include "stm32f103xe.h"
to main.hand both Keil and VScode now take it with no problems, but maybe I had to change ... | I found answer in CubeIDE directives. Add theese to C_Cpp.default.defines
(You can simply do this through Settings->Extensions->C/C++->Defines)
__CC_ARM
STM32F1xx
USE_HAL_DRIVER
DEBUG
|
70,947,360 | 70,947,860 | String Literal in the temporary object? | I am beginner in C++ and its low-level layer (in comparison with Python and so on). I have read on StackOverflow that string literals go into the Read-Only data section (String literals: Where do they go?), but currently I am reading a C++ book (by Bjarne Stroustrup) and it is written in there that temporary objects en... | String literals are the objects that are referred to specifically with the syntax
"Hello "
or
"World"
That is what literal means, an atomic syntax for a value. It does not refer to string values in general.
String literals are not temporary objects. They are objects stored in an unspecified way (in practice, often in... |
70,948,513 | 70,949,326 | Dependent sibling subdirectories in CMake | My current project has the following structure:
root
|- parser
| |- include // a directory for headers
| |- src // a directory for sources
| |- parser.yy
| |- scanner.ll
| |- CmakeLists.txt
|
|- preprocessor
| |- include // a directory for headers
| |- src // a ... |
If then what is the syntax in CMake to use sibling subdirectory ?
There is no special syntax for this since normal (i.e. not IMPORTED) targets are global. If you define a library in one subdirectory, it may be used in any other via target_link_libraries.
For instance:
# parser/CMakeLists.txt
add_library(parser ...)
... |
70,948,614 | 70,948,859 | Problem with overloading a function for literal strings | I have a template function that handles rvalues arguments. The argument is supposed to expose a certian function. For those rvalues that do not have this function, I need to use template specialization to handle the exceptions. The problem I have is with string literals. Here's a short example of what I am trying to do... | Note that "test2" literal is an lvalue, while char *&&x is an rvalue reference and cannot be bound to an lvalue.
|
70,948,707 | 70,948,730 | C++: Is a + b + c always equal to c + b + a? Assuming a,b,c are double | I have two vectors of double. The value of the double is between -1000 and 1000.
Both vectors contain the same numbers, but the order is different.
For example
Vector1 = {0.1, 0.2, 0.3, 0.4};
Vector2 = {0.4, 0.2, 0.1, 0.3};
Is there a guarantee that the sum of Vector1 will be exactly equal to the sum of Vector2, assum... |
Is there a guarantee that the sum of Vector1 will be exactly equal to the sum of Vector2, assuming the sum is done via:
No, there is no such guarantee in the C++ language.
In fact, there is an indirect practical guarantee - assuming typical floating point implementation - that the results would be unequal. (But compi... |
70,949,064 | 70,953,031 | Count elements in texture | I have a 3D texture of 32-bit unsigned integers initialized with zeroes. It is defined as follows:
D3D11_TEXTURE3D_DESC description{};
description.Format = DXGI_FORMAT_R32_UINT;
description.Usage = D3D11_USAGE_DEFAULT;
description.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
description.CpuAcce... | You will have to read back the texture to the cpu with the ID3D11DeviceContext::Map API
https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-map
You will get out a void* you will cast to uint32_t* which will point to the start of your data.
You need to get better a looking up the Direc... |
70,949,264 | 70,954,480 | If statement in a template only run the first if-statement - QT | template <class T> void IOcalibrationWindow::setChildIntoIOcalibrationObject(int i, QString firstChildName, QString lastChildName, QString firstIocalibrationMethodName, QString lastIOcalibrationMethodName){
/* Get the index as string */
QString index = QString::number(i);
/* Create the UI field name */
... | I'm not entirely sure what you're trying to do but, from the code that's given, why can't you simply split out the uIchild->* calls into a couple of functions overloads? That would result in something like (untested)...
QGenericArgument fetch_data (QDoubleSpinBox *p)
{
return Q_ARG(double, p->value());
}
QGenericAr... |
70,949,454 | 70,949,496 | How do I open a file in main and then read from the file in another function? | In my main function I want to open a txt file while not hard-coding the file name, then call another function to read from the txt file.
I've tried to pass it as an argument according to another question thread, but it's solutions don't seem to work for me. The thread I looked at.
Sorry if this is an obvious question, ... | An std::ifstream object cannot be copied, so you cannot pass it by-copy to a function expecting it by-value.
But you can pass it by-reference without any problem:
int readfile(double &a, double &b, double &c, ifstream &filein)
As mentioned by @RemyLebeau in the comments, it is also preferable to take a std::istream& ... |
70,949,466 | 70,949,515 | How can I apply target-specific compiler and linker flags to subdirectories in CMake? | I am using CMake for a STM32 project as the project is outgrowing a plain Makefile. My directory structure looks something like what's below. I have an executable defined in the root CMakeLists.txt and somelib compiled as an OBJECT library which is added to the main CMakeLists.txt using add_subdirectory.
CMakeLists.txt... |
I'm hesitant to put the microcontroller-specific flags in that toolchain file as well since this project could expand to where I'd want to run my project on a different microcontroller.
So don't be hesitant and do that. And when you will move to a different microcontroller, you will have a different toolchain file fo... |
70,949,593 | 70,958,888 | Using htons() in my code puts all zeros in the buffer and I don't understand why | I need to use htons() in my code to convert the little-endian ordered short to a network (big-endian) byte order. I have this code:
int PacketInHandshake::serialize(SOCKET connectSocket, BYTE* outBuffer, ULONG outBufferLength) {
memset(outBuffer, 0, outBufferLength);
const int sizeOfShort = sizeof(u_short);
... | Converting endianess of a 16 bit number and storing it in a byte array is trivial, there is no need for library functions. Assuming 32 bit CPU:
uint16_t u16 = ...;
uint8_t out[2];
out[0] = ((uint32_t)u16 >> 8) & 0xFFu;
out[1] = ((uint32_t)u16 >> 0) & 0xFFu;
The casts and u suffix are there as a good habits to block i... |
70,950,064 | 70,950,094 | While (true) forever loop expected body function error | I'm new here. I am trying to do a forever loop with while (true) but can't seem to get it working. I have tried iterations without int main(void) as well.
#include <cs50.h>
#include <stdio.h>
int main(void)
while (true)
{
printf("goddamnit\n")
}
~/ $ make goddamnit
[clang -ggdb3 -00 -std=c11 -Wall -Werror -Wextra -W... | You are missing {} braces around your main() function's body, it needs to look more like this instead:
#include <cs50.h>
#include <stdio.h>
int main(void)
{ // <-- add this
while (true)
{
printf("goddamnit\n")
}
} // <-- add this
Block statements like if, for, while, etc can omit {} when their bod... |
70,950,122 | 70,950,188 | GetWindowTextA returns gibberish with unrelated code changes | I've tried this code which was supposed to get all window titles and positions and store them in vectors (here window titles are printed) but the outputs seemed completely random:
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <vector>
std::vector<LPSTR> buffs;
std::vector<int> rectposs;
BOOL CA... | Your buff variable is an uninitialized pointer, it doesn't point anywhere meaningful. So your call to GetWindowTextA() is writing to random memory. To fix that, you need to allocate actual memory for it to write to.
After fixing that, you have another problem - you are pushing the same pointer into the buffs vector o... |
70,950,130 | 70,962,891 | Suggestion for a pattern involving bits using bit manipulation | I currently have a structure like this
struct foo
{
UINT64 optionA = 0;
UINT64 optionB = 0;
UINT64 optionC = 0;
}
I am attempting to write a function for comparing two objects of foo based on optionA , optionB and optionC. Essentially what I would like the function to do is check if optionA is the same in both i... | It would be simpler and more readable to just have a comparison function that directly compares the data members in the right order, but if having bit masks that store which data members are bigger is helpful for some other reason then here is how I would do it:
foo compare(foo x, foo y)
{
// needs to hold status f... |
70,950,267 | 70,950,291 | Why char is unsigned and int is signed by default? | I'm using gcc as my c++ compiler and when I declare a variable of int datatype then it is taken as signed by default. But in case of char it is taken as unsigned.
Why is that ?
Because in xcode IDE char is taken as signed by default.
#include<iostream>
using namespace std;
int main() {
system("clear");
int x;
... | char is an unsigned type on your system, because the people who implemented your system chose that it should be unsigned. This choice varies between systems, and the C++ language specifies that either is allowed. You cannot assume one choice if you wish to write programs that work across different systems.
Note that ch... |
70,951,670 | 70,955,721 | Using Constructor v/s static method for basic linked list | I've tried implementing a basic linked list in my first try I implemented a static method (insert) for inserting data and pointer to the next element like shown below:
#include <iostream>
using namespace std;
class Node{
public:
int data = NULL;
Node* next = nullptr;
Node(){}
... | Let's inline insert:
Node::insert(x, a, b) is equivalent to
b->data = x;
b->next = a;
Thus,
Node::insert(1,second,head);
Node::insert(2,third,second);
Node::insert(3,nullptr,third);
is equivalent to
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = nullptr;
N... |
70,951,808 | 70,951,846 | Example of useful downcast with static_cast which does not produce undefined behaviour | I am wondering about a short code example of an application of downcast via static_cast, under conditions where there is no undefined behaviour.
I have looked around and I found quite a few texts (posts, Q&A, etc.) referring to fragments of the standard, explaining, etc.
But I found no examples that illustrate that (an... | A very basic example:
class Animal {};
class Dog : public Animal {};
void doSomething() {
Animal *a = new Dog();
Dog *d = static_cast<Dog*>(a);
}
A more contrived example:
class A { public: int a; };
class B : public A {};
class C : public A {};
class D : public B, public C {};
void doSomething() {
D *d = new ... |
70,952,369 | 70,952,411 | How did this loophole around const member function worked? | In the below code we try to multiply each element's data in the list by 2 and assign it. But the apply function is a const function therefore should not be able to change the values of member fields. Output for the fifth line in main is
6
4
2
2
4
So code below succeeds in changing the values as intended and I can't fi... | The key is logical vs bitwise constness. The head data member is a non-const pointer to non-const Node: the const correctness of the apply member function is bitwise constness:
you cannot change what the head data member (pointer) points to from a const-qualified member function.
You can, however, mutate the Node obj... |
70,952,498 | 70,982,564 | Direct2D Error NO_HARDWARE_DEVICE When Injecting Dll Into Another Process | I have a native target application that renders something by using Direct3D11. I want to extend the functionality of the target by injecting a DLL and hooking some APIs(not important to mention but it is XInputGetState). When DLL is injected, it also creates a window and provides some useful information. To render the ... | Put directly the D2D creating function into new thread by CreateThread in DllMain.
|
70,952,646 | 70,962,382 | Why is C++23 stacktrace_entry different from source_location? | class stacktrace_entry {
public:
string description() const;
string source_file() const;
uint_least32_t source_line() const;
/* ... */
};
struct source_location {
// source location field access
constexpr uint_least32_t line() const noexcept;
constexpr uint_least32_t column() const noexcept;
constexpr ... | The answers from the proposal author.
Regarding returning std::string:
As it is stated in P0881R7: "Unfortunately this is a necessarity on some platforms, where getting source line requires allocating or where source file name returned into a storage provided by user."
Regarding column:
Most popular solutions for no... |
70,952,653 | 70,952,935 | C++ program where user will input names and decide which gender (M/F) to show | Using c++ I need to make a program using map in c++ where the gender (M or F) is the key of 6 input names, and then it will ask the user to choose what gender to display (Male or Female). I am stuck with this, I do not know what to do next.
#include <iostream>
#include <set>
using namespace std;
int main(){
set<pa... | You can try "set" instead of map.
#include <iostream>
#include <set>
using namespace std;
int main(){
set<pair<char,string>> s;
cout<<"Enter 6 gender and name : "<<endl;
char gender; string name;
for(int a=1; a<=6; a++){
cin >> gender; getline(cin, name);
s.insert({gender,name});
}
set<pair<char,string>>::... |
70,953,123 | 70,953,518 | Envoy access logs format validation | We are using envoy access logs
https://www.envoyproxy.io/docs/envoy/latest/configuration/observability/access_log/usage , does envoy validate the fields that are passed to the access logs, e.g. the field format.
I ask it from basic security reason to verify that if I use for example %REQ(:METHOD) I will get a real http... | I'm not sure I understand the question. Envoy doesn't have to validate anything as it is generating those logs. Envoy is HTTP proxy who receives the request and does some routing/rewriting/auth/drop/.. actions based on the configuration (configured by virtualservice / destinationrule / envoyfilter if we're talking abou... |
70,953,345 | 70,953,871 | Can I extern the entire namespace? | Is there a method to declare a namespace with the extern modifier so that the namespace's entire content is externally linked?
| You seem to be asking two questions. One regarding external linkage and one regarding the extern specifier.
Regarding the linkage, there is not really a need for such a syntax.
External linkage is already the default at namespace scope, whether in the global namespace or another namespace, except for const non-templat... |
70,953,755 | 71,025,516 | Subset columns of sparse eigen matrix | I want to take subset columns of some sparse matrix (column-major)
As far as i know there are indexing stuff in Eigen.
But i cannot call it for sparse matrix:
Eigen::SparseMatrix<double> m;
std::vector<int> indices = {1, 5, 3, 6};
// error: type 'Eigen::SparseMatrix<double>' does not provide a call operator
m(Eigen::al... | The SparseMatrix actually does not provide any operator(), so this cannot be done.
EDIT: The following was aimed at an older version of the question.
In case your actual use case also has the property that the columns you want to access are adjacent you can instead use
SparseMatrix<double,ColMajor> m(5,5);
int j = 1;
i... |
70,954,015 | 71,044,310 | Can I use IDXGIFactory2::CreateSwapChainForHwnd for directx 11.0 | As I undrestood, IDXGIFactory2::CreateSwapChainForHwnd was added in DXGI 1.2 API so if the method D3D11CreateDevice will return pFeatureLevel equal D3D_FEATURE_LEVEL_11_0 we able to use only DXGI 1.1 API, therefore we should call IDXGIFactory::CreateSwapChain instead of IDXGIFactory2::CreateSwapChainForHwnd. Am I right... | My guess here is that your customer is running Windows 7, and is missing the DirectX 11.1 Runtime which is installed by the KB2670838 update.
See Microsoft Docs, as well as this blog post and this follow-up post.
It's probably best to just tell customers you require KB 2670838 if they are using Windows 7. Supporting th... |
70,954,719 | 70,954,798 | why socket is ready to read only after thousands of iterations? | I am writing my http server. I use select function and see that socket is ready to write any time, but can be read only after thousands of iterations. If I use select(Max+1, &rfd, NULL, NULL, NULL), I do not have such problem. Why it is ready to read only after so many iterations?
int iteration = -1;
while (true)
{
... | A socket will always be writable, unless you fill up its buffers.
So select will return immediately for every call, with all the sockets marked as writable.
Only add sockets to the write-set when you actually have something to write to them. And once you have written all you need, then remove them from the set and don'... |
70,954,866 | 70,955,091 | What is the best practice to check if an object is null in C++ | I am working on a simple example. Let s say that I have an object Object my_object and I want to check if the object is null.
Therefore, I instantiate the object:
auto my_object = createMyObject(param_object_1);
The idea, is to check whether the object is null or not. If I am not mistaken (I am really new in C++), I h... |
I want to check if the object is null.
Congratulations, your Object object is not null. null is not a possible value for object to be.
A close analog might be to test that it is different to a default-constructed Object, if Object is default-constructable.
EXPECT_TRUE(my_object != Object{})
|
70,955,074 | 70,955,206 | Can't properly insert a pair generated in code into a std::map | I have a weird problem. I have a map in C++ defined like this as private in a class.
std::map<const char *, GameObject *> GameObjects;
I have a function that adds pairs to the map.
void myClass::Add(const char *name, GameObject *object)
{
GameObjects.insert(std::make_pair(name, object));
}
It works fine if I add ... | A string literal has a different pointer value to a return value of malloc. The map will do lookup with std::less<const char *> which compares pointer values, it does not compare text.
Use std::string, and don't use malloc or owning raw pointers.
std::map<std::string, std::unique_ptr<GameObject>> GameObjects;
void myC... |
70,955,759 | 70,955,836 | How to get around calling base class constructor from derived class with the same arguments? | I want to use a base object that defines an "interface" and then have derived objects implement it. Every object is initialized with its name which is always the same process: Writing to a member "name_" with parameter passed to the constructor. I want to have derived objects behave exactly the same way as the base obj... | You may use a using-declaration to
Using-declaration
[...] introduce base class members into derived class definitions.
[...]
Inheriting constructors
If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member acc... |
70,956,681 | 70,956,856 | Function for a specific numeric sequence without any parameters | I got an university task which i am totally stuck on. Normally I wouldn't post about it here, but none of my colleagues has any idea how to solve it.
The Task:
Design an algorithm "NEXT", which delivers the subsequent value of the numeric sequence {0,3,5,6,9,10,12,15,18,20,21,...} as function value whenever it is call... | The sequence consists in all multiples of 3 or 5, in increasing order.
|
70,956,747 | 70,969,314 | Build tesseract as DLL Dynamic link library | I'm using this .NET wrapper https://github.com/charlesw/tesseract and I wanted to update the included tesseract and leptonica DLLs but after a long google search I was not able to generate them from the original tesseract and leptonica github repositories.
I already ask on the charlesw repository but did not get any re... | There are several tutorials you can follow:
https://bucket401.blogspot.com/2021/03/building-tesserocr-on-ms-windows-64bit.html
http://spell.linux.sk/building-minimalistic-tesseract
https://github.com/tesseract-ocr/tessdoc/blob/main/Compiling.md#windows
|
70,956,820 | 72,649,815 | How can I use CMake on command line? - Windows | I want to run CMake on a Windows machine on the command line. The problem is that using Visual Studio as the generator works fine, but when using Ninja, CMake cannot find the specified compiler (cl.exe). I have been able to get around this by calling vcvarsall.bat x64 on the command line before I run the cmake command,... | I have found several workflows to simplify this process for me:
I found that the comment by Alan Birtles is the most user friendly approach to improving my workflow. The recommendation was to use the CMake Tools extension for VS Code which easily scans your system for compilers and you can use options in the bottom ba... |
70,957,213 | 70,957,616 | How can I add backspace? | My professor is asking me to make a program that asks for email and password that while the user is typing its password the characters will be changed into *, My problem is whenever I press backspace it continues to print * and not deleting it. Please help me how this program will delete the previous character and not ... | You can check if the user presses the backspace (character code 8) and if the do print the backspace character '\b' to move the cursor back by one, followed by ' ' to overwrite the '*' and then another backspace character the move the cursor back again. Of course making sure to also delete the last character from the p... |
70,957,598 | 70,957,700 | disable code from compiling for non integral types | #include <iostream>
#include <type_traits>
#include <math.h>
template<typename T>
void Foo(T x)
{
if(std::is_integral<T>::value)
{
rint(x);
}
else
{
std::cout<<"not integral"<<std::endl;
}
}
int main()
{
Foo("foo");
return 0;
}
Does not compile because there is no suit... | In c++17 you could use if constexpr instead of if and it would work.
In c++14 you could specialize a struct to do what you want
template<class T, bool IsIntegral = std::is_integral<T>::value>
struct do_action
{
void operator()(T val) { rint(val); }
};
template<class T>
struct do_action<T, false>
{
void operato... |
70,958,035 | 70,971,174 | short_alloc with _GLIBCXX_FULLY_DYNAMIC_STRING disabled | I wonder if anyone has run Howard Hinnant's short_alloc when libglibc++ has _GLIBCXX_FULLY_DYNAMIC_STRING=1. I am stuck on how to workaround this error:
/usr/include/c++/9/bits/basic_string.tcc:596:30: error: no matching function for call to 'myapp::short_alloc<char, 131072>::short_alloc()'
596 | if (__n == 0 &... | The point of this allocator is to use stack memory. arena_type is used to reserve some stack memory for the allocator.
The allocator instance needs to know which arena to use. Therefore you cannot default-construct the allocator and by extension the string.
You always need to provide a reference to the arena to use whe... |
70,958,162 | 70,958,498 | SFINAE detection: substitution succeeds when compilation fails | I wrote a simple SFINAE-based trait to detect whether a class has a method with a specific signature (the back story is that I am trying to detect whether a container T has a method T::find(const Arg&) - and if yes, then store a pointer to this method).
After some testing I discovered a case where this trait would give... | The issue you're describing is not due to the fact that SFINAE doesn't work properly with function templates (it does). It has to do with the fact that SFINAE can't detect whether a function body is well-formed.
Your approach should work just fine when it comes to detecting that std::set<std::string> does not have a fi... |
70,958,269 | 70,960,120 | Disable CTS flow control on windows COM port | I am using SetCommState to configure a COM port.
if (!BuildCommDCBA(
"baud=9600 parity=N data=8 stop=1",
&dcbSerialParams))
return;
SetCommState(myCOMHandle, &dcbSerialParams);
This appears to enable the CTS flow control, which my hardware does not support
... | According to MSDN:
The BuildCommDCB function adjusts only those members of the DCB structure that are specifically affected by the lpDef parameter...
So you need to make sure all the other fields have acceptable values. The simplest way is to just initialize with
DCB dcbSerialParams = { 0 };
This should disable all ... |
70,958,419 | 70,958,764 | Function pointer which accepts both with and without noexcept | I have some utility code that I've been using for years to safely call the ctype family of functions, it looks like this:
template<int (&F)(int)>
int safe_ctype(unsigned char c) {
return F(c);
}
And is used like this:
int r = safe_ctype<std::isspace>(ch);
The idea being that it handles the need to cast the input ... |
Now that in C++17 and later, noexcept is part of the type system, this is a compile error! Because all of the ctype functions are now noexcept.
It is not a compile error. Pointers to noexcept functions are implicitly convertible to pointers to potentially throwing functions, and thus the template accepting a pointer ... |
70,958,920 | 70,959,877 | Storing template abstract classes in std::vector | I am trying to translate some Java code into C++ and I am having some trouble with the type system.
I have a interface/pure virtual class which represents a column in a table, and I want the table to be a vector of these generic columns:
template<typename T>
class IColumn {
public:
virtual const std::string& name()... | IColumn seems strange, you can indeed go with template:
template <typename T>
class Column {
public:
Column(std::string name, std::vector<T> data) :
m_name(std::move(name)),
m_data(std::move(data))
{}
const std::string& name() const { return m_name; }
std::size_t size() const { return m_d... |
70,959,558 | 70,971,954 | boost asio broadcast not going out on all interfaces | If set up a program with boost asio.
Broadcasts are working fine, if only one network interface is present.
However, if there are more network interfaces each broadcast is being sent on one interface only. The interface changes randomly. As observed by wireshark.
I'd expect each broadcast to go out on every interface.
... | As suggested by Alan Birtles in the comments to the question i found an explanation here:
UDP-Broadcast on all interfaces
I solved the issue by iterating over he configured interfaces and sending the broadcast to each networks broadcast address as suggested by the linked answer.
|
70,960,205 | 70,961,067 | Syntax error on my member initializer lists | I have the following class:
class MathNode {
protected:
std::list<std::pair<std::string, MathNode*> > myChildren;
public:
MathNode()
: myChildren{} // line 15
{} // line 16
MathNode(std::string l, MathNode* c)
: myChildren{ std::make_pair(l, c) }
{}
MathNode(std::string l1, MathNode* c1,
... | The solution was to add a rule for parser.o to compile parser.cc:
parser.o: parser.cc
g++ -std=c++11 -g -c $< -o parser.o
|
70,960,372 | 70,960,488 | What is the purpose of back() in c++? | Here is the code:
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> list = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
int total = list[s.back... | As I have understood the string s contains a number using Roman numerals as for example "IV" that represents 4. So the expression s.back() yields the last symbol in the string that is 'V'.
That is the string is traversed from right to left.
In other words, for sequential containers with rare exceptions the member funct... |
70,960,950 | 70,961,203 | What is time complexity of my sorting algorithm? | It is similar to insertion sort with swap, and for three standards. For example if user inputs 1,2,3 the priority is to sort by height, then weight and then age. I have comparator as well.
The thing is I am not sure about time complexity. Is it going to be O(n^2)? If yes can anyone explain why? Ofc I'm talking about th... | Yes, it's a quadratic sorting algorithm as you stated in your question. The reasoning is this:
The main part of the code runs a nested loop as follows:
for(int i = 1; i < n; i++) {
int j = i-1
while (j >= 0...
where you do constant work inside the inner loop.
In the worst case, the inner loop iterates i times fo... |
70,961,296 | 70,961,928 | Defer/cancel execution of functions and analyze their arguments | I'm trying to write external draw call optimization, and for that I need to collect hooked calls, store their arguments to analyze them later on.
I've been able to make deferred calls, and somewhat readable arguments, stored in tuple, but I need to read arguments from base class and after thorough googling I can't find... | You could provide a virtual function returning void* and use it in a template, but type safety goes down the drain: Should you ever get the type wrong, you'll end up with undefined behaviour.
For getting element using an index you can use a recursive helper template that compares with one index per recursive call.
clas... |
70,961,375 | 70,961,575 | C++ vs. python: daylight saving time not recognized when extracting Unix time? | I'm attempting to calculate the Unix time of a given date and time represented by two integers, e.g.
testdate1 = 20060711 (July 11th, 2006)
testdate2 = 4 (00:00:04, 4 seconds after midnight)
in a timezone other than my local timezone. To calculate the Unix time, I feed testdate1, testdate2 into a function I adapted fro... | localtime sets timeinfo->tm_isdst to that of the current time - not of the date you parse.
Don't call localtime. Set timeinfo->tm_isdst to -1:
The value specified in the tm_isdst field informs mktime() whether or not daylight saving time (DST) is in effect for the time supplied in the tm structure: a positive value me... |
70,961,570 | 70,962,012 | Delete in Linked List | So I revisited double linked list, found I'm really stupid, and can't figure things out even when I narrowed down problem to delete operator. I'm still playing around with templates, so maybe there's something wrong with templates as well. Print works fine without deleting a node. Please tell me what's wrong.
Result of... | The ~DoubleLinkedList() logic is all wrong. When the list is empty, head is nullptr, so accessing tmp->next in the loop is undefined behavior. And the way you are deleting nodes is just weird in general. It should look more like this instead:
~DoubleLinkedList() {
Node *tmp, *next;
for (tmp = head; tmp != nu... |
70,961,923 | 70,962,185 | Is casting strings from `wchar_t` to `char16_t` legal if encoding and width is the same? | On Windows, wchar_t is a UTF-16(LE) formatted character, which is -- for the most part -- equivalent to char16_t. However, these two character types are still distinct types in the C++ type-system -- which makes me uncertain whether converting between sequences of these two character types is legal as per the C++ stand... | You already know the answer to this: strictly speaking, no.
wchar_t is not char16_t. Neither derives from the other. Neither is similar to the other. Neither is a signed/unsigned version of the other. Neither is an aggregate containing the other.And neither of them is a bytewise type (char, etc).
So you cannot access a... |
70,962,146 | 70,970,712 | Can't understand the requirement from the exercise | this https://projecteuler.net/problem=641 is the problem I am trying to solve and below is my half solution.
void dice(int n)
{
int i, j, dices[n];
for(i = 0; i < n; i++) {
dices[i] = 1;
}
for(i = 1; i < n; i++)
{
for(j = 0; j < n; j+=i)
{
dices[j]= dices[j] ... | Read the problem description again. There is a definition of f() there:
Let f(n) be the number of dice that are showing a 1 when the process finishes.
It is not a value of any specific die. Instead, the value of f(n) tells you how many dice in the n–dice row show 1 after completion of all turns.
|
70,962,623 | 70,962,788 | Convert Pixels Buffer type from 1555 to 5551 (C++, OpenGL ES) | I'm having a problem while converting OpenGL video plugin to support GLES 3.0
So far everything went well, except glTexSubImage2D the original code uses GL_UNSIGNED_SHORT_1_5_5_5_REV as pixels type which is not supported in GLES 3.0
the type that worked is GL_UNSIGNED_SHORT_5_5_5_1 but colors and pixels are broken,
so... | This should be what you're looking for.
uint16_t Convert1555To5551(uint16_t pixel)
{
// extract rgba from 1555 (1 bit alpha, 5 bits blue, 5 bits green, 5 bits red)
uint16_t a = pixel >> 15;
uint16_t b = (pixel >> 10) & 0x1f; // mask lowest five bits
uint16_t g = (pixel >> 5) & 0x1f;
uint16_t r = pi... |
70,962,870 | 70,963,445 | Build Qt project with same filenames in different directories | In a typical C++ application (no Qt), I may have the following:
app/include/namespace1/Foo.h
app/src/namespace1/Foo.cpp
app/include/namespace2/Foo.h
app/src/namespace2/Foo.cpp
Where "app" is the root folder for the project. The classes in those files are:
//In app/include/namespace1/Foo.h
namespace namespace1 {
... | Here is one answer: https://riptutorial.com/qt/example/15975/preserving-source-directory-structure-in-a-build--undocumented---object-parallel-to-source--option--
This causes Qt to generate a directory structure in the build directory that "mirrors" the source directories.
|
70,963,295 | 70,964,104 | Turn C string literal into std::integer_sequence at compile-time with C++17 | Is it possible to write a construct that turns any C string literal "XY..." into a type std::integer_sequence<char, 'X', 'Y', ...> at compile time? I really want a character pack, not a std::array.
Something like
using MyStringType = magic_const_expr("MyString");
A nice approach using the literal operator was demonstr... | Something like this might do it:
template <size_t N, typename F, size_t... indexes>
constexpr auto make_seq_helper(F f, std::index_sequence<indexes...> is) {
return std::integer_sequence<char, (f()[indexes])...>{};
}
template <typename F>
constexpr auto make_seq(F f) {
constexpr size_t N = f().size();
usin... |
70,963,319 | 70,967,279 | Cannot read back serialized data using protocol buffer in C++ platform | I have just started to use protocol buffer and try to make a minimal example to write and read back data. But I am failed to read back the serialized data.
Sources I have used to make the example
1, 2, 3.
My Approach
Structure and Code to generate serialized data
.
├── CMakeLists.txt
├── lib
│ └── libproto_library.so... | Encircled in a minor issue really. The path of message.data was wrong.
Firstly, I was opening file with std::ios_base::out. Syntactical error. Already edited in the question though.
Executable file is executing from bin directory
message.data is located in 1 level up of bin, in the src directory
Corrected code to read... |
70,963,558 | 70,963,886 | How to use matcher in google test (error: undeclared identifier) | I'm trying to use google test to test a C function. A simple test using ASSERT_NO_FATAL_FAILURE(); and also EXPECT_THAT();. But when I try to use matchers (like not null for example) the IDE says: Use of undeclared identifier 'NotNull'.
#include "gtest/gtest.h"
extern "C" {
#include "first_tdd.h"
}
TEST(sum, sum_... | NotNull is declared in the namespace ::testing. Possible fixes
TEST(sum, sum_has_return)
{
EXPECT_THAT(sum(), ::testing::NotNull());
}
or
TEST(sum, sum_has_return)
{
using ::testing::NotNull;
EXPECT_THAT(sum(), NotNull());
}
|
70,965,055 | 70,965,429 | Raw pointer but modern way | I have to have a semantic stack in my project which is going to hold multiple types in it.
I aim to have my project to use modern C++.
What is the correct way to have a stack of any type ?
Equivalent version in java is Stack<Object>.
Which of these are correct?
Use void* and cast it to the type I want.
Something as 1 ... |
std::any is for storing objects of any type (limitations may apply).
However, the entire design of storing any type is rarely ideal. Often, it's better to use variadic templates to keep polymorphism entirely compile time, or to have only a limited set of types (std::variant), or even to use an OOP hierarchy. Which is... |
70,965,523 | 70,968,869 | simulate selection in windows C++ | I have this in my Notepad:
hello
I want to simulate selecting in C++ using Windows' keybd_event function.
here is my code:
keybd_event(VK_SHIFT, 0, 0, 0);
for (size_t i = 0; i < 5; i++)
{
keybd_event(VK_LEFT, 0, 0, 0);
keybd_event(VK_LEFT, 0, KEYEVENTF_KEYUP, 0);
}
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);... | Add KEYEVENTF_EXTENDEDKEY will select rightly.
https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput#members
#include <windows.h>
void main()
{
Sleep(2000);
keybd_event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), KEYEVENTF_EXTENDEDKEY, 0);
for (size_t i = 0; i < 5; i++)
{
keybd_event(VK_LEFT... |
70,965,785 | 70,966,048 | Rounding errors in lethal dose calculator program | I was given an assignment that asks me to find the lethal dose of soda in grams for an inputted weight from the user. I am having many issues with rounding errors... this should be simple and not sure why I'm having so many issues with it. For example, here are a couple of inputs and outputs that are causing problems. ... | The round you use returns a floating point value. You need lround - see here: https://en.cppreference.com/w/cpp/numeric/math/round
cout << "Lethal dose in grams, cans is [" << lround(dieter_lethal) << ", "
<< lround(dieter_lethal_cans) << "]" << endl;
Lethal dose in grams, cans is [124850000, 356714292]
|
70,966,204 | 70,966,487 | C++ call to list constructor is ambiguous | I'm trying to build an old C++ project on a modern version of Clang and getting lots of ambiguous errors. I don't have much C++ experience so apologies if this is basic stuff.
/home/ubuntu/NameAndTypeResolver.cpp:124:40: error: call to constructor of 'list<list<const dev::libcrunch::ContractDefinition *> >' is ambiguou... | To solve your problem do this:
std::list<std::list<ContractDefinition const*>> input(1);
// ^^^^ drop the ,{}
The {} is an attempt to constructor an object of type std::list<ContractDefinition const*> (i.e. a single member of the input).
In C++ 11 the original line w... |
70,966,753 | 70,967,309 | C++ reading from file is not giving expected, or any output | I am trying to make a game which loads it's levels from a text file. I decided to do this with the help of a 2 dimensional vector of integers. Before implementing it in my main code, I first decided to check whether my logic was right so I made a Test.txt file containing the the level I wanted to draw.
Test.txt:-
1 1 0... | So I finally found the problem, the code, logic, text file everything were working fine. After taking the advice about debuggers from the other answer, this time instead of using atom's terminal plugin, I used powershell and it worked. It gave the output i was expecting. Then i tried the same code with the atom's termi... |
70,966,768 | 70,967,321 | How to parse below JSON with nested array in C++ and retrieve the result | I have a JSON like below which need to be parsed in C++ using read_json.
[
{
"key": "123",
"revoked": false,
"metadata": [
{
"visible": true,
"key": "abc",
"value": "0"
},
{
"visible": true,
"key": "cdf",
"value": "0"
}
... | I'd suggest Boost JSON:
#include <boost/json.hpp>
#include <fmt/ranges.h>
#include <iostream>
namespace json = boost::json;
int main() {
std::map<std::string, std::string> kv;
auto doc = json::parse(sample);
for (auto& toplevel : doc.as_array()) {
for (auto& md : toplevel.at("metadata").as_array()... |
70,967,008 | 70,967,151 | whats wrong with this code it just give Enter an Alphabet= j ERROR! (Enter one Alphabet only not two Alphabet or a number) | #include <stdio.h>
int main(void)
{
char a;
printf("Enter an Alphabet=\n");
scanf("%c",&a);
if(a>=0)
{
printf("ERROR!\n(Enter one Alphabet only not two Alphabet or a number)");
}
else
{
switch (a)
{
case 'a' :
printf("It is vowel");
break;
case 'e' :
printf("It is vowel");
break;
cas... | To check if a character is an alphabetical character, you should use the isalpha function.
Putting together my other pointer (checking what scanf returns as well as using tolower, the code could be written something like this:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char a;
printf("Enter an alp... |
70,967,139 | 70,967,386 | I am not getting how the structure is being passed to a function in following code using call by reference? | Like in this code, what I don't understand is how 'n1' [ increment(n1) ] is being passed to 'number& n2'[void increment(number& n2)].
how can we pass n1 into &n2?
Please let me know if I am getting the basics wrong, because its only recently that i have started to learn C and C++.
// C++ program to pass structure as an... | Since you are taking the parameter to increment function as a refrence so when you pass n1 to it as follows:
increment(n1);
It is passed as a reference to the increment function which basically means that alias of n1 is created with the name n2
void increment(number& n2)
This means whenever there is a change in n2, It ... |
70,967,271 | 70,971,423 | Overload resolution between constructors from initalizer_list and from a value requiring conversion, compilers diverge | In the following code, struct A has two constructors: A(int) and A(std::initializer_list<char>). Then an object of the struct is created with A({0}):
#include <initializer_list>
struct A {
int a;
constexpr A(int) { a = 1; }
constexpr A(std::initializer_list<char>) { a = 2; }
};
static_assert( A({0}).a ==... | Clang & GCC are right, MSVC has a bug
This is CWG 1589:
1589. Ambiguous ranking of list-initialization sequences
Section: 16.3.3.2 [over.ics.rank]
Status: CD4
Submitter: Johannes Schaub
Date: 2012-11-21
[Moved to DR at the November, 2014 meeting.]
The interpretation of the following example is unclear in the current
... |
70,967,545 | 70,967,720 | Why can you create typedefs to a struct that doesn't exist? | The following code compiles fine.
header.h:
typedef struct Placeholder_Type* Placeholder;
impl.cpp:
#include "header.h"
void doSomething(Placeholder t) {
(void) t;
}
int main() {
int *a = new int();
doSomething((Placeholder)a);
}
compilation command:
clang++ impl.cpp
The type Placeholder_Type does not ex... | struct Placeholder_Type declares the struct Placeholder_Type (but doesn't define it), no matter where it appears. Even if it's inside a typedef. So you don't create a typedef to a struct that doesn't exist, but to one you just declared (and thus created, if the compiler didn't already know about it).
As for why, it's b... |
70,967,789 | 70,967,816 | Why can we use uninitialized variables in C++? | In programming languages like Java, C# or PHP we can't use uninitialized variables. This makes sense to me.
C++ dot com states that uninitialized variables have an undetermined value until they are assigned a value for the first time. But for integer case it's 0?
I've noticed we can use it without initializing and the ... | C++ gives you the ability to shoot yourself in the foot.
Initialising an integral type variable to 0 is a machine instruction typically of the form
REG XOR REG
Its presence is less than satisfactory if you want to initialise it to something else. That's abhorrent to a language that prides itself on being the fastest. ... |
70,967,924 | 70,968,805 | Recursive wrapper that adds a specific function applied to every objects in a container of container in c++ | I would like to make a wrapper to a specific container (or a container of container) class such that the wrapper (1) inherits all the functions of the parent class and (2) adds a specific function that applies to all the elements.
For example, I want to add bar function that takes an object whose class is Destination o... | With 2 overloads, you might do something like:
template <typename T>
auto bar(T& item, const Destination &dest)
-> decltype(item.bar(dest), void())
{
item.bar(dest);
}
template <typename Container>
auto bar(Container& c, const Destination &dest)
-> decltype(c.begin(), void()) // Check container, just use `begin` h... |
70,968,143 | 70,968,305 | Generate all balanced parenthesis for a given N | // Header files
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
// This function checks for well formedness of the passed string.
bool valid(string s)
{
stack<char> st;
for(int i=0;i<s.length();i++)
{
char x=s[i];
if(x=='(')
{
st.push(x);
... | //c++ program to print all the combinations of
balanced parenthesis.
#include <bits/stdc++.h>
using namespace std;
//function which generates all possible n pairs
of balanced parentheses.
//open : count of the number of open parentheses
used in generating the current string s.
//close : count of the number of closed... |
70,968,504 | 70,969,516 | How do I constrain the parameter(s) of a functor using concepts? | I have the following concept:
template <typename T>
concept FunctorInt = requires(T a, int b) {
a.operator()(b); //require the () operator with a single int parameter.
};
I use this in the following function:
template <FunctorInt functor_t>
void for_each_sat_lit(const int ClauseIndex, functor_t functor) {
auto... | Your concept check if the type can be called with an int
but you cannot control promotion/conversion which happens before.
You can check signature of T::operator(), but then previous valid cases (as overload, template function, no exact function but similar (const, volatile, ...)) might no longer work.
For example:
tem... |
70,968,854 | 71,429,252 | Using ADTF File Library | I wanted to use ADTF library in my visual studio project. Do i need to build the library from my machine to use it? The instructions provided with the library are not clear to me since i haven't used cmake build before.
Any help in this regard is greatly appreciated.
| The following instructions are for ADTF File Library 0.7:
Linux
First build a_util
$ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=<any-install-dir> -Da_util_cmake_enable_documentation=OFF -Da_util_cmake_enable_integrated_tests=OFF . && make && make install
Then build ddl
$ cmake -DCMAKE_BUILD_TYPE=R... |
70,969,000 | 70,969,209 | Function to return median of 3 | I am looking for the best solution to finding a median of 3. I want it to be in the least lines possible. Thank you in advance :) I've tried sth like this:
int median(int a, int b, int c)
{
if ((a >= b && a <= c) || (a <= b && a >= c)) return a;
if ((b >= a && b <= c) || (b <= a && b >= c)) return b;
return... | int median(int a, int b, int c)
{
return ((b > a) == (a > c)) ? a : ((a > b) == (b > c)) ? b : c;
}
https://godbolt.org/z/4G3dzPcs3
Above code has small bug in it (prove that tests are important), here is fixed version:
int median(int a, int b, int c)
{
return (b > a) == (a > c) ? a : (b > a) != (b > c) ? b : ... |
70,969,326 | 70,969,441 | how to use parallelize two serial for loops such that the work of the two for loops are distributed over the thread | I have written the below code to parallelize two 'for' loops.
#include <iostream>
#include <omp.h>
#define SIZE 100
int main()
{
int arr[SIZE];
int sum = 0;
int i, tid, numt, prod;
double t1, t2;
for (i = 0; i < SIZE; i++)
arr[i] = 0;
t1... | You can declare the loops nowait and move the reduction to the end of the parallel section. Something like this:
# pragma omp parallel private(tid, prod) reduction(+: sum)
{
# pragma omp for nowait
for (i = 0; i < 50; i++) {
prod = arr[i]+1;
sum += pr... |
70,969,514 | 70,970,696 | Variadic Template Specialization Overload works in GCC but not MSVC | I have the following function declarations
template<typename RET, typename... PARAMS>
RET Execute(PARAMS... params)
{ ... }
template<typename RET>
RET Execute()
{ ... }
template<typename... PARAMS>
void Execute(PARAMS... params)
{ ... }
void Execute();
These calls work fi... |
This call works fine in GCC, but not in MSVC.
In my Debian stable, I get the same error also with clang++ 11.0.1-2 ("error: call to 'Execute' is ambiguous") and g++ 10.2.1 (" error: call of overloaded ‘Execute<int32_t>(int32_t, int32_t)’ is ambiguous").
Considering it is not possible to explicitly give the typenames... |
70,969,783 | 70,970,200 | How to print all inputs of string from a for loop? | Printing the names that I inputted in the variable userInput only prints the last name that I inputted and not including the first one that I inputted.
If my programming was incorrect please explain what should I do in a way that beginners could understand.
int main()
{
int data = 0;
int input;
string user... | As already mentioned you are just overwriting userInput with each new input read. You can simply append the new string to your existing one:
std::string students;
for (int i=0; i<data; ++it) {
std::string input;
std::cout << "Enter student name: ";
std::cin >> input;
if (!students.empty())
... |
70,970,886 | 70,971,036 | C++ endl not printing new line when called from a method | New to C++
My understanding is endl will add a new line. So with the following piece of code:
#include <iostream>
using namespace std;
void printf(string message);
int main()
{
cout << "Hello" << endl;
cout << "World" << endl;
printf("Hello");
printf("World");
return 0;
}
void printf(string message) {
cout << m... | The problem is that due to overload resolution the built in printf function is selected over your custom defined printf function. This is because the string literal "Hello" and "World" decays to const char* due to type decay and the built in printf function is a better match than your custom defined printf.
To solve th... |
70,970,959 | 70,972,329 | nested if v/s && operator | I am writing code in C++ for checking if a cycle is present in a given undirected graph or not.
My code is this:-
#include <bits/stdc++.h>
using namespace std;
// Class for an undirected graph
class Graph
{
// No. of vertices
int V;
// Pointer to an array
// containing adjacency lists
list<in... | Think about the negation of your condition, as this affects when the else branch is executed.
In the commented-out code, it is
!(!visited[i] && isCyclicUtil(i, visited, v))
which is
visited[i] || !isCyclicUtil(i, visited, v)
and your entire conditional, testing the negated condition first, is equivalent to
if (visite... |
70,971,282 | 70,971,706 | Generate Integer Sequence For Template Parameter Pack | There is a class method template with parameter pack I want to call, defined as:
class C {
template<int ... prp> void function() {}
}
For a given integer N, I need all integers up to N as template arguments for the parameter pack.
constexpr int N = 2;
C c;
c.function<0, 1>();
I have tried using std::integer_seque... | You might create helper function:
template <int... Is>
void helper(C& c, std::integer_sequence<int, Is...>)
{
c.function1<Is...>();
c.function2<Is...>();
}
And call it
constexpr int N = 2;
C c;
helper(c, std::make_integer_sequence<int, N>());
|
70,971,668 | 71,037,938 | How to include libgmp to xeus-cling? | I am trying to run the following code:
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.so")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp... | in jupyter:
#include <stddef.h> /* for size_t */
#include <limits.h>
#define __xeus_cling__
#pragma cling add_library_path("/usr/lib/x86_64-linux-gnu")
#pragma cling add_include_path("/usr/include")
#pragma cling add_include_path("/usr/include/x86_64-linux-gnu")
#pragma cling load("/usr/lib/x86_64-linux-gnu/libgmp.s... |
70,971,977 | 70,972,386 | CMake - Library with example subdirectory running as separate project | Edit 2 - Fixed!
The issue was fixed by correctly using absolute paths rather than relative paths, and by adding add_subdirectory to example/CMakelists.txt.
I have updated the provided code (and will leave the repository in case somebody wants to use it as a starting point.
Edit:
Adjusted CMakelists.txt files to use ab... |
he example project should be capable of running on its own by loading the CMakelists.txt in the directory, and should be able to use the library
Just add:
add_subdirectory(./../ some_unique_name_here)
I think I would remove source/CMakelists.txt and write it all in root CMakelists.txt. It's odd to use ../ to refer t... |
70,971,989 | 70,972,054 | In C++, why are my variable inputs that are separated by a space being stored incorrectly? | In this code I ask the user for inputs separated by a space, gradeOne space gradeTwo.
However, it is not functioning as intended so I added output statements at the end to see if the values were stored correctly.
If I type in: 59 95 gradeOne should be 59, temp should be ' ' and gradeTwo should be 95 but the output says... | operator >> automatically skip space. Just change to:
cin>>gradeOne>>gradeTwo;
|
70,972,111 | 70,972,379 | Why can I go out of bounds with the assignment opeator but not with the {} | My question is pretty straightfoward: why can I assign a value that goes out of bounds to an array like this, but not with the {} operator:
int arr[2];
arr[2] = 2;
for(int num{0}; num < 3; num++)
cout << arr[num] << endl;
But when I do this I get an error right from the start:
int arr[2] {1,2,3};
Now I know tha... | Both cases are completly different. The first one is array element assignement. The second is array initialization. The rules state that it is an error if you provide more initializers that the array can hold. The rules state also, that element access behind the array end is not an error but undefined behaviour. In oth... |
70,972,244 | 70,972,545 | c++ - structure in map allocation | As I known, map value is initialized by NULL(0). However, Below code is works well without any allocation. How is this code work?
#include<bits/stdc++.h>
using namespace std;
struct stuc{
map<string, stuc> mp;
int cnt;
}root;
int main() {
stuc* u = &root;
stuc* v = &(u->mp["test"]); // how to allocate?... | If you access a map with the [] operator like in
&(u->mp["test"])
there is a new key value pair allocated, default initialized, and inserted into the map if the element does not already exists [1]. In your program that is exactly what happens. The map does not already have an key "test". Thus a new value is default co... |
70,973,253 | 70,983,377 | Ignore exceptions on Boost.Log when unable to create folder | This is a snippet of code that I have to maintain:
std::string log_file_name = "/tmp/log/program.log";
auto fs_sink = boost::log::add_file_log( boost::log::keywords::file_name = log_file_name, boost::log::keywords::open_mode = std::ios_base::app );
boost::log::add_common_attributes( );
fs_sink->locked_backend( )->... | You can set an exception handler on sink, core or logger level. The handler will be called when an exception is propagated through the given component, and in particular it may suppress further propagation of the exception. For example, to suppress all exceptions on the core level, you can set it like this:
boost::log:... |
70,973,619 | 70,973,707 | How to constrain an auto lambda parameter to a pointer to member function? | I have a generic lambda function that needs to accept a pointer-to-member-function as a parameter. I can of course simply use auto on its own and the compiler will deduce the correct type. However, where possible, I prefer to decorate my auto parameters with *, & and const where appropriate, thus better communicating t... | You can declare it as:
auto l = [](auto S::*pmf)
It does tie the pointer to a S type, but it makes sense because it is that way you will use it.
|
70,973,923 | 70,984,846 | ECDSA signature verification: Go vs OpenSSL | I'm trying to verify an ECDSA signature for a hash using a public key. I've written a small Go program that successfully does this but I've been unable to port it to C++.
Here is my input data:
Public key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDd9VXmpHjV4voFO+0ZoFPlRr5icZXquxsr9EkaOUO9B7Wl1DAgGI0EKCm1++Bl2Od32xZFeFuG07O... | EVP_DigestVerify{Init/Update/Final} do two things:
They hash the input data
Then they verify the computed hash against the signature
ecdsa.VerifyASN1 on the other hand does only the second step from the above, already taking in the hash as input.
The OpenSSL function that does that is ECDSA_verify.
So you can do some... |
70,973,970 | 70,978,259 | cmake compile_commands.json for interface target | I have a simple c++ library that should be shipped as header-only library. The library depends on other libraries installed through CPM.
I'm using VS code and the compile_commands.json in order to notify VS code about the include paths from CPM packages. That does work as long as the project is configured as shared/sta... | It turns out I was simply using the wrong target. Interfaces don't include any source files and thus won't generate any meaningful compile_commands.json.
What I was looking for is the object target which solves my issue completely.
Just for the reference, this is how the "correct" CMakeLists.txt would look like:
cmake_... |
70,974,463 | 70,974,659 | Returning the correct child type from a function | I have a UIComponent class. Window, Button and Text inherit from it. UIComponent has a recursive structure in that it stores a std::vector<std::unique_ptr<UIComponent>> contents;. I am trying to write a function that recursively that goes through contents and finds the given UIComponent.
In my original code, I use a ha... | For the polymorphic behaviour you are attempting to work, you need at least one of the base class member functions to be virtual.
In your code, simply adding that specifier to the GetComponent member function will do the trick; like this:
virtual UIComponent* GetComponent(const std::string& name)
{
// .... |
70,974,476 | 70,977,817 | Efficiently load/compute/pack 64 double comparison results in uint64_t bitmask | I want to load/compare/pack as runtime efficent as possible the results of 64 double comparisons into a uint64_t bitmask.
My current approach is to compare 2*2 pairs via AVX2 using _mm256_cmp_pd. The result of both (=8) comparisons is converted into a bitmap using _mm256_movemask_pd and via a|b<<4 assigned as byte into... | Here’s an example. It packs the comparison results into bytes with whatever instructions were the most efficient, shuffles into correct order once per 32 numbers, and uses _mm256_movemask_epi8 to produce 32 bits at once.
// Compare 4 numbers, return 32 bytes with results of 4 comparisons:
// 00000000 11111111 22222222 ... |
70,974,613 | 71,031,583 | Is there a way to detect if a given header of the C++ Standard Library is included? | More specifically, is it possible to detect, at compilation time, if a C++ standard header file is included (let say <complex>), and do that in a way that is cross-plateform and cross-compiler ? I'd like it to work with C++11 at least, but for the question's sake, is it possible for any C++ standard ?
I know the implem... | TL;DR : No, there is not, apart from the C++17 feature #if __has_include(<complex>). Not with defined macro anyway.
Long answer : there are two parts to the answer. What I read from some headers, and the tests I ran on differents OS with differents compilers.
Warning : I will write also about C, as some compilers uses ... |
70,975,375 | 71,377,680 | xcb correct window size | I have a question regarding xcb Window size
I create a window using xcb_create_window function
xcb_create_window(mScreen->connection(),
XCB_COPY_FROM_PARENT,
mWindow,
mScreen->screen()->root,
x, // left corner of the window client area
... | The following code gets margins of a window
followed suggestion from Erdal Küçük:
create window
configure stuff (like title or close button)
wait for property message
in case _NET_FRAME_EXTENTS read data
uint32_t value_mask, value_list[32]{};
auto windowHandle = xcb_generate_id(xcb_connection());
value_mask =... |
70,975,403 | 70,975,456 | How to write a generic function to print begin and end iterator elements | The function below, printloop, is able to print the elements in a collection as below. But if I try to remove the loop and use std::copy, how do I get that version, print, to work?
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
// this print function doesn't compile
template <typename ... | You might use iterator_traits:
template <typename iter>
void print(iter begin, iter end) {
using value_type = typename std::iterator_traits<iter>::value_type;
std::copy(begin, end, std::ostream_iterator<value_type >(std::cout, "\t"));
}
Demo
|
70,975,663 | 70,975,730 | Can I initialize a std::array<uint8_t with a string literal? | I write a lot of C code interacting with instruments using UART serial ports. I'm starting a new project where I'm trying to use a more object oriented approach with C++. Here's how I've defined and sent commands in the past using C.
uint8_t pubx04Cmd[] = "$PUBX,04*37\r\n";
HAL_UART_Transmit(&hUART1, pubx04Cmd, size... | std::array is an aggregate, i.e. a possible implementation may be like
template <typename T, size_t S>
struct array {
T a[S];
// ...
};
The enclosed array can be initializes as usual:
std::array<uint8_t, 14> pubx04Cmd{"$PUBX,04*37\r\n"};
|
70,975,761 | 70,976,110 | MSVC: C++14: std:set: comparison function: why "const" is required? | Sample code:
#include <string>
#include <set>
using namespace std;
class x
{
private:
int i;
public:
int get_i() const { return i; }
};
struct x_cmp
{
bool operator()(x const & m1, x const & m2)
#if _MSC_VER
const
#endif
{
return m1.get_i() > m2.get_i();
}
};
std::set<x, x_cmp> members;
... | This is LWG2542. In C++14, the wording for the comparison operator said "possibly const", which was interpreted by GCC and Clang as meaning that the comparison operator was not required to be const qualified. MSVC always required it.
This is a wording defect, as comparison operators for associative containers should be... |
70,976,288 | 70,976,344 | The value of integer is changing without any calculation | I have no idea why suddenly the value of integer is changing even though there's no process of caluclation, here's the code of my program :
#include <iostream>
using namespace std;
int main()
{
int n;
int a[] = {};
int b[] = {};
cin >> n;
cout << "\n";
for(int i=0;i<n;i++)
cin >> a[i... | These declarations
int a[] = {};
int b[] = {};
invoke undefined behavior because you may not declare arrays with the number of elements equal to 0.
It seems you are trying to use variable length arrays that is not a standard C++ feature.
Nevertheless if the compiler supports this feature then you need at least to wri... |
70,976,291 | 70,976,366 | libc++abi: terminating with uncaught exception of type std::length_error: basic_string | I'm trying to read a .CSV file and I'm encountering errors with reading strings.
For context, this .CSV file contains a person's name followed by a few personality traits (e.g., likes cats, chocolate, mountains, etc.). I want to read in this data and store it in a map<string, vector<string> > where the person's name is... | The problem here is that f.eof() won't return true until getline fails. When getline reads the last line in the file, the getline succeeds, the file is positioned after the last byte, but f.eof is not yet set. Thus, you are calling line.pop_back() on a zero-length string.
Instead, use this idiom:
while( getline(f... |
70,976,393 | 70,998,967 | Add a cv::Mat inside a cv::Mat at a specific position | I am currently making a soft that renders chess game. To do it, I use OpenCV.
The idea is to have the chess board in a cv::Mat and add pieces with a std::array of cv::Mat :
RenderImage::RenderImage() {
backgroundChess = cv::imread("files/board_chess4.png"); /// The chess board
piecesChess[0] = cv::imread("fil... | Thanks you @Christoph Rackwitz, with your link I have found the solution.
I convert the python code of Try2Code ( enter link description here )
The final code is here :
void RenderImage::overlayImage(cv::Mat& back, const cv::Mat& front, std::size_t posX, std::size_t posY) {
cv::Mat gray, mask, mask_inv, back_bg, fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.