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 |
|---|---|---|---|---|
71,859,064 | 71,859,223 | Are pointer to member functions not callable object | I am reading C++ Primer 5th edition and there I came across the following statement:
As a result, unlike ordinary function pointers, a pointer to a member is not a callable object; these pointers do not support the function-call operator.
So my question is: Is the highlighted part correct according to the standard?
M... |
What i am asking is that whether pointer to member function are callable object according to the standard.
Yes, a pointer to a member function is a callable object according to the standard.
From func.def#4:
A callable object is an object of a callable type.
And from func.def#3:
A callable type is a function objec... |
71,859,149 | 71,878,538 | Creating a DLL using MSVC's cl | I am attempting to get an understanding of how building and linking works, since there's a library I want to compile into a DLL. I do not have control over the tool that will be used to compile - It's going to be the msvc tools invoked via command line.
To that end, I've managed to locate a tutorial on creating DLLs th... | Note that Serial last official version (v1.2.1) was released in April 2015 (20150422), and the activity has dropped significantly since then.
Please check [SO]: Linking to CRT (unresolved external symbol WinMainCRTStartup) (@CristiFati's answer) (just posted) before going further.
I just built the package and placed th... |
71,859,765 | 71,860,252 | Why is std::move generating instructions here? | I heard time and again that std::move(t) is more or less only a fancy way of saying static_cast<T&&>(t) and would not generate any instructions.
When I was playing around now with std::move on godbolt in order to better understand move semantics I saw that it does (or at least may) generate instructions. In this exampl... | You are compiling without optimisations. So you see exactly what is written without any attempt to simplify or inline functions.
Generated code is roughly eqivalent to what type&& foo(type& x) { return x; } would generate, which is what move does.
Studying assembly generated without optimisations turned on is exercise ... |
71,859,923 | 71,863,555 | C# equivalent of C++ deferred async execution? | I'm relatively new to C# and I'm trying to replicate an asynchronous call that has already been written in C++. This has been a little difficult because while I can easily understand the async/await keywords in C#, I'm stuck on the concept of deferred launch in that language. Here is the original code:
bool runMethod(c... | If my quick google search was correct then launch::deferred means lazy evaluation on the calling thread.
In that case, using a task might not be a good idea, they are not meant for lazy evaluation because:
Awaiting them or taking their result does not start them if they were
not started already (and starting them whil... |
71,859,992 | 71,884,979 | What is causing this memory access violation error (0xC0000005) when using Eigen with "-march=native"? | I am rewriting some c++ code (originally written in Matlab as a MEX function) in codeblocks so that I can use debugging and profiling tools designed for c++. The code I am rewriting uses Eigen and SIMD intrinsic instructions, so I need to compile with the -march=native flag. I was getting a memory access violation erro... | I managed to reproduce this problem using Eigen 3.4.0 and mingw (gcc 8.1.0 with -mavx -m64 -std=c++17 -g) on Windows using AVX (-mavx, also enabled by -march=native for the OP). As already suspected by people in the comments, it is certainly the issue that mingw-gcc fails to align stack variables correctly to 32 bytes,... |
71,860,358 | 71,872,418 | C++ function not exported by .so seemingly because of pybind11 parameters | I am currently trying to define a shared library that I aim to use from a Python C++ extension as well as from vanilla C++ applications.
I managed to build the shared library, and tried to link a simple C++ application against it to test its functionalities, but one of the functions of the shared library is treated as ... | Namespace pybind11 has hidden visibility.
/usr/include/pybind11/detail/common.h:#
define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
so all functions that have anything to do with that namespace (like having an argument type from it) are also hidden.
You can override this by explicitly set... |
71,860,616 | 71,860,871 | C++ method resolution by name | I am wondering if there is a way in C++ to write a function that will resolve object methods based on the method name alone (specific examples below). Run time or compile time resolution (such as templates) would both be acceptable. I have read a little bit about template metaprogramming, but I was hoping I might get s... | You can make exampleFunction a function template that has the first parameter of type of the object, the second parameter can be a reference to a pointer to a member function and the third parameter is a function parameter pack that denotes the arguments to be passed when calling the member function.
#include <iostream... |
71,860,748 | 71,860,865 | Logical operators don't output correct results | Here is the code that I'm struggling with
#include <iostream>
#include <string>
using namespace std;
int main() {
int a{ 6 }, b{ 9 };
cout << !(a < 5) && !(b >= 7);
}
Every time I run this code it outputs 1. Why doesn't it output 0?
| You've been tripped up by the semantic overloading we give the << operator in C++.
This operator comes from C, where it is used exclusively for bit-shifting integers.
Because of that, it has a lower precedence than the && operator. C++'s use of the << operator for stream insertion doesn't change that. The << will be... |
71,861,504 | 71,861,597 | What happens when a paddr_t is passed to a linked list that is expecting unsigned on a 64bit system? | After looking harder at the code, I figured out the answer to my question. I was mistaken in thinking the initial declaration of linked list meant all future types had to be the same
The code I am looking at is for linked list insertion. The linked list is used to store logical addresses. The linked list is defined as ... | Assuming a common-sense definition of LinkedList: You don't pass paddr_t to the insert function. You pass unsigned to the insert function. If you try to pass paddr_t, the compiler will add an (unsigned) cast for you, and may or may not emit a warning.
If paddr_t and unsigned are the same type, it's unlikely that you'll... |
71,862,558 | 71,862,688 | UI blocks while the program is running in QT c++ | I have an application in QT with ui. And also I have heavy calculations. When calculations starts, my program stops responding while calculations are running. I wanted to do this via multithreading, but I cannot correctly implement this. I tried to do it with default lib thread:
void HeavyCalculations()
{
// some he... | See the Multithreading Technologies article in Qt - the "simplest" solution is probably to use QtConcurrent for running the computation, and QFutureWatcher for getting notified about when the computation is finished.
So. something along those lines:
void MainWindow::on_pushButton_3_clicked()
{
// context is some ob... |
71,863,108 | 71,863,149 | What happen when we assign a reference to a variable? | void func(){
int a = 1;
int b = a; // copy assignemnt
int &c = a; // nothing?
int d = c; // nothing?
}
For example, when we assign reference c to d, is there anything triggered (move, copy, etc.)?
What if d is an instance member? Is it safe to store a local variable reference into it?
|
when we assign reference c to d, is there anything triggered (move, copy, etc.)?
Your terminology's getting me confused! If you're talking about d and c, I assume you're referring to int d = c; I'd describe that as "assigning whatever c refers to to d". "Assign reference c to d" sounds too much like int& c = d;.
Y... |
71,863,760 | 71,863,840 | How to access data in a struct? C++ | Just quick one, how should I go about printing a value from a struct? the 'winningnums' contains a string from another function (edited down for minimal example)
I've tried the below but the program doesnt output anything at all, is my syntax incorrect?
struct past_results {
std::string date;
std::string... |
is my syntax incorrect?
No, it's just fine and if you add the inclusion of the necessary header files
#include <iostream>
#include <string>
then your whole program is ok and will print the value of the default constructed std::string winningnums in the results instance of past_results. A default constructed std::str... |
71,863,881 | 71,865,452 | using -march switch for gcc does not make a difference in terms of run-time speed | I built a small program (~1000 LOC) using GCC 11.1 and ran it for many iterations both with and without enabling -march=native but overall there was no difference in terms of program execution time (measured in milliseconds). But why? Because it's single-threaded? Or is my stone age hardware (1st gen i5, Westmere micro... | I think you should be specifying -march=native as part of LDFLAGS as well, so -flto is targeting the same machine.
But it seems your code-gen is respecting your specified arch since you say -march=alderlake make code that crashed with SIGILL, probably on an AVX encoding of a vector instruction.
It's quite possible tha... |
71,864,115 | 71,865,495 | Why do I get a segmentation fault when using "dialog_checklist" from Linux's "dialog.h"? | I wanted to use the dialog.h library from the dialog Linux package but when I try to make a radiolist (checklist with flag parameter set to 1) it gives me a segmentation fault. I assume it has to do with the list of strings (char**) but I have been unable to find a fix for it.
In this code on line 10 the error occurs:
... | It appears I read the documentation wrong, the list was supposed to contain {tag, item, status} for each item.
|
71,864,982 | 71,865,664 | When should I be using if constexpr as apposed to a regular if in a constexpr template function? | I've been trying to write a metafuncion to evaluate powers at compile time.
I have managed to do it with template metaprogramming, implemented as such:
template<int A, int B>
struct pow {
static constexpr int value = (B % 2 == 0) ?
pow<A, B / 2>::value * pow<A, B / 2>::value :
... |
In your first example, since the ternary operator is evaluated at runtime (just like a regular if statement), it cannot stop the instantiation of the template, and since your template has no specialization for the exit, all branches will be instantiated, which makes it recursive infinitely.
In your second example, si... |
71,865,108 | 71,866,103 | How would I seed the PCG RNG with a chosen, set seed? | For testing purposes I need to seed PCG's C++ implementation (the 64 bit output one) with a set value. When I look at the examples I only see it seeding using entropy.
I've used
pcg64 rng(42);
and it's worked, rng() generating the same numbers every time, but PCG64 uses a 256-bit seed and this way seems to generate th... | As I read source code, pcg64 is an instantination of engine template class which accepts pcg128_t seed value in constructor. So it is only 128 bit value, not 256 bit.
There are two ways how you can pass 128 bit seed to constructor. First is if you already have pre-defined two 64-bit values, then you can use PCG_128BIT_... |
71,865,304 | 71,865,594 | Heap corruption detected, while deleting a dynamic 2d char array | I have written a class with char** class field(which is dynamic 2d array) named visa(basically i want there to be countries which a person has visited) and countriesVisited(in fact size of the array). I intentionally didn't use strings. I've added a class method, which adds countries to the mentioned array, but when i ... | tmp[i] = new char[strlen(country)];
here you are allocating memory in amounts of strlen(country)
but in this loop:
for (int i = 0; i <= strlen(country); i++) {
if (i == strlen(country)) {
tmp[countriesVisited][i] = '\0';
break;
}
tmp[countriesVisited][i] = country[i];
... |
71,865,608 | 71,867,070 | Why is my QGraphicsLine in the wrong place | I want to draw a line to connect two circles (QGraphicsEllipseItem), but I find that I don't get the desired result with this way of writing.
//they have been initialized to the correct place
QGraphicsEllipseItem* nodeu;
QGraphicsEllipseItem* nodev;
this->addLine(nodeu->x(), nodeu->y(), nodev->x(), nod... | you should first add one QGraphicsView in your UI or :
QGraphicsView *graphicsView;
QGridLayout *gridLayout;
gridLayout = new QGridLayout(centralwidget);
gridLayout->setSpacing(0);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
graphicsView = new QGraphicsView(centralwidget);
graphicsView->se... |
71,865,918 | 71,866,714 | Why isn't rvalue copy constructor used for assignment from temporary? | #include<iostream>
#include<vector>
#include<string>
using namespace std;
class test {
public:
test(int y) {
printf(" test(int y)\n");
}
test() {
printf(" test()\n");
}
test(test&&c) noexcept {
printf(" test(test&&c) noexcept\n");
}
test(const test&z) {
print... |
So why the constructor test(test&&c) noexcept is not called?
This is due to non-mandatory copy elison prior to C++17.Under certain circumstances, the compilers are permitted, but not required to omit the copy and move (since C++11) construction of class objects.
You can verify this by providing the flag -fno-elide-co... |
71,866,011 | 71,866,159 | Replace hour of chrono::time_point? | How can I change just the hour of an existing std::chrono::system_clock::time_point?
For example, say I wanted to implement this function:
void set_hour(std::chrono::system_clock::time_point& tp, int hour) {
// Do something here to set the hour
}
std::chrono::system_clock::time_point midnight_jan_1_2022{std::chrono:... | The answer depends on exactly what you mean. The simplest interpretation is that you want to take whatever date tp points to (say yyyy-mm-dd hh:MM:ss.fff...), and create: yyyy-mm-dd hour:00:00.000....
Another possible interpretation is that yyyy-mm-dd hh:MM:ss.fff... is transformed into yyyy-mm-dd hour:MM:ss.fff....
... |
71,866,214 | 71,866,742 | How to use multiple conditions in enable_if? | I have the following code:
#include <iostream>
#include<type_traits>
using namespace std;
enum class a : uint16_t
{
x, y
};
template<typename T>
using isUint16ScopedEnum = std::integral_constant<
bool,
std::is_enum_v<T> && std::is_same_v<std::underlying_type_t<T>, uint16_t> && !std::is_convertible_v<T, uint16_... | (uint16_t)1 is of type uint16_t and not an enum type, so there is no member type for underlying_type, which causes underlying_type_t to be ill-formed and aborts compilation.
You can wrap is_enum_v<T> && is_same_v<underlying_type_t<T>, ...> into a separate trait and use partial specialization to apply underlying_type_t ... |
71,866,374 | 71,866,591 | Different behavior when accessing a base class when it's a template | When I write A::B::C, with A being a class, and B being its base class, I assume I'm accessing C which is defined in that base B. This wouldn't work when B isn't actually a base of A. However, the same apparently isn't true when B is a template, e.g. A::B<123>::C still gives me B<123>::C, and it doesn't seem to matter ... | template< int > struct B has an injected-class-name B that acts as a template name if it immediately precedes a <. The class struct A inherits this.
So, A::B< 123 >::C is the same as B< 123 >::C, not the base class B< 42 >. For example:
template<int X>
struct B {
using C = char[X];
};
struct A : B<42> {};
using F... |
71,867,090 | 71,926,738 | C++ pass function pointer in function template | I'm trying to pass a function pointer in a template, to then use it in asm code:
template <auto T>
_declspec(naked) void Test()
{
__asm
{
lea eax, T
jmp [eax]
}
}
int main()
{
Test<MessageBoxA>();
Test<Sleep>();
}
I know the naked function will crash when executed but I've simplifi... | I'm not an assembly expert, but creating a static constexpr void* set to the non-type template parameter value seems to do the trick:
template <auto T>
__declspec(naked) void Test()
{
static constexpr void* fptr = T;
__asm
{
lea eax, fptr
jmp [eax]
}
}
const void sleep()
{
}
int ... |
71,867,686 | 71,867,796 | type-casting abstract class type to struct type with a integer member | I am studing Blender's GHOST code and found the following statement in GHOST_CreateSystem C-API function
GHOST_ISystem::createSystem();
GHOST_ISystem *system = GHOST_ISystem::getSystem();
return (GHOST_SystemHandle)system;
GHOST_ISystem is an abstract class for a specific operating system such as win32, linux.
... | Abstract class CANNOT be instantiated, to wit it cannot be converted. What happens here is a conversion of pointer values.
The calls GHOST_ISystem::createSystem(); and GHOST_ISystem::getSystem(); are calls to static functions. The latter returns a pointer to GHOST_ISystem. Pointer is a separate compound type and pointe... |
71,867,733 | 71,868,129 | Why am I unable to read 2D array using vectors? | The code is :
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<vector<int>> arr;
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
cin >> arr[i][j];
}
}
return 0;
}
Compilation is successful. But, when I tried to r... | Because the vector arr is empty in your code.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<vector<int>> arr;
cout << arr.size() << endl; // output: 0
cout << arr.empty() << endl; // output: 1 , it means arr is empty
// First way
vector<vector<int>> arr1(5... |
71,867,746 | 71,868,081 | My if statements inside my while loop keep repeating forever when they are not suppose to be. It should go back to the while loop after the if stateme | So im working on a project for school and i just cant get this to work. everything else seems to run but when i input the users choice for q, s, z10, z25,z5,z1 it loops indefinetly. i cant figure out why it keeps running the function over and over. im not quite sure if im just typing something wrong or what but this is... | It seems you call getline outside of the loop. so choice is never updated.
|
71,867,795 | 71,869,861 | Specialised template *not* asserting despite compile time constant static_assert | For a few days I've been using and testing my application without any trouble using the following code:
class dataHandler
{
public:
template<class T>
T GetData(bool truncate = false) { static_assert(false, "Unhandled output type"); }
template<T>
int GetData<int>(bool truncate)
{
// Normal st... |
However I find myself wondering why the initial case of static_assert(false) didn't also fail to compile. Is this some niche exception, or is this an issue with MSVC's consistency?
It's certainly not an inconsistency. The key part here is "Standard conformance mode", controllable with the compiler option /permissive-... |
71,867,891 | 71,869,207 | C++/WinRT DeviceInformation No default Constructor exists error | Hello i'm trying to port the following code from a c# program.
public class DeviceListEntry
{
private DeviceInformation device;
private String deviceSelector;
public String InstanceId
{
get
{
return device.Properties[DeviceProperties.DeviceInstanceId] as String;
... | Assuming your DeviceListEntry declaration looks like:
namespace SerialArduino {
class DeviceListEntry {
public:
//...
private:
winrt::Windows::Devices::Enumeration::DeviceInformation device;
winrt::hstring deviceSelector;
};
}
Try implementing your constructor like this:
// having a DeviceInformation ob... |
71,868,106 | 71,868,566 | How to make getting a pixel value independent of the cv::Mat type? | I am writing a method that uses OpenCV (C++).
For example
void foo(const cv::Mat &image);
Inside, I need to take the pixel value of the cv::Mat by row and column.
If the type of image the method works with is CV_32FC3, I need to use
image.at<cv::Vec3f>(row, col);
If the type is CV_32SC2, I need to use
image.at<cv::Ve... | Drop the use of cv::Mat - where you have to call type() method (at runtime) to get the type of values stored by mat, and instead that just start using templated version of mat class: it is cv::Mat_<Type> and write more generic code.
Then you could write only one function template to read mat pixels:
template<class T>
T... |
71,868,477 | 71,868,598 | Is there a concept in the standard library that tests for usability in ranged for loops | There are a number of different ways, that make a type/class usable in a ranged for loop. An overview is for example given on cppreference:
range-expression is evaluated to determine the sequence or range to iterate.
Each element of the sequence, in turn, is dereferenced and is used to initialize the
variable with the... | It seems like what you need is std::ranges::range which requires the expressions ranges::begin(t) and ranges::end(t) to be well-formed.
Where ranges::begin is defined in [range.access.begin]:
The name ranges::begin denotes a customization point object. Given a subexpression E with type T,
let t be an lvalue that den... |
71,868,673 | 71,868,713 | Creating a std::string from std::string_view | Given a string_view sv and a string s(sv), does s use the same char array internally as sv? Is it safe to say that when s is destroyed, sv is still valid?
| Creating a std::string object always copies (or moves, if it can) the string, and handles its own memory internally.
For your example, the strings handled by sv and s are totally different and separate.
|
71,869,011 | 71,869,059 | std::map.operator[] not working with global maps | Can someone tell me how I can make use of std::map.operator[] to get the value of a const std::map ?
For example:
file.h
#ifndef _FILE_H
#define _FILE_H
#include <map>
#include <string>
const std::map<std::string,std::string> STRINGS= {
{"COMPANY","MyCo"}
,{"YEAR","2022"}
};
#endif
file.cpp
#include "cpp_playg... | The operator[] in std::map is defined to return a reference to the object with the given key - or create it, if it doesn't exist, which modifies the map, that's why it's not a const method. There is no const version of that operator, that's why you get the shown error.
Use std::map's at(...) function for access-only. N... |
71,869,458 | 71,911,504 | Drake cmake Could NOT find Gurobi | I use ubuntu 20.04 and I trying install Drake software.
I have got error while making with cmake cmake -DWITH_GUROBI=ON -DWITH_MOSEK=ON ../drake:
CMake Error at cmake/modules/FindGurobi.cmake:13 (file):
file STRINGS file
"/home/dmitriy/git/drake/Gurobi_INCLUDE_DIR-NOTFOUND/gurobi_c.h" cannot be
read.
Call Stack ... | I installed Gurobi and error dosappeared.
|
71,869,663 | 71,869,961 | Visual Studio C++ Project for Linux, how to run .out file? | Im using Visual Studio 2022 and have created a C++ project for linux.
I followed this article:
https://learn.microsoft.com/en-us/cpp/linux/connect-to-your-remote-linux-computer?view=msvc-170
And got a running OpenGL-application in Linux via Remote Debugging in Visual Studio.
I see a .out-file in Linux but I can not ru... | As you are using linux, you can use cpp or g++ for compiling your code. Linux usually have the g++. Run it by g++ filename.cpp and you will get a ELF file named a.out, you can execute this by the command ./a.out.
If you couldn't run or your code check for the modes on file with ls -la command and if you can't find th... |
71,869,715 | 71,869,870 | Linking CPR C++ library with OMNET++ | I have succesfully installed OMNET++ and now I want to link OMNET with a REST API library called CPR. Usually, in Eclipse (Which OMNET++ is based on) I would do the linking something like project properties->C/C++ build->Settings->GCC C++ Linker->Libraries->[-l section]. Now in OMNET I have tried linking it by going to... | The cpr library should be on your library path (i.e. usually on /usr/lib). Otherwise you must specify also the -L option to specify the directory where that given library is.
|
71,870,664 | 71,870,821 | Printing vector of struct - data not being saved? c++ | I have a program that randomly generates an array, and then compares the numbers to the numbers in a csv file. The file is read via getline, where it is then inserted into my struct called 'past_results'.
I then try and insert the struct data into a vector in my main function, but this doesnt seem to work. No data is p... | csv_reader writes to a function local array. Once the function returns all information read from the file is lost. Data is not stored in the class past_result. The data is stored in an instance of type past_result.
In main you push a single element to the vector via results.push_back(past_results()); as a default const... |
71,870,798 | 71,870,981 | C++ what happens if an exception occurs inside catch block? | What happens if an exception occurs inside a catch block?
try {}
catch(...)
{
stream.close(); // IO exception here
}
What's the default behaviour?
| Nothing special will happen. A new exception object will be initialized by the throw expression inside the call and a search for a matching catch handler will start, which on escaping the function call will continue on the nearest enclosing try block (enclosing the shown try/catch pair). The old exception object will b... |
71,871,314 | 71,871,419 | static_cast from 'QgsVectorLayer *' to 'QgsMapLayer *', which are not related by inheritance, is not allowed | Class QgsVectorlayer derives from base class QgsMapLayer which derives from base class QObject. I want to cast a QgsVectorlayer object to a base class. This should easily be possbile but I get an error and don't understand why.
The annex to the (probably not unimportant) error message is:
...qgsgeometry.h:46:7: note: ... | The definition of the class is missing at the point where the static_cast is used. Just because the definition of the class exists in some header file doesn't mean that the compiler automatically knows it everywhere the class is referenced. Whichever header file defines this class was not #included, so the only thing t... |
71,871,601 | 71,872,289 | Why does inet_ntop() return a pointer instead of an int? | inet_ntop() has a signature as follows:
const char* inet_ntop(int af, const void* src, char* dst, socklen_t
size);
Description:
This function converts the network address structure src in the
af address family into a character string. The resulting string
is copied to the buffer pointed to by dst, which mus... | While the reason for these choices should be found in the minutes of the committee discussion, or asked to the people who designed the API, I can take a guess.
inet_ntop() is a POSIX function, so it comes from C more than from C++. As you say, the pattern for socket operations is to return an int. But inet_ntop() is mo... |
71,871,708 | 71,871,944 | Get G++ to use a custom calling convention to pass larger structs in registers instead of memory? | Short question:
Are there compiler options or functions attributes available in g++ that force the compiler to pass members of structures through registers instead of the stack.
Long question:
In my application I have a list of function handles that I am basically calling in a loop. Since every function does only a sma... | You could pass the uint8_t or one of the pointers as a separate arg to describe what you want to the compiler, or stuff it into one of the existing 64-bit members (see below).
Unfortunately no, there aren't compiler options that tweak the C ABI / calling-convention rules to pass structs larger than 16 bytes in registe... |
71,872,106 | 71,885,647 | Error: ‘int XYZ::data’ is private within this context | I have one question about the following code snippet in c++ :
#include <iostream>
using namespace std;
class ABC;
class XYZ
{
int data;
public:
void setvalue(int value)
{
data=value;
}
friend void add(ABC,XYZ);
};
class ABC
{
int data;
public:
voi... | The problem is that while defining the function add, the order of the two parameters named obj1 and obj2 is opposite to what it was in the friend declaration.
So to solve this, make sure that the order of the parameters match in the definition and the friend declaration as shown below:
class XYZ
{
public:
//other ... |
71,872,131 | 71,872,809 | iterating over an unordered_set | I need help iterating over an unordered map in C++. I am trying to put the elements of the set into an array so that I can sort the array.
for(auto it=s.begin();it!=s.end();it++){
a[i]=*it;
i++;
}
| Your are using many differen terms here.
unordered_set
unordered_map
set
array
So, it is a little bit unclear what you really want to do.
If you have a std::unordered_setand want to put the data into a std::set, then you can simply use its range constructor and write something like std::set<int> ordered(s.begin(),s.e... |
71,872,152 | 71,872,153 | Unable to compile doctest's `CHECK_THROWS_AS` with Visual Studio 2019 | Consider the following code using doctest.h C++ unit test library:
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
TEST_CASE("") {
CHECK_THROWS_AS(throw 0, int);
}
The code creates a single test case with an empty name. The test ensures that throw 0 throws an exception of type int. The example comp... | Visual C++ command line compiler does not fully support C++ exceptions by default, see here. Hence, doctest disables them inside (_CPPUNWIND is left undefined by VS), but the error message is somewhat misleading.
You should pass the /EHsc compiler flag:
[REDACTED]>cl /EHsc /std:c++17 a.cpp
Microsoft (R) C/C++ Optimizin... |
71,872,205 | 71,872,668 | In template: static_assert failed due to requirement in qt c++ | I`m making an app on QT c++. And here is a problem. When I try to create Future in QT, I got many errors. Here is a bit of my code:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindo... | auto future = QtConcurrent::run( &MainWindow::SomeFunc, file_path, file_name, result_name, isProgressBar );
An immediate question comes to mind when seeing any line of code involving a pointer to a member function: "Which instance of is the method being called on?"
In this case, none, so there's obviously a problem. W... |
71,872,351 | 71,872,460 | Why Does My Multidimensional Array Works Globally, but Not Scoped? | I have a multidimensional array meant to represent 1024 * 1024 2-byte values. When I declare it in global scope, my fstream is able to read into it. When I declare it inside the same function that calls file.read, I get 0xC00000FD (stack overflow exception in windows?)
The following works, returning 0 when the program ... | By default, programs built on Micrsoft Windows using the Microsoft compiler have a default maximum stack size of about 1 MB.
The declaration
unsigned short textureMap1[1024][1024];
allocates 2 MB on the stack, if you declare it as an automatic variable. That is why the stack overflows in your case.
If you instead decl... |
71,872,381 | 71,872,848 | how to compile multiple cpp files with main methods at once? | For the sake of example i have 10 cpp files with main method.
a.cpp
b.cpp
c.cpp
d.cpp
e.cpp
f.cpp
g.cpp
h.cpp
i.cpp
j.cpp
All these scripts do different things so they have their own main method.
I have been compiling them one by one
for example
g++ -o a a.cpp
My question is is there a way to compile all c... | I'll start by stating I don't believe this question's tags are not exactly related to the problem at hand. The compilation one is the closest one but, even though, I consider the question to be more related to specific environment file selection and string manipulation than anything else.
Nonetheless there are several ... |
71,872,624 | 71,872,702 | Comparing a vector and a vector of struct for matching values - c++ | I have a vector of 6 numbers, and another vector which is a vector of my struct that contains numeric data from a file.
my vectors are as so (vec1 = 6 random nums, vec2 = file numeric data)
vec1
1, 2, 3, 4, 5, 6
vec2
4, 5, 2, 7, 34, 76
5, 7, 3, 7, 1, 23
98, 76, 5, 9, 12, 64
I need to compare vec1 to vec2 to see how m... | In your if statement you are trying to compare an element of randomnums which is of type std::string to an element of resultvec which is of type past_result. In order to compare the actual winningnums value of the struct, change your if-statement to:
if(randomnums.at(i) == resultvec.at(i).winningnums)
{
//output re... |
71,872,705 | 71,873,841 | Is swapping a const member undefined behavior? C++17 | https://godbolt.org/z/E3ETx8a88
Is this swapping UB? Am I mutating anything? UBSAN does not report anything.
#include <utility>
struct MyInt
{
MyInt(int ii): i(ii) {}
const int i;
MyInt& operator=(MyInt&& rh)
{
std::swap(const_cast<int&>(i), const_cast<int&>(rh.i));
return *this;
}
... | This seems to be an area of c++ evolution.
It's UB in c++17 because of this restriction on replacing const member objects
However, in later versions, this restriction is mostly removed.. There remains a restriction on complete const objects. For instance you can't do this if MyInt i0(0); was const MyInt i0(0);
Even tho... |
71,873,800 | 71,873,935 | std::unique_copy with overlapping ranges | template< class InputIt, class OutputIt >
OutputIt unique_copy( InputIt first, InputIt last,
OutputIt d_first );
Is it valid to use std::unique_copy if input range and output range overlap?
Consider the following two example cases
auto d_last = std::unique_copy(first, last, d_first);
d_first <= ... | The preconditions for std::unique_copy are described in
[algorithms#alg.unique-8]:
template<class InputIterator, class OutputIterator>
constexpr OutputIterator
unique_copy(InputIterator first, InputIterator last,
OutputIterator result);
Preconditions:
The ranges [first, last) and [result, resul... |
71,873,890 | 72,053,725 | How to erase line if entry it doesn't match variable | I am trying to make a program where you have to sign in with a password. If the password is incorrect it is supposed to erase the line so you can try again. Instead it just makes new lines. Any ideas on how to make this work?
cout << "--Bank Account Database--\n";
string password = "wfadmin";
string pwentry;
int entryC... | It can be done.
However, I do not know of a portable way of doing it.
The reason for that is that echoing of stdin is a console property, and not part of the C++ standard.
There is a library designed to address that problem: ncurses
Beyond that, your loop can be simplified quite a bit. (See: ideone)
If there is a porta... |
71,874,667 | 71,875,003 | Overloaded 'operator<<' must be a binary operator (has 3 parameters) | I am trying to implement Heap ADT in C++.
I am currently facing a problem in the my overloaded operator<<. I saw many solutions but non worked for me: first solution || Here is the second one
Here is the hpp file:
#ifndef Heap_hpp
#define Heap_hpp
#include <stdio.h>
#include <vector>
#include <string>
#include <iostre... | The problem is that you've defined the overloaded operator<< as a member function of class Heap instead of defining it as a non-member function.
To solve this you should remove the Heap qualification(Heap::) while defining the overloaded operator<< as shown below:
//------v-----------------------------------> removed H... |
71,874,730 | 71,876,340 | Qt5 + CMake + QThread: the signal from abstract base class is not connected to the slot in another thread | I implemented a hierarchy of classes to handle sensor interaction in a multithreaded QThread-based manner, as how it is recommended in Qt documentation. Here I have the header file types.h with the abstract base sensor reader class:
#include <QtCore>
class QAbstractSensorReader: public QObject
{ Q_OBJECT
protected sl... | You are not entering application event loop. Remove sleep from main function and call QCoreApplication::exec. I.e. replace these lines
sleep(10);
return 0;
with
return app.exec();
|
71,875,107 | 71,876,428 | How to pass a DBus variant to Qt's QDBusInterface::call | I am trying to send the following message to Connman over Qt 5.12's DBus API:
dbus-send --system --print-reply --dest=net.connman / net.connman.Manager.SetProperty string:"OfflineMode" variant:boolean:true
As seen, the SetProperty method takes a dbus string and a dbus variant.
If I look at the signature with qdbus, I ... | I have found a workaround using a different part of the API... Utilizing QDBusMessage, this can be done:
QDBusMessage message = QDBusMessage::createMethodCall("net.connman", "/", "net.connman.Manager", "SetProperty");
QList<QVariant> arguments;
arguments << "OfflineMode" << QVariant::fromValue(QDBusVariant(... |
71,875,304 | 71,875,925 | Is there an example of specializing std::allocator_traits::construct? | I have the task of porting some code to c++20. Part of it is an templated allocator that handles some of the odd needs or Microsoft COM objects so we can use them in vectors. In part, it allocates/deallocates memory via CoTaskMemAlloc/CoTaskMemFree
It also provides specializations of construct and destroy which have go... | The standard has the following to say about specializing standard library templates ([namespace.std]/2):
Unless explicitly prohibited, a program may add a template specialization for any standard library class template to namespace std provided that (a) the added declaration depends on at least one program-defined typ... |
71,875,477 | 71,876,095 | Updating value of class variables - C++ | I'm just beginning to learn how to code and I've come across a problem I can't seem to solve.
More specifically the problem occurs in the "borrows" function.
In the following program I am somehow unable to update the value of the public class variable "stock" even though I used getters and setters.
It seems to be updat... | Your actual problem is that you are operating on a copy of the Book object, not the setters and getters of the members of a book.
for(auto i:myBooks){
You need
for(auto &i:myBooks){
But as other have pointed out, you need 2 classes, Library and Book.
|
71,875,808 | 71,875,933 | How to update value in progressBar in another thread in QT c++ | I develop a qt program with an interface. I also have a complex calculation that is done on a separate thread from the ui thread. I want to update the progressBar from the thread in which the calculations are done. But I get an error that I cannot change an object that belongs to another thread.
Here is my code:
void S... | Use a signal/slot combination, specifically the queued connection type (Qt::ConnectionType). So, along those lines:
void MainWindow::Somefunc()
{
emit computationProgress(progress);
}
void MainWindow::setProgress(int progress)
{
ui->progressBar->setValue(progress);
}
void MainWindow::on_pushButton_3_clicked()
{... |
71,876,111 | 71,876,269 | When using streams do you need to sync after cudamalloc | When using streams in cuda, is it necessary to perform any synchronization between memory allocations and usage of this memory by a stream (assuming cudaMallocAsync is not available, which it is not for me).
example:
cudaStream_t stream;
cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking);
... Other code
int *a;... | There is no chance that the memory allocation will not be completed. You don't need an explicit device synchronization after a memory allocation.
When the cudaMalloc call returns, the memory is allocated and usable.
|
71,876,202 | 71,889,274 | EmguCV: Emplace one Mat onto another? | In C++ if you wanted to emplace one mat into another, the code would simply be:
clone_img.emplace(out_mat);
Now, I know in C# there is no real equivalent to the "emplace" method. If I was working with other data types in a more standard collection, I can find the answer for what I want to do on Google. Working with a ... | I found the answer for what I wanted to do, although it may not exactly answer this above question.
What I wanted to do was to create an empty Mat, and then call Mat.emplace() to put something else in it.
I found out it was as simple as doing:
Mat newMat = old_mat;
|
71,876,207 | 71,876,366 | instance of 'std::out_of_range' error disappear with a change in expression of an integer | i'm into a problem that looks like this :
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Example 1:
Input: ... | std::string::find returns an unsigned integer type, size_t. If the string isn't found, it returns std::string::npos which is the largest possible value representable in size_t. This value is outside of the range of int and gets converted to the int value -1.
This results the condition in e.g.
if(pos1<Len){
evaluating ... |
71,876,809 | 71,877,102 | Is it possible to avoid copying a temporary class instance passed to a function that saves a pointer to it? | I have a class Holder with a vector that holds instances of different classes (e.g. Derived) derived from the same abstract base class (Base). I constructed it as a vector of pointers to the base class to support polymorphism. New instances are added to the vector via a method called add. The new classes are construct... | In main
the parameter passed is a temporary destroyed just after the call to add returns. You may store this value, the address, but you must never dereference it.
If you want to ensure the the object remains valid for the lifetime of Holder your only option is taking over the ownership of an existing object or making ... |
71,876,832 | 71,877,896 | Qt how to center widget with a maximum width? | How can I horizontally center a widget in Qt, in such a way that it stretches out up to a certain size? I tried the following:
QVBoxLayout *layout = new QVBoxLayout(this);
QProgressBar *progressBar = new QProgressBar();
progressBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
progressBar->setMaximumWidth... | Can be fixed by replacing QVBoxLayout with QHBoxLayout and
replacing layout->addWidget(progressBar, 0, Qt::AlignCenter); with layout->addWidget(progressBar); progressBar->setAlignment(Qt::AlignCenter);, guess these two alignments are different.
QHBoxLayout *layout = new QHBoxLayout(this);
QProgressBar *progressBar = ne... |
71,877,509 | 71,877,734 | Constructor cannot be redeclared C++ | Tp start, I want to say that I am new to C++. I am trying to declare my constructor 3 times, because i have 3 more derived classes, which work with different variables. But i get this error, so i don't really know what to do then... The task is to create a class with derived classes of different ways of payments and pr... | That's because your constructor was redefined. The compiler doesn't care about variable names, all he sees in your case is data type.
employee(int, int, int, char *)
Which is the same in both cases
employee(int b, int spm, int pps, char *n) { //This one doesn't declare
sales_per_month = spm;
percent_per_sales ... |
71,877,651 | 71,877,712 | How to write the string representation of the contents of a file? | In my file let's assume it has the following content:
my_file.txt
/* My file "\n". */
Hello World
If I wanted generate a file and pass this same content as a string in C code, the new file would look like this:
my_generated_c_file.c
const char my_file_as_string[] = "/* My file \"\\n\". */\nHello World\n\n";
In an u... | You could simply print a '\\' wherever a '\' was present in the original file:
while (size--) {
char next_c = getc(fp_in);
if(next_c == '\\') {
fputs("\\\\", fp_out);
}
else {
fputc(next_c, fp_out);
}
}
You'll probably also want to perform other such transformations as well, such as r... |
71,877,876 | 71,878,112 | How to remove trailing zeros with scientific notation when convert double to string? | Live On Coliru
FormatFloat
I try to implement one conversion of Golang strconv.FormatFloat() in C++.
#include <sstream>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
std::string convert_str(double d)
{
std::stringstream ss;
if (d >= 0.0001)
{
ss << std::fixed << std... | At the risk of being heavily downvoted criticised for posting a C answer to a C++ question ... you can use the %lg format specifier in a call to sprintf.
From cpprefernce:
Unless alternative representation is requested the trailing zeros are
removed, also the decimal point character is removed if no fractional
part is... |
71,878,217 | 71,878,326 | Input validation C++ | I need help with input validator, whenever the console gets a wrong input, it does the job to determine whether the input is valid or not but here I have a problem where if I put a wrong input first, I have to re-enter the next input twice for it to go to Enter operator line.
#include <iostream>
#include <windows.h>
u... |
I have to re-enter the next input twice
That is because you are asking for input twice:
while (! (cin >> num1))
{
...
// Ask for the input again
cout << "(!) Enter first number >> ";
cin >> num1; // <--
}
If the user enters bad input, !(cin >> num1) is true, so the loop is entered, and then cin >> n... |
71,878,695 | 71,878,892 | How to save a persistent value for application access across multiple runs? | As the title states, I would like to store a variable (which will always be an positive integer < 10,000) for my application to access and process as needed across multiple runs.
My current implementation simply saves the value to a file, in the current directory, and then reads it in when needed.
#include<fstream>
in... | There is nothing wrong with using a file, but you don't have to (and should not) store it in the same folder as the .exe file, as it may not work depending on where the .exe is located (for instance, non-admins can't write to Program Files).
Windows sets aside special folders in the user's profile just for application-... |
71,878,766 | 71,878,828 | How to read n to n + i lines in c++? | This is the file to be read
5
Name1
Name2
Name3
Name4
Name5
My current code to read this is:
void readData(string fileName, string names[], int n) {
ifstream myFile("file.txt");
string line;
if (myFile.is_open())
{
myFile >> n; // read first line
cout << n;
for (int i = 0;... | You didnt read the whole first line when you did myFile >> n. So the first getline just read the rest of that line, which is empty
Do
myFile >> n;
getline(myFile, line); // read rest of line
or
getline(myFile, line); // read whole line
n = stoi(line); // convert to int
|
71,879,059 | 71,886,748 | fstream doesn't read the input Visual Studio Code but it works in Visual Studio Community | The code below works properly in Visual Studio Community 2019, the input file opens and gets read.
When I try the same code in Visual Studio Code, it doesn't work, and returns "access denied".
I need to use Visual Studio Code.
The input file is in the .exe's directory in case of Visual Studio Code, and in the .cpp's di... | Try to give the full location of the file.
file.open("C\..\input.txt");
|
71,879,337 | 72,507,796 | Difference between calculating in line or two lines | Here is my code in C++. I'm using g++-11 with gcc version 11.2.0.
#include<iostream>
#include<vector>
#include<algorithm>
#include<cmath>
#include<map>
using namespace std;
int main()
{
string t="90071992547409929007199254740993";
//separateNumbers(t);
unsigned long long stringNum=0;
for (int j=16;j... | As mentioned in @PaulMcKenzie's comment, the source of the difference is mixing floating-point arithmetics with integers.
Some more info for those who are interested:
The difference manifests in the last iteration of your loop.
In the first case, you have:
stringNum += (t[j]-'0')*pow(10,32-j-1);
which is equivalent to... |
71,879,408 | 71,886,825 | Persistent storage in Lambda C++ | I am wanting to create a lambda that can store intermediate data between calls. Is this something that is possible? I never hit the Tokens Persisted even after the Storing Tokens is printed.
auto process = [&in, &out, callback, tokens = std::deque<O>{}]() mutable {
// Debug this is never reached
... | I achieved what I wanted by creating a shared_ptr and passing that into the process lambda. This allows each creation of process to have a unique buffer that it can store results in case of back pressure from the out.
auto t = std::make_shared<std::deque<O>>();
auto process = [&in, &out, callback, tokens = t]() mutab... |
71,879,753 | 71,898,152 | MacOS LLDB | Thread 1: EXC_BAD_ACCESS (code=1 & 2, address=0x123456789) | So to start, I am not too knowledageble in C++, I know very little from a class I took a while back. Almost everything I have so far is from this very generous and knowledgable community.
I have to use a wack piece of custom software for work on MacOS and it doesn't have any form autosave and it occasionally likes to c... | With assembly explanations from @Peter Cordes I managed to solve my issue.
@Peter Cordes: addb %al, (%rax) is how 00 00 decodes. Crashing there indicates that execution jumped to some memory that's all zeros, perhaps due to overwriting a return address or function pointer. Or if you have any hand-written asm, due to... |
71,879,770 | 71,917,565 | Accumulating Doubles Into Bins via intrinsics | I have a vector of observations and an equal length vector of offsets assigning observations to a set of bins. The value of each bin should be the sum of all observations assigned to that bin, and I'm wondering if there's a vectorized method to do the reduction.
A naive implementation is below:
const int N_OBS = 100`00... | Modern CPUs are surprisingly good running your naïve version. On AMD Zen3, I’m getting 48ms for 100M random numbers on input, that’s 18 GB/sec RAM read bandwidth. That’s like 35% of the hard bandwidth limit on my computer (dual-channel DDR4-3200).
No SIMD gonna help, I’m afraid. Still, the best version I got is the fol... |
71,879,837 | 71,880,103 | A Hugeint object + Hugeint object = garbage value. Huh? | I'm making 2 Hugeint objects with this constructor
HugeInt.h
public:
static const int digits = 30; // maximum digits in a Hugelnt
HugeInt( long = 0 ); // conversion/default constructor
HugeInt( const string & ); // conversion constructor
//addition operator; Hugelnt + Hugelnt
HugeInt operator+(... | Your major problem is that you hard code maximum number of digits you can deal with to 30
But
9999999999999999999999999999999999
1234567890123456789012345678901234
this string is 34 digits
Plus you build the result of the add into 'temp' but do nothing with it
added
return temp;
increased digits to 40
n6 = n3 + n... |
71,880,112 | 71,880,157 | Why c++ no more shows index out of range on giving index for accessing character of a string, which is more than the length of string? | Think C++ Allen B. Downey, chapter 7, section 7.6 A run-time error
After reading the excerpt about run time error and index out of range error in c++. I tried to execute the same in my compiler of c++ which is running in vs code. But even on trying positive out of range index as well as negative index. I wasn't getting... | When you wrote:
char a = user_input[100];//this is undefined behavior
The expression user_input[100] leads to undefined behavior because you're going out of range of the std::string. If you want to make sure that you get an error while accessing out of range elements, then you can use std::string::at member function l... |
71,880,135 | 71,880,170 | How to use lambdas to use std::function with member functions? | I'm trying to move some global functions inside a class. The current code looks like this:
struct S{};
void f(S* s, int x, double d){}
void g(S* s, int x, double d){}
/*
...
...*/
void z(S* s, int x, double d){}
int main()
{
function<void(S*, int, double)> fp;
//switch(something)
//case 1:
fp... | Member functions require a specific class object to invoke, so you need to do
function<void(S*, int, double)> fp = &S::f;
fp(this, x, d);
Or use lambda to capture a specific class object and invoke its member function internally
function<void(int, double)> fp = [this](int x, double d) { this->f(x, d); };
fp(x, d);
D... |
71,881,347 | 71,881,782 | Bring nested name into scope in non-member function | I have a struct B that contains the declaration of a type anchor_point as a nested name. How can I bring anchor_point into scope in another function using the using-directive? I basically want to access the type as is without qualifiying it (just like from within a member function). I tried the following (see comments)... | As you have shown you can do
using anchor_point = B::anchor_point;
repeated for every relevant member. This has to appear only once in the scope enclosing all your uses of the member that you want to cover.
There is no other way, in particular no equivalent to using namespace for namespaces which makes all members vis... |
71,882,268 | 71,882,337 | For loop does not work (and Visual Studio gives a warning), why? | I isolated my code to the following test program:
#include <iostream>
using namespace std;
int main()
{
cout << "Begin" << '\n';
for (unsigned int c = '\200'; c < 256; c++)
{
cout << c << '\n';
}
cout << "End";
return 0;
}
And the for loop does not run, why?
I suspect it has to do wi... | Yes, the literals are in octal, but that does not matter. You would still have the problem with hex literals, too.
The real problem is that the literals are using the char type, which is either signed or unsigned by default, the C++ standard leaves it up to the compiler implementation to decide which to use (some compi... |
71,882,752 | 71,884,790 | C++ constexpr std::array of string literals | I've been happily using the following style of constant string literals in my code for awhile, without really understanding how it works:
constexpr std::array myStrings = { "one", "two", "three" };
This may seem trivial, but I'm hazy on the details of what is going on under the hood. From my understanding, class templ... | As user17732522 already noted, the type deduction for your original code produces a const std::array<const char*, 3>. This works, but it's not a C++ std::string, so every use needs to scan for the NUL terminator, and they can't contain embedded NULs. I just wanted to emphasize the suggestion from my comment to use std:... |
71,882,767 | 71,883,693 | Multi-threaded input processing | I am new to using multithreading and I am working on a program that handles mouse movement, it consists of two threads, the main thread gets the input and stores the mouse position in a fixed location and the child thread loops through that location to get the value. So how do I reduce CPU utilization, I am using condi... | Using std::condition_variable is a good and efficient way to achieve what you want.
However - you implementation has the following issue:
std::condition_variable suffers from spurious wakeups. You can read about it here: Spurious wakeup - Wikipedia.
The correct way to use a condition variable requires:
To add a variab... |
71,882,880 | 71,900,452 | QMainWindow with member QWidget and QLayout crashes on exit, how to fix that? | The following is a single-file QWidget program.
//main.cpp
#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QLabel>
class MainWindow:public QMainWindow{
QLabel lb;
QWidget wgt;
QVBoxLayout lout{&wgt};
public:
MainWindow(){
lout.addWidget(&lb);//line A
setCe... | While the problem is due to an attempt to free memory that wasn't allocated on the heap I don't think the QMainWindow destructor or a 'double-delete' is the culprit (as suggested elsewhere).
As well as deleting its children the QObject destructor will also remove itself from any parent's object hierarchy. In the code ... |
71,883,192 | 71,883,257 | Reading CSV file lines with hex content and convert it to decimal | Here is my CSV file and its contents are in hex.
a3 42 fe 9e 89
a3 43 14 9d cd
a3 43 1e 02 82
a3 43 23 bd 85
a3 43 39 d5 83
a3 43 3e b9 8d
a3 43 3f 44 c0
a3 43 50 c9 49
a3 43 67 29 c8
a3 43 67 43 0d
I need only the second-last value and the code to extract that value is this.
void getvalues(){
std::i... | If you want to convert a string to an integer, you can use std::stoi, which is included in the string package. By default, you can use stoi as such:
int num = std::stoi(cell)
However since we want to parse a base 16 hex number, then we need to use it like:
int num = std::stoi(cell, 0, 16)
Quick article about this: ht... |
71,883,343 | 71,887,365 | How to write to file in C++ | I've tried to write to file in C++ on a mac in different ways and I can't.
I've used:
int bestScore = 3;
QFile data("bestScore.txt");
data.open(QIODevice::WriteOnly);
QTextStream out(&data);
out << bestScore;
data.close();
int bestScore = 3;
FILE *out_file = fopen("bestScore.txt", "w");
if (out_file == NULL)
{
q... | First thing you need to include fstream.
Second you declare the name of the file as an variable.
You need to open it.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
If ... |
71,883,656 | 72,577,297 | How to add a administrative template in Group policy with C++? | I'm on Windows. Adding a administrative template in Group policy is easy, you just go to the gpo where you want to add the template, then right click, add template. I want to do this with C++, I looked at msdn and I only discovered functions where I can add a new gpo, but I couldn't find a function to add a template.
T... | I solved it a long time ago. The only thing the registry does is this: creating/deleting keys. When you use LGPO it actually creates those keys. You can manage registry keys using Windows API.
You can also track the changes in the registry using a software or just simply pressing ctrl + f to search for those keys so yo... |
71,884,084 | 71,884,171 | malloc size modified after changing stored value? | I have a program that uses malloc to allocate a void-typed space for my program
the value I pass to malloc is 1 so it should allocate 1 byte.
Now I cast the pointer to int and modify it's value to int (eg, 280).
I am pretty sure that an int needs 4 bytes of memory to be stored, and I know for a fact that
280 is represe... | Malloc only allocates one byte but has no mechanism to avoid that you write on other memory addresses, by writing 4 bytes in the address of p you write the allocalted byte + 3 other consecutive bytes.
After that when you deference the pointer you read 4 bytes that are the same ones you just wrote.
What you are doing is... |
71,884,116 | 71,884,384 | Why does C++ sometimes not identify overloaded operators? | I have been scratching my head at a problem with my program. At lines 4-6, I overload operator== to accept an int and a pair<int,int>. Then I try it at line 9. It works. So then, I try it at line 10, with find(). It... fails. C++ says that it can't find a operator==() overload that accepts an int and a pair<int,int>, e... |
Then I try it at line 9. It works.
Your main can see the overload of operator== you declared but std::find
cannot. The only way for std::find to call your operator is through
argument-dependent lookup (ADL).
However, ADL won't find your operator== because it is not part of the innermost enclosing namespace of std::pa... |
71,884,150 | 71,884,190 | Why can't cmd recognize g++ | I installed the MinGW Compiler but when I type g++ in cmd, it just tells me that it's not recognized. But it is RECOGNIZED in every IDE/programming app I tried.
I'm sorry if this is another not-recognized question, but none of the solutions I found on the Internet worked.
| SET PATH=C:\MinGW\bin;%PATH%
set the path via cmd (or manually) before running your commands
|
71,884,636 | 71,884,827 | Forward Declaration using for a template method | Why do I get an error when using a template method with a forward declared class? I don't actually need a definition of this class, only a declaration. Or maybe I have misunderstood how it actually works? Do I really need to include a corresponding .h file of class B?
Edited:
And why then does forward declaration of cl... |
Why do I get an error when using a template method with a forward declared class?
This is not generally a problem.
I don't actually need a definition of this class, only a declaration. Or maybe I have misunderstood how it actually works?
There is no general rule that template parameters need to be complete types, b... |
71,884,726 | 71,885,159 | template class has no acceptable convertion | The following code works fine:
struct A {
int d;
A(int _d) : d(_d) {}
};
A operator+(const A& x, const A& y) {
return x.d + y.d;
}
int main() {
A x = 6;
cout << (x + 4).d << endl;
cout << (4 + x).d << endl;
}
However, if I make A a template class, then it doesn't compile:
template<int p>
struct... | The problem is that template argument deduction doesn't consider implicit conversions like the one converting constructor that you've provided.
From template argument deduction's documentation
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload ... |
71,885,147 | 71,885,217 | Create and fill a 10 bits set from two 8 bits characters | We have 2 characters a and b of 8 bits that we want to encode in a 10 bits set. What we want to do is take the first 8 bits of character a put them in the first 8 bits of the 10 bits set. Then take only the first 2 bits of character b and fill the rest.
QUESTION: Do I need to shift the 8 bits in order to concatenate ... |
Do I need to shift the 8 bits in order to concatenate the other 2?
Yes.
The bits of a have to be shifted left to make room for the two bits of b. As there is room needed for two bits a left shift by 2 is appropriate. (Before my recent update, there was a wrong left shift by 8 which I didn't notice. Shame on me.)
The ... |
71,885,286 | 71,885,369 | is using an integer to store many bool worth the effort? | I was considering ways to reduce memory footprint, and it is constantly mentioned that a bool takes up more memory than it logically needs to, as a byproduct of processor design.
it is also sometimes mentioned that one could store several bool within an int.
I am wondering if this would actually be more memory efficien... | You are describing a text book example of a trade-off.
Yes, several bools in one int is hugeley more memory efficient - in itself.
Yes, you need to spend code to use that.
Yes, for only a few bools (for different values of "few"), the code might take more space than you save.
However, you could look at the kind of memo... |
71,885,720 | 71,885,920 | Apparent bug in clang when assigning a r value containing a `std::string` from a constructor | While testing handling of const object members I ran into this apparent bug in clang. The code works in msvc and gcc. However, the bug only appears with non-consts which is certainly the most common use. Am I doing something wrong or is this a real bug?
https://godbolt.org/z/Gbxjo19Ez
#include <string>
#include <memory... | Yes this is a libstdc++ or clang issue: std::string's move constructor cannot be used in a constant expression. The following gives the same error:
#include <string>
constexpr int f() {
std::string a;
std::string b(std::move(a));
return 42;
}
static_assert(f() == 42);
https://godbolt.org/z/3xWxYW717
http... |
71,885,770 | 71,885,820 | C++ memory leak. Valgrind - mismatched delete | I receive objects from Thread #1 - its a 3rd party lib code - my callback called on it.
Objects have fixed-length string fields wrapped:
typedef struct somestr_t {
char * Data;
int Len; } somestr_t;
I have to create copy of the objects by hand every time, before I can pass it further to my code. So amongst ... | char* data = new char[src->Len];
and
if (someobj ->somestr.Len != 0) delete someobj ->somestr.Data;
That delete should be delete [].
Why are there still reachable: 425,333 bytes in 3,860 blocks. Sorry, my crystal ball isn't working.
Normally Valgrind does give a hint as to what you need to do
==19283== Rerun ... |
71,886,042 | 71,886,761 | Is there a higher performing implementation of powf(10,floorf(log10f(x))) | I have a need to truncate a float to the nearest power of 10. For example, 1.1 would truncate to 1.0 and 4.7e3 would truncate to 1e3. I am currently doing it with the seemingly complicated powf(10,floorf(log10f(x))). I am wondering whether there is a better performing (as in faster execution speed) solution? My target ... | It is possible to use a lookup table to speed up the computation. This technique should work for all normal floating point numbers. Subnormal numbers and NaN won't work without some dedicated logic, 0 and infinity can be handled by extreme values in the table.
Although I expect this technique to be actually faster than... |
71,886,160 | 71,886,291 | How to use classes prototypes in C++? | I study C ++, I am also not strong in it, so do not judge strictly, played with classes, and decided to make 2 classes so that you can try their prototypes, to which I received in response, in the 1st case, not a complete description of the class, and in the second There is no access to the fields and in general to cla... | Before befriending a member function, there must be a declaration for that member function in the respective class(which is human in this case).
To solve this you can declare the member function before and the define it afterward the class apple's definition as shown below:
class apple; //friend declaration for apple
c... |
71,886,342 | 71,886,391 | How to separate a two digit hexadecimal number into its digits? | Suppose I have a hexadecimal number 4e. How to get 4 and e separately and store it in two separate variables?
| if you mean 'how can I get the upper and lower nibbles of a byte into two variables'
char x = 0x4e;
int low = x & 0x0f;
int high = (x & 0xf0) >> 4;
|
71,886,441 | 71,888,951 | (C++) How to write a clone method for a class which has a unique pointer as a data member? | I have the following set up:
class Base {
private:
// data members
public:
// methods
// pure virtual methods
virtual Base* clone() const =0;
}
class Derived : public Base{
private:
// more data members
public:
// more methods
// pure virtual methods overridden
Derived* clone() const override{
return new Derived(*this... | Simply add a copy constructor to DecoratedDerived that clone()'s the data member, eg:
class DecoratedDerived : public Base {
private:
unique_ptr<Base> ptr;
// ...
public:
DecoratedDerived(const DecoratedDerived &src)
: Base(src), ptr(src.ptr ? src.ptr->clone() : nullptr)
{
}
// ...
... |
71,886,569 | 71,886,952 | cmake on Mac with ARM M1 is running linker with x86_64 architecture instead of arm64 | I am trying to compile glfw from source on Mac with M1 arm64 processor, and while running the linker, cmake strangely is trying to link the project for x86_64 architecture, while the binaries were built for arm64.
I clone the project, create build folder named cmake-build-debug, generate build system in it with the Mak... | For anyone running into the same problem, it looks like the first version of cmake with an adequate support for Apple Silicon is 3.19.
I was using 3.17.5 as my slightly out-of-date version of CLion does not support versions of cmake above that.
After an update to cmake 3.22.4 the problem is gone.
|
71,886,576 | 71,887,705 | why can CMake Build files not be generated correctly | I am trying a simple test to see if CMake is working on my windows system correctly.
I keep getting a error.
Here is the command with the error.
cmake .
-- Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.19044.
-- Configuring done
CMake Error at CMakeLists.txt:5 (add_executable):
No SOURCES given to t... | Can't add a comment since my reputation is too low, so I will write an answer instead. In the last line of your CMakeLists.txt file
add_executable(main.cpp)
you are missing the name of the executable
add_executable(name_exe main.cpp)
CMake is telling you that in the error message. CMake tries to create a target main.... |
71,886,827 | 71,887,466 | Is it ok that with fp:fast 3000.f/1000.f != 3.f? | I'm using MSVC 2019 v16.11.12.
When I tried compiling my code with /fp:fast instead of /fp:precise, my tests started failing.
The simplest case is:
BOOST_AUTO_TEST_CASE(test_division) {
float v = 3000.f;
BOOST_TEST((v / 1000.f) == 3.f);
}
Failing with result:
error: in "test_division": check (v / 1000.f) == 3... | One of the optimizations which is enabled by gcc's -ffast-math option (and probably msvc's /fp:fast option) is converting a "divide by constant" into a "multiply by reciprocal", as floating point divides are quite slow -- on some machines more than 10x as expensive as a multiply, as multipliers are commonly pipelined w... |
71,887,767 | 71,887,824 | cannot overload functions distinguished by return type alone but it is not a real mistake | I have different variants of some function, that are choosed by preprocessor definition
#if defined(V2)
bool getAICoord(TTT_Game& game) {
//
// 4x4 field
//
return false;
}
#elif defined(V3)
bool getAICoord(TTT_Game& game) {
... | You could workaround this error by only typing the function signature once and using the preprocessor definitions on the body of the function; e.g.
bool getAICoord(TTT_Game& game) {
#if defined(V2)
//
// 4x4 field
//
return false;
#elif defined(V3)
//
// renju field
//
return false;
#els... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.