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 |
|---|---|---|---|---|
63,535,031 | 63,535,449 | XAudio2 false Targeting windows version | I'm using XAudio2 to run SteamWorksExample game to see how can i include steam stuffs inside my C++ based game, I'm using Windows 10 but when i run code, I got this error:
"This version of XAudio2 is available only in Windows 8 or later. Use the XAudio2 headers and libraries from the DirectX SDK with applications that ... | check your VC++ directories, if they are like that:
Include Directories: $(IncludePath);$(DXSDK_DIR)Include
Include Library Directories: $(LibraryPath);$(DXSDK_DIR)Lib\x86
delete them.
in my case, it solved problem
|
63,535,233 | 63,536,227 | Why does constexpr not cause compilation to fail on index out of bounds | I wrote a small helper function in my c++ project which should convert values of an enum to a predetermined list of strings. I wrote it like this:
#include <stdint.h>
#include <iostream>
enum things{
val1 = 0,
val2,
val3,
val4
};
constexpr const char* things_strings[4] = {"A", "B", "C", "D"};
conste... | Yes, but you're calling the function at run time. If you call this function in a compile time context, e.g. by assigning to a constexpr variable, you'll get a compile time error:
constexpr auto c = get_thing_string(static_cast<things>(12)); // error
Here's a demo.
Note that in c++20, you can make the function conste... |
63,535,262 | 63,535,490 | smooth 64bit input from vertex to frag shader - "error C7570: 64 bit input should be flat" | I've made a small program in OpenGL that draws the Mandelbrot set, however I am having some trouble using 64bit values in my fragment shader. Everything works as intended when i use the vec2 type in my shaders like so and an array of doubles for my vertex array in c++:
#shader vertex
#version 410 core
layout(location ... | The type of the fragment shader input
in dvec2 frag_mandelbrot;
is a double-precision floating-point type.
See the most recent GLSL specification, OpenGL Shading Language 4.60 Specification (HTML) - 4.3.3. Constant Expressions
[...]
Fragment shader inputs that are, or contain, integral or double-precision floating-po... |
63,535,786 | 63,536,414 | What happens when you return a reference from a c++ function? | The question is not why and when one should use it. I'm wondering what exactly happens in the inferior level, because we get really curious results doing it.
For example, it is clear when you use it like this:
int& func(int& num) {
++num;
return num;
}
Here we pass a variable by reference, change it, and retur... | Well, I compiled your code with g++ version 5.4.0.
So I've been wondering:
Why are we not getting a compilation error returning a reference to a non existent object?
The compiler doesn't give an error, but it does give you a warning.
sampe.cpp: In function ‘int& func(int)’:
sampe.cpp:6:15: warning: reference to loc... |
63,535,891 | 63,647,486 | GLFW can't find VK_KHR_win32_surface in MinGW | Description
Currently my program runs on MSVC without any problems but on MinGW glfwCreateWindowSurface(...) strangely throws an error that it's missing the VK_KHR_win32_surface extension.
Surface Code
void createSurface() {
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) {
t... | Fixed by using GLFW Native since it works:
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
// ...
VkWin32SurfaceCreateInfoKHR surfaceInfo {};
surfaceInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
surfaceInfo.hinstance = GetModuleHandle(nullptr);
surfaceInfo.hwnd = glfwGetWin32Window(wind... |
63,535,958 | 63,536,146 | problem caused due to changing the size of array , during finding the frequency of charcters | #include <iostream>
using namespace std;
int main()
{
string s;
int hash[256];
getline(cin, s);
int max = 0;
char ch;
for (int i = 0; i < s.size(); i++)
{
hash[s[i]]++;
if (hash[s[i]] > max)
{
max = hash[s[i]];
ch = s[i];
}
... | First of all: An array in C++ will not be initialized and can contain arbitrary data. Using uninitialized values will result in undefined behavior.
Why does changing the size the array changes anything?
When you invoke undefined behavior anything can happen. Technically deleting all your files would be a "correct" impl... |
63,536,093 | 63,574,633 | What's the equivalent of numpy.spacing(1) in libtorch? | It seems pytorch does have/expose the finfo link, but I can't find it in libtorch. Is it even made available in libtorch yet or not? Using the torch.finfo I could easily do:
esp = torch.finfo(torch.float).eps
which I believe is the counterpart/equivalent of np.spacing(1) but in libtorch I can't do the same thing as I ... | It turns out, we can simply use std::nextafter just fine. And also torch::nextafter is recently added (#42580) and uses this under the hood!
So if you don't use nighlybuilds, and until 1.7 ships, you can simply use std::nextafter just fine! Concerning the THPFinfo:
THPFInfo and THPFInfo_eps exist to make this informa... |
63,536,242 | 63,536,745 | I'm getting std class vector has no member error for all my vector methods | My professor sent me the code and most of it works but this part is having problems. All the methods from vector class are showing error. I don't have much experience with c++ but I need to run the code. He was running the same code and it was working just fine.
error is: class "std::vector<int, std::allocator >" has n... | I was missing windows sdk. Installing them worked.
https://developercommunity.visualstudio.com/content/problem/958134/error-c1083-yvalsh-unable-to-include-crtdbgh.html
|
63,536,305 | 63,536,342 | Should I use the 'const' keyword in c++ | I am new to C++ and have come across the const keyword. I looked it up online and read that The main use is to prevent the changing the value throughout the program. I have these two snippets below
const int size = 56;
Compared to using
int size = 56;
Why should I use one over the other? What is the idea behind using... | Yes, you should make all variables const if you are never going to change its value after initialization. This prevents bugs where you accidentally change a value you're not supposed to. You seem to be aware of this already.
In addition, there is something that you might not be aware of, which is that making an int var... |
63,536,457 | 64,186,068 | OpenGL empty project uses too much CPU | I have created a simple OpenGL program, following the LearnOpenGL tutorial. It just creates a window and fills it with a color. I am using Visual Studio 2019.
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput... | You can enable vsync with glfwSwapInterval(1)
|
63,536,533 | 63,536,683 | What's the difference between delete[] and ::operator delete() in c++ | I was watching a youtube series about data structures and how to made our-self data structure.
But then the Instructor replaced the new[] with ::operator new() and delete[] with ::operator delete(), is there any difference? cuz this is the first time for me to see the ::operator thing in c++
| The new-expressions new T and new T[n] create objects in memory that they acquire.
The delete-expressions delete p and delete [] p destroy objects and release the memory where they were stored.
operator new is a memory allocation function, and operator delete is a memory deallocation function. They do not do anything ... |
63,536,758 | 63,557,960 | Is there any way to use both Borland Compiler and graphics.h in CodeBlocks? | I am currently trying to use both Borland Compiler in CodeBlocks as I do not find Turbo C and its environment suitable for coding. Now I realize that graphics.h library is not working in CodeBlocks while using Borland Compiler. I know there is a way while using MinGW compiler, but I need to write other programs in Borl... | To work with CodeBlocks, the advice is to install the latest version (20.03).
However, CodeBlocks has long been able to use the Borland bcc32 compiler (version 5.5 or 5.6, it seems to me) by setting the toolchain paths appropriately.
While using the Borland compiler from CodeBlocks, this does not allow you to use the ... |
63,537,050 | 66,404,015 | Visual Studio 2019 Always run OLD version code | I tried many things that searched on google.
listing I had.
Project -> Property -> Debugging -> Debugging = Auto
Build -> Configuration Manager -> Check OK "BUILD" option ( Also I checked solution platforms and configs. )
Tools -> Option -> Build & Run -> Always Build. and Uncheck "just startup project & dependencys"
... | I had the same problem. Looking for days but finally i found a solution.
The first step is to completely delete Visual Studio (installer as well,yes) and then install it again.This time check on "general options" and not "recommended for C++" in the beginning of the installation(Its where you choose the color of the ID... |
63,537,196 | 63,537,219 | Why do i get a wrong value for `i` integer? | Below I have simple C++ code to generate numbers with a length of 18. When I call the gen_nums function, i is equal to 1569325055 as if the number that I assign to the i variable was too big for it.
#include <iostream>
using namespace std;
void gen_nums(){
int i = 99999999999999999;
cout << i <<endl;
}
int... | It may be because you're assigning a value to int that is outside of its range.
When you assign an int outside its range, the behavior is implementation defined.
Some compilers truncate the higher bits to the width of the integer type you are assigning it to.
If you really want to use such large numbers, maybe use a lo... |
63,537,299 | 63,537,493 | c++ shared_ptr<map<int, int>> initialized with different comparison function, any way? | if I have a field in class like below,
class MyClass {
public:
shared_ptr<map<int, int>> my_map;
}
The default map<int,int>'s comparison function is less<int>, but I would like to initialize my_map as
my_map = make_shared<map<int, int, greater<int>>>();
sometimes,
This doesnt compile, what other way I can have a ... |
what other way I can have a shared_ptr<map<int, int>> that in two different object of MyClass, one has less<int> and the other have greater<int> so that the my_map in each object is sorted differently?
You can specify std::function as the template argument for comparator as
std::shared_ptr<std::map<int, int, std::fun... |
63,537,346 | 63,537,745 | 'windows.h', what about other platforms? | I'm using visual studio on windows and I have this header file called windows.h which of course gives me access to the win32 API.
but when I try to use other platforms API like the linux API for example. I don't find any header file with that name, which mean that I can't use any other OS API than windows,
now the prob... |
but when I try to use other platforms API like the linux API for example. I don't find any header file with that name
There is no header called <linux> for the system API. The POSIX operating system specification (which Linux conforms to) lists several headers which contain the functionality that you might find from ... |
63,537,619 | 63,537,680 | How can I implement the behavior of unique in matlab using C++? | In Matlab, the [C, ia, ic] = unique(A) function returns an sorted array C in which the duplicates in A are removed, and the ia and ic arrays contains the indices such that C = A(ia) and A = C(ic). For example:
A = [1, 2, 3, -1, -2, 0, 0, 0, 4];
[C, ia, ic] = unique(A);
C = [-2, -1, 0, 1, 2, 3, 4];
% The indices are ... | The answer is very similar to how you calculate ic. Just swap A and C in the transform call:
std::vector<int> ia;
ia.reserve(C.size());
std::transform(C.begin(), C.end(),
std::back_inserter(ia),
[&](int x) { return std::distance(A.begin(),
std::find(... |
63,537,774 | 63,537,848 | Possible to output console result into text file? | I am required to store the below console data into a text file:
enter image description here
However, the name of the textfile of where the output will be placed in is typed in by the user. I am unable to find a proper way to store all the console data in the requested text file. Since I use width and special spaces I ... | When you are sending text into cout you are basically writing to a file already, just a system standard one called stdout. You simply need to open a different output file stream and send the output the same way.
#include <iostream>
#include <fstream>
using namespace std;
ofstream out = ofstream("file.txt", ios::out);
... |
63,538,556 | 63,538,863 | How does c++ handle memory for local variables when passing them by reference? | I think I get the functionality -- passing a reference into a function passes the address, so modifications to a_val and b_val in get_point below change the values of variables in calling_func.
What I don't understand is how this is actually achieved -- are the values moved to heap space and their addresses passed into... | Or can addresses from the calling_func stack frame be passed into get_point and modified there?
Exactly; the stack grows downwards for each function when called, and the callers stack space above is still valid when calling the callee. Usually this is achieved by passing a pointer wherever the argument would've been p... |
63,538,956 | 63,539,389 | What could explain this strange behaviour in GDB? | When I step through the following code with GDB, the execution flow progresses in an unintuitive way. Specifically, when it steps into f, the first line it goes to is the return statement.
#include <iostream>
int f(int m) {
int arr[m];
std::cout << "hello" << std::endl;
return 0;
}
int m... |
What could explain this behavior,
Your tests explain it fairly well, no? It is caused by having a variable length array. If you want a deeper explanation, the executable is probably allocating space for the array on the stack. This confuses the debugger for a bit because memory locations have changed from what was de... |
63,538,976 | 63,540,159 | Encrypt file with openssl with secure strings | I am trying to encrypt a file with openssl in c++.
I am using the examplecode in evp-encrypt.cxx where a new datatype called secure_sting is used for the encryption.
My problem is that I dont know how to read the file in a way that i can still use the secure_string datatype to encrypt.
The important code part is:
templ... | ptext = str.c_str(); solved the problem
|
63,539,054 | 63,540,309 | DATA_ERROR when reading zlib/miniz deflated data | I am writing a simple C++ wrapper for miniz-cpp's implementation of zlib compression. I got deflation to work, but now I have a problem with inflating the data again.
Code
I have a test case which (grossly simplified) boils down to:
ByteArray randomData = createRandomData(1024 * 1024);
ByteArray deflatedBytes = deflate... | This is an anticlimactic solution, but as it turns out I should have used the actual miniz instead of the single-header mirror which is miniz-cpp. This single-header library is using a severely outdated version of the library from 2017 and simply couldn't read the data correctly.
When using the actual miniz, the test p... |
63,539,106 | 63,539,156 | delete[] operator in C++ not working as it should | Please have a look at this below code::
#include<iostream>
using namespace std;
int main()
{
int *ptr;
ptr = new int[100000];
cout<<"\n\n address = "<<ptr;
for(long int i=0;i<100000;i++)
*(ptr+i) = i+1;
delete []ptr;
cout<... | delete[] is working just as it should. It ensures that destructors are called for the members of the array and marks the memory (internally) as available for re-use.
There's nothing in the C++ standard that says it has to zero the memory or return the memory to the OS or clear the variable holding the address you passe... |
63,539,353 | 63,696,614 | How to read LoRa Messages in Serial monitor via heltec esp32 | I am new to the esp32 and LoRa messaging.
I am following the two examples in the heltect esp32 lora library.
The two modules I am using to send and receive data have an oled display... and I print their values to the serial monitor. The data values appear on the oled display but they are random characters in the serial... | Perhaps, the serial monitor is configured with the wrong Baud Rate? In my case, default in IDE was 9600, but ESP32 sent with 115200. You can change the Baud Rate in a combobox in the serial monitor.
|
63,539,729 | 63,539,793 | Vector Subscript out of range when decrementing from 100 to 0 | I debugged this error, and I cannot understand the reason as to why this vector subscript is going out of range. I have also looked at this link but it was to no avail:
Vector subscript out of range
I have a class called board with a private data member vector<int> m_Board_board. In the board constructor, I am initial... | They are not doing the same!
Your m_Board_board has 100 elements in it, meaning the indexing start from 0, 1, 2,..., 99 and in the first code, in the loop
for (int i = 100; i > 0; --i) {
you are starting the index 100. This is trying to accessing the non-existing element in the vector vis std::vector::operator[], whic... |
63,539,896 | 63,539,972 | I Cant Reach Vector of Class Methods ! What should i do? | **Its header file**
#ifndef MUSTERI_H
#define MUSTERI_H
#include <string>
using std::string;
class Musteri
{
public:
string ad;
void SetAd(string);
string GetAd();
};
#endif
its cpp file
#include "Musteri.h"
#include <string>
void Musteri::SetAd(string deger)
{
ad=deger;
}
string M... | From the code you have posted (which is apparently incomplete, as your definition of class Musteri does not contain any member function called SetSoyad...) and a quite unclear question, one can only guess what your problem is. What does "I can't reach" mean?
However I have a feeling that you have problem with either he... |
63,540,048 | 63,574,968 | Where exactly is macro $(VCTargetsPath) defined? | We had a discussion before.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/e04e7791-c0c4-4598-b900-310878f5af45/how-can-i-locate-and-change-the-vctargetspath-variable?forum=msbuild
After hours searching .props files, all the $(VCTargetsPath) in .prop and .targets are deleted, but Visual Studio can still recogni... |
Where exactly is macro $(VCTargetsPath) defined?
Actually, VCTargetsPath property is defined in the MSBuild system props or targets files under MSBuild folder(C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild). And the files are nested and related to each other. Therefore, the values of various pr... |
63,540,288 | 63,540,384 | Designated initialization and base classes? | In C++20 (latest draft), given the following code:
struct B { int mb; };
struct D : B { int md; };
which of these six expressions are ill-formed and which are not?
/*1*/ D{42, 43}
/*2*/ D{{42}, 43}
/*3*/ D{42, .md = 43}
/*4*/ D{{42}, .md = 43}
/*5*/ D{.mb = 42, .md = 43}
/*6*/ D{{.mb = 42}, .md = 43}
| (2) is your standard, explicit aggregate initialization. It's fine.
(1) is aggregate initialization with brace elision around the B subobject. This is also fine.
(3) and (4) are mixing designated initializers with non-designated initializers, which is not allowed. The grammar for designated-initializer-list only allows... |
63,540,315 | 63,540,629 | C++: Using cout causing change in value of a variable | I was learning about how to use classes and wrote the following code:
#include<iostream>
using namespace std;
class DQNode
{
public:
int data;
DQNode *next, *last;
DQNode(int num, DQNode *n, DQNode *l)
{
data = num;
next = n;
last = l;
}
};
class Deque
{
private:
... | You have undefined behavior.
This is what happens when you break the rules. When you're lucky, you program crashes with a segmentation fault. Other times, you're unlucky and your program misbehave.
How did you break the rules? Well, you access a dead object.
The source of the problem is happening in your addFirst funct... |
63,540,333 | 63,541,177 | what is the meaning of subclass::superclass in c++ | Consider the following code
class abc
{
};
class def: public abc
{
};
void main()
{
abc a1;
def a2;
def::abc a3;
}
What is meant by def::abc here; is abc a member of def?
Are a3 and a1 similar?
| def::abc a3; is same as abc a1;. You can check order of instantiation as below :
#include <iostream>
class Base {
public:
Base()
{
std::cout << "Base\n";
}
};
class Derived: public Base
{
public:
Derived()
{
std::cout << "Derived\n";
}
};
int mai... |
63,540,335 | 63,540,500 | How to get FileDescription with VerQueryValue (getting the example to work)? | I am trying to get the various attributes of a file as seen in its "Details" tab with the WinAPI function VerQueryValue. I have successfully used this function to get the non-string version info with VS_FIXEDFILEINFO, but have not been able to get the example shown at the bottom of the functions documentation working.
... | VerQueryValue(verData, subBlock.c_str(), &lpBuffer, &bufferSize);
std::cout << bufferSize << '\n' << descBuffer;
Once VerQueryValue returns, lpBuffer no longer points to descBuffer, but to a different buffer assigned inside the call. The returned string is at (const TCHAR *)lpBuffer at that point.
|
63,540,439 | 63,540,972 | C++ array of 192 bitsets to 4 24char array | I want to convert between the following to formats:
#include <bitset>
std::bitset<4> input[192]; // (4 * 192 bits = 768 bits)
char output[4][24]; // (4 * 24 bytes = 768 bits)
Specifically, I would like to convert each of the four bits, in the bitsets, as separated char[24] arrays.
How would do that the easies... | I would simply use a nested for loop:
constexpr int kSize1 = 4;
constexpr int kSize2 = 24;
constexpr int kBitsPerChar = 8;
void convert(std::array<std::bitset<kSize1>, kSize2 * kBitsPerChar> &input,
std::array<std::array<char, kSize2>, kSize1> &output)
{
for (int i = 0; i < kSize1; ++i)
{
... |
63,540,451 | 63,540,534 | Windows message loop implementation in the Quake 2 | I'm studing The Quake 2 source code, for learning, getting experience and just for a pure pleasure. There is an entry point - the classic chunk of code - Windows msg loop. Here is what it look like:
while (1)
{
// if at a full screen console, don't update unless needed
if (Minimized || (dedicated &&... |
As pointed out in the comments, the check for !GetMessage is equivalent to checking for msg.msg==WM_QUIT
That time check is in milliseconds, not seconds. There's a possibility of a divide by zero error if any code attempts to normalize a point based on division by time. Such could easily happen if the game was runn... |
63,540,596 | 63,540,841 | Dealing with circular dependency in std::variant | I'm trying to deal with circular dependency in following scenario:
I've got a std::variant, say:
//types.h
using Types = std::variant<int, double, std::string, SomeClass>;
SomeClass is a pretty simple thing holding few pointers, with some template logic:
#someclass.h
class SomeClass {
// few simple members (pointe... | In the live example you provided, all you need to solve the issue is define SomeStruct after SomeClass.
This way your Types variant will no longer have any incomplete types when SomeStruct is defined. In other words, here is the order:
class SomeClass;
using Types = std::variant<..., SomeClass>;
class SomeClass {
... |
63,541,153 | 63,541,369 | Why is const char[] a better match for std::ranges::range than for an explicit, const char* free overload, and how to fix it? | I wanted to write a generic << for any range and I ended up with this:
std::ostream& operator << (std::ostream& out, std::ranges::range auto&& range) {
using namespace std::ranges;
if (empty(range)) {
return out << "[]";
}
auto current = begin(range);
out << '[' << *current;
while(++c... | I think this shouldn't compile. Let's simplify the example a bit to:
template <typename T> struct basic_thing { };
using concrete_thing = basic_thing<char>;
template <typename T> concept C = true;
void f(concrete_thing, C auto&&); // #1
template <typename T> void f(basic_thing<T>, char const*); // #2
int main() {
... |
63,542,208 | 63,542,327 | How can you get gcc to fully vectorize this sqrt loop? | If I take this code
#include <cmath>
void compute_sqrt(const double* x, double* y, int n) {
int i;
#pragma omp simd linear(i)
for (i=0; i<n; ++i) {
y[i] = std::sqrt(x[i]);
}
}
and compile with g++ -S -c -O3 -fopenmp-simd -march=cascadelake, then I get instructions like this in the loop (compiler-explorer)
.... |
XMMs are 128 bit registers
It's worse than that, vsqrtsd is not even a vector operation, as indicated by the sd on the end (scalar, double precision). XMM registers are also used by scalar floating point operations like that, but only the low 64 or 32 bits of the register contain useful data, the rest is zeroed out.
... |
63,542,389 | 63,542,506 | C++ String Literal Changing After Function Terminates | I have three functions like this:
MyStruct foo() {
//do something...
return get_var("string literal");
}
MyStruct get_var(const string &literal) {
return (MyStruct) {some_attribute, &*literal.begin(), literal.size()}; //struct needs const char*
}
void bar() {
Mystruct var;
//do stuff
var = foo... | c++ is an old language that grew out of C, the result is that both the behavior and the terminology used to describe that behavior can be rather confusing.
A "string literal" is a sequence of characters in the source code surrounded by quotes. In most contexts it evaluates to a pointer to a null-terminated sequence of ... |
63,542,410 | 63,542,692 | Why is deleting a function necessary when you're defining customization point object? | From libstdc++ <concepts> header:
namespace ranges
{
namespace __cust_swap
{
template<typename _Tp> void swap(_Tp&, _Tp&) = delete;
From MS-STL <concepts> header:
namespace ranges {
namespace _Swap {
template <class _Ty>
void swap(_Ty&, _Ty&) = delete;
I've never encountered = de... | TL;DR: It's there to keep from calling std::swap.
This is actually an explicit requirement of the ranges::swap customization point:
S is (void)swap(E1, E2) if E1 or E2 has class or enumeration type ([basic.compound]) and that expression is valid, with overload resolution performed in a context that includes this defin... |
63,542,693 | 63,542,711 | overloading the operator -> | I was looking at overloading the -> operator. I came up with the following simple example:
struct foo
{
int p = 12;
};
struct A
{
foo* f;
A()
{
this->f = new foo();
}
foo* operator-> ()
{
return f;
}
};
int main()
{
A a;
std::cout << a->p; //output 12
}
Alt... | Yes, this is by-design, operator-> will be called recursively on the return value; then we can use such class (so-called smart pointers) in the same way as raw pointers.
If a user-defined operator-> is provided, the operator-> is called again on the value that it returns, recursively, until an operator-> is reached th... |
63,542,947 | 63,543,070 | How do I process tuples through a vector? | I am currently attempting a contest problem that involves passing tuples through vectors to compare with other tuples. Is there a way to do this in C++? Or, perhaps, is there a more efficient way to solve this problem without tuples? Here is what I have so far.
int aNoisyClass()
{
int a, b, n, m;
cin >> n;
... | You need Graphs to solve this problem. That's enough of a problem spoiler.
If you still can't figure out how to solve it, see spoiler here.
|
63,543,099 | 63,543,122 | What does ... mean in c functions | Looking through MSVC's standard libraries, I see the function definition of printf() is:
printf(char const* const _Format, ...)
What does the 3 periods mean?
| That defines the function as a Variadic Function (variable arguments) meaning it is a function which can take any number of arguments. This is useful for functions like printf since there is no way to determine how many arguments might be passed in
printf("%d %d", 5, 5); // two args
printf("%d %d %d", 5, 5, 5); // thr... |
63,543,205 | 63,543,237 | Non-static data member initializers only available with -std=c++11 or -std=gnu++11 |
[Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11
Below I have used // to show that three lines of code where I got the error, despite the code working fine.
#include <iostream>
#include <conio.h>
using namespace std;
class Bank
{
private:
char name[20];
int accN... | float servCharge = 5; //[Warning]
float count = 0;//[Warning]
bool status = true;//[Warning]
Those are warnings, not errors. It means that you are initialising those member variables in-class but those are not static members. This was a limitation of older C++98 and C++03.
You may eliminate those warnings in two wa... |
63,543,388 | 63,544,040 | Can acquire loads reorder with other acquire operations? cppreference says only non-atomic and relaxed are ordered by acquire | According to C++ Reference, mutex.lock() is a memory_order_acquire operation, and mutex.unlock() is a memory_order_release operation.
However, memory_order_acquire and memory_order_release are only effective for non-atomic and relaxed atomic operations.
memory_order: Release-Acquire ordering on cppreference
If an atom... | TL:DR: "all memory writes" means all, not just the kinds mentions, but the phrasing is confusing. Probably intended just to point out that even non-atomic and relaxed atomic ops are safely visible across a synchronizes-with, but the phrasing is missing the word "including".
Note that cppreference is a wiki that's int... |
63,543,489 | 63,570,882 | Segmentation fault in Pybind11 when trying to bridge yices library in usr/local/include | I am trying to bridge my c++ code with python using pybind11. I have example.cpp file and it has an include to yices.h. yices.h is in usr/local/includes folder.
#include <pybind11/pybind11.h>
#include "yices.h"
int add(int i, int j) {
yices_init();
return i + j;
}
namespace py = pybind11;
PYBIND11_MODULE(... | You forgot to link it with gmp and yices:
target_link_libraries(example PUBLIC yices gmp)
|
63,543,707 | 63,543,980 | unable to understand use of scope resolution operator | ::mediapipe::Status RunMPPGraph() {
std::string calculator_graph_config_contents;
MP_RETURN_IF_ERROR(mediapipe::file::GetContents(
FLAGS_calculator_graph_config_file, &calculator_graph_config_contents));
LOG(INFO) << "Get calculator graph config contents: "
<< calculator_graph_config_contents;
... | It's pretty straigtforward, I guess you're not familiar with namespaces.
::mediapipe::Status RunMPPGraph()
RnuMMPGraph is a function taking zero arguments and returning ::mediapipe::Status. Status is a type defined in the mediapipe namespace which is defined in the global namespace.
|
63,543,847 | 63,767,507 | How do I read uint32_t values out of a nested PROGMEM array? | I have an array of 16x16 matrices of uint32_t values: const uint32_t sprites[][16][16] PROGMEM = { ... }; I'm trying to read out the values with pgm_read_dword(sprites + (submode * 256 + row * 16 + column) * sizeof(uint32_t)), but am getting turned around and confused about how the address math works. In this, submode ... | According to datafiddler in the comments, it's as simple as just calling pgm_read_dword(&sprites[submode][row][column]) and letting the compiler handle the offset calculations.
|
63,543,950 | 63,544,206 | Why sublime text and VSCode not showing runtime error? | In the below code snippet, for example, take n as 9 and the array a's elements as {5,5,4,5,5,5,4,5,6}.
Sublime text and visual studio code are showing the correct output as 3 but Leetcode online ide is showing "runtime error: index 8 out of bounds for type 'int [k]' ". I want to know why sublime text and visual studio ... | int k = n - 1;
int temp[k]; // variable length array, must be either #define k <constant num>
// or 'const int k'
The variable-length arrays (VLAs) aren't supported in C++ standard. The Sublime Text & VS Code doesn't matters at all, but the compiler.
You might've not enabled your compiler warnings, ... |
63,543,989 | 63,544,000 | error: no match for ‘operator[]’ (operand types are ‘std::map<std::__cxx11::basic_string<char>, int>’ and ‘char’) | I wanted to test if the increment ++ works for the std::map :
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<string, int> map;;
map['1'] = 0;
map['1']++;
cout << map['1'] << endl;
return 0;
}
And Ì get the error of the title for :
map['1'] = 0;
I do not understand why
| In C++ '1' is a character, not a string literal, and your map has a key std::string, which is not same types. That is why the std::map::operator[] gave you the compiler error, it is mismatch type.
You need "" for mentioning it is a string literal.
map["1"] = 0;
Also, have a read:
Why is "using namespace std;" consid... |
63,544,275 | 63,548,192 | Pass argument to std::bind at run time to a dispatch Queue | I have trouble to pass an argument to my dispatch queue that takes a function pointer as a parameter. I have implemented a Dispatch Queue like this tutorial
typedef std::function<std::string( const std::array<float, kMaxSamples> &)> fp_t;
class DispatchQueue {
public:
DispatchQueue(std::string name, size_t thread... |
Inside the implementation of DispatchQueue, functional objects of type fp_t are invoked as fn(), so fp_t should be std::function<std::string()> or std::function<void()>. There should be no const std::array& parameter.
std::bind should give you something that takes no parameters. Your std::bind is almost correct. When... |
63,544,365 | 63,545,155 | Call member constructor in copy constructor definition | I'm trying to understand the copy constructor in c++ and I want to define my own copy constructor as I have a pointer member in my class so I need a deep copy.
Suppose this:
communicate.h:
#ifndef communicate_h
#define communicate_h
#include "mbed.h"
class Communicate
{
private:
/* data */
BufferedSerial seri... | The error message tells you that BufferedSerial is not copy assignable:
[Error] communicate.cpp@17,51: no matching function for call to 'mbed::BufferedSerial::BufferedSerial()'
[Error] communicate.cpp@19,21: use of deleted function 'mbed::BufferedSerial& mbed::BufferedSerial::operator=(const mbed::BufferedSerial&)'
At... |
63,544,431 | 63,544,715 | C++ program giving garbage value to an initialized variable | I'm just starting out with C++ and writing very basic programs to understand the fundamentals. I wrote a simple code to take in a string and integer via user input (Code attached below). When I give input as 35 Tom (deliberately giving inputs in wrong sequence to see the type sensitivity) I get output Wow 35!!! I didn'... | Why it is not working?
Code in C++ when compiles does not read all the lines at the same time instead, it read the code from line to line. Since you have declared "cin >> name" first, it is asking for the string input first (35 can be int or string both), that is why it is getting accepted 35 as valid input. After this... |
63,544,667 | 63,544,903 | two ncurses window running parrallel | im currently making a project of a typing game, and i want to have a countdown clock window on the top and a typing window running in the buttom, which has to run parallel.
The only way i can think of now is multi threading, and i've researched it which appears that i have to use something like use_screen() or use_wind... | For your intended use case, you could just create 2 windows in the main thread. One for the countdown window and one for the typing window. With newwin you will get the 2 WINDOW*. You can then set all properties of the windows.
Then, you can write code for your countdown window,
This code will be started with std::asyn... |
63,544,910 | 63,547,268 | Coding a cryptography algorithm that accepts random bits from an unspecified source | I'm currently coding a cryptography algorithm that I want to share on GitHub. This algorithm accepts random bits as input. I know that there are many possible sources of pseudorandom bits, one of the weirdest being that you can buy them. Because the quality and sources of pseudorandom number generators can vary widely,... | You can pass a function as a parameter in C++. Take a random generator function as a parameter for your algorithms. Not only this allows to plug in any generator, it also makes unit tests trivial:
#include <functional>
// The first generator
int generate_random() {
return rand();
}
// The second generator good for ... |
63,545,005 | 63,545,085 | how to make our own function like touch in c++ | As soon as I add the below code this programs ends showing this error message:
Process returned -1073741819 (0xC0000005)
If I run those code separately then both of them work.
I used sstream and array too but combined they do not work properly.
#include <sstream>
#include <string>
#include <iostream>
#include <fstream... | length is one less than the number of words in your string as you are only counting the number of spaces. This means your final filesNameArr[number] = word causes undefined behaviour and will probably corrupt the stack.
string filesNameArr[length]; uses a variable length array which is not valid c++. If you use a std::... |
63,545,438 | 63,545,821 | Overloading [] and = operators to accept values for my template class in C++ | I am creating my own ArrayList STL class in C++ and now am stuck in a problem. I want to overload the [] or = operator (I'm sorry I don't know which one will be better implementation) such that the value on the right side of = operator gets assigned to the element of the vector accessed by the [] operator.
I have overl... | You are getting confused. You are asking about assigning T objects but T is not your ArrayList class. It's up to the T class to handle it's own assignment, not upto your ArrayList class.
The code you have written already will work fine.
ArrayList<int> x = ...;
x[1] = 2;
ArrayList<std::string> y = ...;
y[0] = "hello";
... |
63,545,624 | 63,545,658 | Working of assignment operator while copying objects | The assignment operator copies one object to another member-wise. If you do not overload the assignment operator, it performs the bitwise copy.
When the bitwise assignment is performed both the object shares the same memory location and changes in one object reflect in another object.
This concept and my code goes cont... |
When the bitwise assignment is performed both the object shares the same memory location and changes in one object reflect in another object.
This is incorrect. Bitwise copy assignment does not lead to objects sharing the same memory. It's a separate copy, so a2 and a1 are in fact in different memory location.
This ... |
63,545,666 | 63,545,731 | Binary input of text file | Programming Principles and Practice says in the Chapter 11:
"In memory, we can represent the number 123 as an integer value (each int on 4 bytes) or as a string value (each character on 1 byte)".
I'm trying to understand what is stored in the memory, when reading binary a text file.
So I'm writing the content of the ve... | Let me assume you are using little-endian machine (for example, x86) and ASCII-compatible character code (such as Shift_JIS and UTF-8).
test is represented as 74 65 73 74 as binary data.
Using little-endian, higher bytes of muitl-byte integer is placed to higher address.
Therefore, reading thes as 4-byte integer, it wi... |
63,546,039 | 63,560,420 | How to convert a list of tensors into a torch::Tensor? | I'm trying to convert the following Python code into its equivalent libtorch:
tfm = np.float32([[A[0, 0], A[1, 0], A[2, 0]],
[A[0, 1], A[1, 1], A[2, 1]]
])
In Pytorch we could simply use torch.stack or simply use a torch.tensor() like below:
tfm = torch.tensor([[A_tensor[0,0], A_tens... | so C++ libtorch does not indeed allow tensor construction from a list of list of tensors like Pytorch (as far as I know), but you can still achieve this result with torch::stack (implemented here if you're interested) and view :
auto tfm = torch::stack( {A[0][0], A[1][0], A[2][0], A[0][1], A[1][1], A[2][1]} ).view(2,3)... |
63,546,162 | 63,546,552 | Recursion- sum of n natural number | function to calculate the sum of n natural number
int solve(int n)
{
if(n==0 or n==1)
return n;
int sum=0;
sum=sum+n;
solve(n-1); // gives me wrong output
return sum;
}
int solve(int n)
{
if(n==0 or n==1)
return n;
int sum=0;
sum=sum+solve(n-1); // gives me correct output
... | solve function in the first method does not have any effect in your program
int solve(int n)
{
if(n==0 or n==1)
return n;
int sum=0;
sum=sum+n;
solve(n-1); // has not any effect
return sum;
}
In the second method, returned value will always be 1 while it must return the sum of the numbers, ... |
63,547,146 | 63,547,354 | Can someone please explain this line of code | I was watching a youtube video on how to implement your own vector/dynamic_array in C++.
I understood everything except one like of code, I'm new to c++ and trying to understand the underline data structure implementation.
But I didn't see such a line of code like that one.
The Code:
template<typename... Args>
T& Empla... | This line of code constructs an object of type T with arguments args... at the address &m_Data[m_Size]. No memory allocation involved.
new(&m_Data[m_Size])T(std::forward<Args>(args)...);
Lets assume we call a "normal" new operator:
new T((std::forward<Args>(args)...);
This will allocate memory which size will be equa... |
63,547,982 | 63,548,581 | In a nested requirement, why use `requires bool_constant<X>::value;` instead of `requires X;`? | I was reading this cppreference page, and found following code in it:
template <class G>
concept uniform_random_bit_generator =
// ...
requires {
// ...
requires std::bool_constant<(G::min() < G::max())>::value;
};
I'm curious why std::bool_constant is used here. Isn't it possible to use requires G::min(... | Because requires G::min() < G::max(); is a hard error if G::min() < G::max() doesn't form a constant expression, but requires std::bool_constant<(G::min() < G::max())>::value would just be false.
Take for example this type and these concepts:
struct foo {
static int min();
static int max();
};
template<typenam... |
63,548,396 | 63,548,829 | Recursion for evaluating log(1+x) using taylor series of the same | #include<iostream>
using namespace std;
double log(double x,int n)
{
static double p = x ;
double s;
if(n==1)
return x;
else
{
s=log(x,n-1);
p*=x;
if(n%2==0)
return s - (p/n);
else
return s + (p/n);
}
}
int main()
{
double r =... | There is nothing wrong with that piece of code: this has obviously got to do with the rate of convergence of the Taylor series.
If you take n = 200 instead of n = 15 in your code, the approximation error will be low enough that the first two decimals of the exact solution ln(2) = 0.693147... will be the correct ones.
T... |
63,548,467 | 63,548,573 | CPP array memory allocation | Here I am declaring array length before taking input for n. At the time of array declaration n=0.
#include <iostream>
using namespace std;
int main() {
int n;
int sum=0;
int arr[n]={};
cin >> n;
for(int i=0;i<n;i++) {
cin >> arr[i];
cout << arr[i];
}
return 0;
}
for below ... |
Here I am declaring array length before taking input for n.
Yes, but that's no valid C++. It's a compiler specific extension. See Why aren't variable-length arrays part of the C++ standard?
At the time of array declaration n=0.
That's wrong. n has not been initialized, so it contains garbage data (which could be 0)... |
63,548,664 | 63,548,730 | How to get input from the user and push it to a list | #include <iostream>
#include <list>
#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl
template<typename T>
T input(const char* string) {
print(string);
T temp{};
std::cin >> temp;
return temp;
}
int main() {
std::list<char*> list_of_foods;
char* food;
while (1... | T temp{};
Is initializing temp to nullptr, so you cannot have it read something there.
You should use std::string instead:
#include <iostream>
#include <string> // add this to use std::string
#include <list>
#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl
template<typename T>
T input(c... |
63,548,721 | 63,655,954 | Ccache hit rate 0.00 % in GitHub Actions CI | In our C++ project, we managed to setup GitHub Actions building our sources using ccache.
It works very well on Linux where, thanks to ccache, the build succeeds in less than 5 minutes.
Unfortunately, when trying to build on macOS, ccache doesn't seem to work, giving:
cache directory /Users/runner/.... | The problem is most likely that max cache size is too small. If the results (mostly object files) from a build do not fit in max cache size then no usable results will be left for the next build and you will only get cache misses.
cleanups performed was 2976 before the build and 3353 after the build, so 377 automatic c... |
63,549,041 | 63,549,203 | How is memory managed during C++ copy elision? | #include <iostream>
using namespace std;
class A
{
public :
A()
{
cout<<"constructor is called"<<endl;
}
~A()
{
cout<<"destructor is called"<<endl;
}
A(const A &s)
{
cout<<"copy constructor is called"<<endl;
}
};
A beta()
{
A a;
cout<<"mem... | Consider this line: A b = beta();. How does a compiler implement that?
Well, beta is some other function. And beta has a return value that is an A. So there are two possible ways to implement this. The compiler could make beta allocate the stack space for its A return value, but that could be problematic since the call... |
63,549,182 | 63,551,428 | What is stored in Code memory and Data memory | Can some one please explain difference between Code and Data memory. I know code is stored in Flash and Data is stored in RAM but i am confused.
#include <iostream>
using namespace std;
int main()
{
int a =10, b=20;
int c = a+b;
return 0;
}
Here a,b,c are stored in data memory(RAM), but whats get stored i... | In your example, many scenarios based on the optimization level of your compiler.
Constants placed in "code memory"
In the code below:
int a =10, b=20;
int c = a+b;
return 0;
The variables a and b are constants, they don't change. A compiler could optimize this and optimize them to be:
int c = 10 + 20;
So the values ... |
63,549,281 | 63,567,229 | How to send python dict to C++ |
This is my python function:
if __name__ == "__main__":
file = open("data_input.txt", "r")
contents = file.read()
e = ast.literal_eval(contents)
neighbour_num= 4
new_data = 300
result = np.ndarray((4,4),dtype='int32',buffer=np.zeros((4,4),dtype='int32'))
c_module.mmult_wrapper(e, new_data, ... | you will likely need to include dictobject.h, floatobject.h, , if not already pulled in via other headers. Here is a way to grab all the values from a dict of floating point numbera to a vector. Depending on what's actually in the dict and how that's structured you may want to look at keys and other pieces.
Note tha... |
63,549,436 | 63,549,507 | Unable to print vector object data member values in C++ | I am creating a snakes and ladders game. For now, I have created two classes board and ladders. The board is responsible for printing the board and the ladder is responsible for all ladder functionality.
Here is my ladder.h class:
#ifndef LADDER_H
#define LADDER_H
#include <iostream>
using std::ostream;
class Ladd... | For the Ladders version you are creating a vector of 6 elements.
For the Boards version, you don't get any output because m_Board_ladders is empty when you construct the Board. Note that calling reserve doesn't actually change the size of a vector:
Board() {
m_Board_ladders.reserve(6); // still empty
}
If you wan... |
63,549,522 | 63,549,591 | IDA Pro - rewriting HIBYTE, LOBYTE and __OFSUB__ macros to C++ | I was able to hook one function and now I'm trying to rewrite it's code, but I have issues with
translating some macros generated by IDA Pro's pseudocode
LOBYTE(v8) = v8 & 3;
LOBYTE(v12) = 0;
HIBYTE(v12) = *result;
v21 = __OFSUB__(v24 + 1, 30);
LOBYTE and HIBYTE are detected by Visual Studio but when I copy-pas... | LOBYTE and HIBYTE are macros that do some bit shifting logic so you can extract specific values from an unsigned short. So, for example if you had an unsigned short with value 0xAB93, you could get the specific bytes as so:
unsigned char lo = LOBYTE(0xAB93);
unsigned char hi = HIBYTE(0xAB93);
lo would hold the value 0... |
63,549,596 | 63,552,543 | Swapping two boost::adjacency_list graphs, akin to std::swap | I'm building an application, which contains a class DecoratedGraph (say) making use of a boost::adjacency_list graph as an underlying member.
I have a bunch of other members in DecoratedGraph too, some of them storing std::map and std::vector on vertices of the graph, representing various additional properties. I will ... | Indeed, std::swap doesn't seem to be what you want. It selects the generic std::swap that moves through a temporary, very simplified implementation:
template <typename T> inline void swap(T& a, T& b) {
T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
This would seem fine, except that Boost Gr... |
63,550,155 | 63,550,233 | Trying to make a custom string class and I keep getting C2440 and a E0415 errors | I'm self teaching from a book. I'm using this example from a book to work with a custom string class and and I keep getting
Error (active) E0415 no suitable constructor exists to convert from "const char [15]" to "Stringz"
and
Error C2440 'initializing': cannot convert from 'const char [15]' to 'Stringz'
please... | In C++, the char* and const char* types are distinct. Your string literal is a const array of char so it can 'decay' into a const char* but not to a char* (otherwise, a function may try to modify it's contents, which is not allowed).
To get your Stringz from that literal, you need to make the constructor take a const c... |
63,550,227 | 63,550,265 | how to check the return value of a lambda inside an if statement in c++? | I'm working on a small snake game challenge using only the console window, and I got stuck in the draw function where the console is supposed to get cleared, and then draw the grid and the other componements (snake, tail and fruit)
and this is the code:
void draw()
{
system("cls");
for(int h = 0;h < HEIGHT;h++)
... | You are comparing a lambda expression to a bool, which is not allowed. You need to call the lambda and compare the result you get, like this:
else if ([&]() {
for (Snake::Tail T : snake.tails) {
if (T.x == w && T.y == h)
return true;
}
return ... |
63,550,234 | 63,550,297 | Linked List Not Printing Out Correct Data | I'm having trouble understanding why my printout method for my linked list implementation does not work. When the linked list has the numbers 1-5, it prints out 0è⌂è⌂ using the following code below:
void printList(List& source, bool forward)
{
if (forward)
{
ListItr start = ListItr(source.first());... | Because you try to add return value of itr.retrieve()and " " that value is 32 as a decimal in ASCII. I mean, your fail code;
cout << start.retrieve() +" ";
your worked code;
cout << itr.retrieve() << " ";
|
63,550,418 | 63,550,806 | Passing brace enclosed initializer list to variadic macro and expanding to std::pair<> | I am currently working on a threaded Logging library as the first part of a bigger project for graphics drawing (for personal learning and development of skills).
currently i am using a singleton with a thread running on the side and taking Log messages and data into queues (so that they are not blocking events) to be ... | Note the declaration
void Logging::push_to_queue(GG::LOG_LEVEL level, std::string mess,
std::pair<const char*, std::string> log_data ...);
does not have a variable number of parameters with type std::pair<const char*, std::string>. It's actually equivalent to the version with an added comma:
void Logging::push_to_... |
63,550,530 | 63,556,648 | Refresh System Environment Variables for all processes without Logout/ Restart in C++ | I am writing a program in c++ that adds a new directory to the path environment variable for the system. The directory is successfully added with the RegSetValueEx() function but the changes are not reflected for all processes.
I have tried BroadcastSystemMessage() and SendMessageTimeout() functions seperately as below... | I figured out what i was doing wrong, I was using
LPCTSTR keyPath = TEXT("System\\CurrentControlSet\\Control\\Session Manager\\Environment");
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)keyPath, SMTO_BLOCK, 100, NULL);
when it should be
LPCTSTR keyPath = TEXT("Environment");
SendMessageTimeout(HWN... |
63,550,595 | 63,550,724 | What's the actual size of PSAPI_WORKING_SET_INFORMATION buffer used in QueryWorkingSet function of PSAPI.h | I'd like to use the function QueryWorkingSet available in PSAPI, but I'm having trouble to actually define the size of the buffer pv. Here is the code :
#include <Windows.h>
#include <Psapi.h>
#include <iostream>
void testQueryWorkingSet()
{
unsigned int counter;
HANDLE thisProcess = GetCurrentProcess();
... | Both examples are completely ignoring the return value and error code of the 1st call of QueryWorkingSet(). You are doing error handling only on the 2nd call.
Your 1st example fails because you are not taking into account the entire size of the PSAPI_WORKING_SET_INFORMATION when calculating wsi2_buffer_size for the 2nd... |
63,550,597 | 63,551,442 | C++ - HMAC MD5 is not equals with online generator | In my code, I want to generate HMAC MD5. so:
void Gen()
{
CString newKey = L"320E6FADB2738DA273A41E14F85027E1";
unsigned char bNewKey[16];
memset(bNewKey, 0, 16);
string k = ws2s(newKey.GetString());
hex_to_bytes(k.c_str(), bNewKey, 16);
CString data = L"35413B1DD9AB9FA0F1395759BD72451C";
s... | You are incorrectly assuming that the web site is converting the data from a hex string to bytes when it's not.
This simple example results in the same output as the web site:
bool test_gen_md5_hmac()
{
std::string k = "320E6FADB2738DA273A41E14F85027E1";
std::string d = "35413B1DD9AB9FA0F1395759BD72451C";
u... |
63,550,685 | 63,567,156 | Creating packet sniffer in c++ | I have before created a simple packet sniffer using python, with the following code:
import socket
import os
import time
host = "192.168.0.164"
if os.name == "nt":
socket_protocol = socket.IPPROTO_IP
else:
socket_protocol = socket.IPPROTO_ICMP
while True:
sniffer = socket.socket(socket.AF_INET, socket.SO... | I would recommend that you review some complete examples of configuring and reading from a socket. The example provided here appears to be not only complete, but the page specifies expected return values for the receive function.
Additionally, you are not initializing your buffer properly. You are essentially allotti... |
63,550,711 | 63,550,818 | Why my C++ code is not taking input ? What's wrong with my code? | I am currently learning C++ and completely newbie to programming. I came across a question and tried solving but ended up with an undesired output. Then with the help of python tutor I tried visualizing the execution of my code , where even after running cin >> q it isn't taking input and displaying an error while exec... | I don't know what you mean when you say that cin isn't working. There's nothing in your code that would make it not work.
However your code has bugs. This code
if(cin >> t1>>t2){
if(t1==0)
{
v.push_back(t2);
}
else if(t1==1)
{
cout << v[t2] <<"\n";
... |
63,551,184 | 63,556,447 | Floating point types representation | Is std::numeric_limits<float>::is_iec559 + std::numeric_limits<float>::digits == 24 enough to ensure(1) that float is binary32(2) in IEEE 754 ? Same for double with ... digits == 53 ?
In any case including the weirdest implementations still respecting the C++ standard.
"binary32" is a specific representation of floati... | You can use traits class to check your representation matches some expectations.
Here are the traits used to test your representation:
namespace num {
template <std::size_t N> struct ieee754_traits;
template <> struct ieee754_traits<4> {
using unsigned_type = uint32_t;
static constexpr std::siz... |
63,551,202 | 63,551,342 | Trying to understand why my linked list only show the last added node | So i'm lost right now the idea was to make a linked list where the user can add multiple school subjects and it needs to be displayed at the end but what i get is the last inserted subject and it's infromation at the end. Maybe someone can help?
#include <iostream>
using namespace std;
struct cvor {
int sif_pred;
... | You only allocate one node, here:
cvor* noviPredmet = new cvor;
Then, every time, you add that very same node to the list:
unos(glava, noviPredmet);
|
63,551,203 | 63,551,634 | Which of these new expressions with char arrays are well-formed? | For the following program:
int main()
{
new char[4] {"text"}; // #1
new char[5] {"text"}; // #2
new char[] {"text"}; // #3
}
clang gives an error for #1 which says:
error: initializer-string for char array is too long
and accepts #2 and #3.
gcc gives the following error for all statements:
error: inv... | OK, this is pretty simple to trace. The presence of {} means that list initialization is being performed, so we get to visit our favorite part of the spec: [dcl.init.list]/3.
The object being initialized in case 1 is a char[4]. The braced-init-list is not a designated initializer, so 3.1 is ignored. char[4] is not a cl... |
63,551,429 | 63,551,712 | How to stop execution when a return statement is encountered in Visual Studio? | I have a function with multiple return statements. I want to stop execution of my program (during debugging) when a return statement is about to be executed within this function.
One way to do this is add break points at all the return statements, but is there another way?
| The closest you can do to a break-on-any-return is a step-out (shift+f11) from an existing breakpoint in the function. This won't let you inspect arguments to the return expression but it will let you inspect the value that is actually returned to the calling function. If you need to break from a running program then y... |
63,551,523 | 63,552,288 | How to prevent `std::cin` or `\n` from flushing the buffer of `std::cout`? | Let's imagine my program needs input from the user at different times.
I want this input to prevent flushing the cout buffer.
Can I set cin and cout on different stream buffers?
Example in question: a program that reads two numbers in a line, n1 n2, and depending on the first number being either 0, 1, or 2:
n1 = 0: wr... | You could write to your own std::stringstream buffer, and then output that to std::cout when you're ready.
MWE:
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
using std::cin;
using std::cout;
using std::istream;
using std::runtime_error;
using std::stringstream;
using std::vector;
stati... |
63,551,568 | 63,714,045 | Win64 GLFW undefined references | I modified my makefile for Win64, but I get "undefined reference" errors when compiling, which is strange since this doesn't happen on the Win32 makefile. The OpenGL libraries are all included, and I modified the library directory to point to the Win64 DLLs.
GLEW works fine, despite the millions of warnings.
The makefi... | I managed to fix it by switching to 64-bit Windows, installing the 64-bit version of MinGW-w64, and modifying the makefile to use "x86_64-w64-mingw32-g++" instead of "i686-w64-mingw32-g++".
|
63,551,864 | 63,588,817 | How to programmatically disable/enable tasks in CMFCTasksPane without completely hiding them? | I have a task bar with tasks that I need to dynamically disable and enable. For now I am doing it by CMFCTasksPane::ShowTask, however that hides/shows the task as well, ideally I would like to grey out the task when it is not enabled. I noticed that same behavior happens when I assign to a task command that is not regi... | The reason causing this is the involvement of the the UI Update Mechanism. And while the CMFCTasksPane class appears to have no public members that can enable/disable the task items, the UI Update Mechanism would change them even if they did.
Indeed, having a ON_COMMAND handler for UI item (menu, toolbar/rebar button e... |
63,551,875 | 65,595,640 | I get the error: no matching constructor for initialization of std::pair when trying to emplace objects in map | I've tried emplacing my custom type Exercise as key and Open_polyline from Stroustrup's Graph_lib into a map without any luck. Inserting the objects doesn't help me.
Do I have to have a default constructor for key and value of each pair in a map?
The error I get is as follows:
C:\Program Files (x86)\Microsoft Visual St... | As per the comments to this post, the problem lied in the lack of copy contructor for the Open_polyline class. My own solution to this problem was to use pointers to Open_polyline objects, to emplace them inside the map.
|
63,552,014 | 64,186,989 | How to determine the HWND in an ATL message map with contained windows | Let's say you're creating an ATL CWindowImpl class with one or more CContainedWindows. And then let's say you want to chain some of the CContainedWindows' ALT_MSG_MAPs so that a couple windows share some base functionality in their window procedures. But during those shared procedures, you're gonna want to know which... | Actually, I'm not sure yet, but I think this might work:
#define MESSAGE_HANDLER_EX(msg, func) \
if(uMsg == msg) \
{ \
bHandled = TRUE; \
lResult = func(hWnd, uMsg, wParam, lParam, bHandled); \
if(bHandled) \
return TRUE; \
}
And then the handler function should have a s... |
63,552,176 | 63,552,574 | Problem with getting text from a .txt file in c++ using fstream | And thisI am trying to get the things written in a .txt file called CodeHere.txt and here is my main.cpp:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, const char * argv[]) {
string line;
string lines[100];
ifstream myfile ("CodeHere.txt");
int i = 0;
if (myfile.is... | Are you sure that your .txt file is in the same repertory? To me, it just looks like you entered the path wrong. Try with the absolute path (full one). Another option is that you haven't saved the text file yet, you're just editing it, and so it is in fact empty, that would be why your cout doesn't print anything.
|
63,552,767 | 63,552,895 | C++ efficient way to store and update sorted items | I have a operation that continuously generates random solutions (std::vector<float>). I evaluate the solutions against a mathematical function to see their usefulness (float). I would like to store the top 10 solutions all the time. What would be the most efficient way to do this in C++?
I need to store both the soluti... |
You evaluate the float score() function for current std::vector<T> solution, store them in a std::pair<vector<T>, float>.
You use a std::priority_queue< pair<vector<T>, float> > to store the 10 best solutions based on their score, and the score itself. std::priority_queue is a heap, so it allows you to extract its max... |
63,552,915 | 63,553,268 | cmake command line - pass var dependent on the build type | I am trying to create a cmake build with multiple configurations: Debug/Release.
I am using msvc, so I can call cmake once to configure both Debug and Release projects.
My problem:
I have a custom variable that I want to pass to cmake via command line
and that variable depends! on the build type!
e.g.
cmake -DMYVAR=... |
is there a way in cmake to set a variable, in the command line, based on the 'current' build type that is internally used when cmake runs?
Generally, no.
First of all, in multi-configuration generators (like MSVC) there is no "current build type". When process CMakeLists.txt, CMake doesn't have build type set, neithe... |
63,552,990 | 63,553,301 | Faster way to compare string part of a multi type vector with one type vector and erase duplicate | I want to compare string parts of the vectors below and erase the duplicate as fast as possible.
using namespace std;
vector<string> v1;
vector<pair<string, int>> v2;
I've tried find_if lambda, which seems to be slightly faster than nested for loops.
Example data:
+--------+------------+
| index | v1 |
+----... | #include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> v1{ "apple", "watermelon", "cherry", "cucumber" };
vector<pair<string, int>> v2{ {"pear",345},{"apple",85},{"strawberry",1912},{"grape",54},{"peach",90} };
struct HASH {
public:
... |
63,553,274 | 63,589,496 | How to download, build and include PDCurses in Visual Studio 2019 for C++ on Windows | I'm fairly new to C/C++ but have never tried to include external libraries before in my projects as I've mostly been doing tutorials and such. These have been mostly console applications/games. When I was looking for an alternative to the "evil" system(" ") commands I was pointed to Curses.
Now I've gone to the GitHub ... | So, I have figured out how to get PDCurses compiled using it's Makefiles (Makefile.vc specifically) and such.
To anyone who may have issue doing this in future, make sure to read the README.md file very slowly and carefully. From a beginners perspective it was a bit vague but it does contain all the information needed ... |
63,553,623 | 63,553,878 | How to systematically update a C++ dependency that I once manually installed from binary | Scenario:
I wish to use Google OR-Tools with it C++ version as a dependency in my C++ project. I choose to install it from binary. I download the binary file and use the provided Makefile to install it.
Question:
In the future, when a new version of OR-Tools is released, how do I update the dependency in my local proje... |
how do I systematically update C++ dependencies that I installed from binary?
Write a script that fetches and installs the dependencies however you wish or setup one of the many package managers or build systems with package support that C++ has.
|
63,553,910 | 63,555,313 | Is a function definition required to be instantiated when there is no need to check for narrowing? | Consider the following program:
template<typename T>
constexpr int f()
{
T{}.i; // error if instantiated with [T = double]
return 42;
}
constexpr void g(char);
using U = decltype( g( {f<double>()} ) );
To my understanding, the last line is an error because the call to f<double>() is within a brace initializ... | This is CWG #1581 I think, resolved by P0859.
temp.inst/5 says:
Unless a function template specialization is a declared specialization, the function template specialization is implicitly instantiated when the specialization is referenced in a context that requires a function definition to exist or if the existence of ... |
63,554,326 | 63,558,122 | Find starting offset of a partition | Suppose I have a usb drive with two partition e:, f:. How do I know from which offset the partition e: or f: starts so that I can write raw data starting from that offset. I could not find any function that would provide me the offset in c++. In Dos I could easily get this with wmic partition get Index, Name, StartingO... | To get the StartingOffset of partitions in a Physical Drive(such as \\\\.\\PhysicalDrive1), you could use IOCTL_DISK_GET_DRIVE_LAYOUT_EX to get PARTITION_INFORMATION_EX arrays for each partition:
#include <windows.h>
#include <stdio.h>
#define wszDrive L"\\\\.\\PhysicalDrive1"
int wmain(int argc, wchar_t* argv[])
{
... |
63,554,556 | 63,555,144 | Vector subscript out of range error - C++ Vectors & OpenCV4 | I am writing a program that would merge images with SURF,but an unresolved bug has been encountered,about Vector out of range.(i cannot speak english very well,im sorry about that);
My programe
int main(int argc, char **argv) {
Mat image01, image02;
image01 = imread("D:/work/Temp/拼接A1.jpg");
image02 = imread("D:/work/T... | The problem is that you are trying to reach an element of keypoint vector which is overloading the size. For safety, you can try this:
for (size_t i = 0; i < good_matches.size(); i++) {
if (good_matches.empty())
{
cout << "no good matches" << endl;
break;
}
if((int)good_matches[i].qu... |
63,554,663 | 63,554,717 | Why is accessing the members of a member object not allowed in a ctor? | class Edge:
class Edge {
int dist = 0;
std::pair<Node, Node> ends;
public:
Edge() = default;
explicit Edge(const int idist) : dist(idist) { }
explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist) {
ends.first = end1;
ends.second = end2;
}
~Edge() = default;
};
... | This is just not allowed. As the syntax of member initializer list,
class-or-identifier ( expression-list(optional) ) (1)
class-or-identifier brace-init-list (2) (since C++11)
While ends.first and ends.second don't refer to class or identifier, they're expressions. You have to initialize ends in whole, e.g.
expli... |
63,554,721 | 63,554,875 | C++ Undefined Reference to Function of Dynamically Created Class Member | I have four different C++ classes; Comp(), which contains Parent(), which has two children ChildA() and ChildB(). I want to dynamically create an instance of ChildA or ChildB inside of Comp() depending on some parameter.
My code looks a bit like this:
class Parent {
public:
foo();
};
class ChildA : public Parent... | As you are a Python programmer you got used to the world where every method is a virtual one, and the overload means that you just replace the value in the dict. C++ is somewhat different.
So the first solution is to define the Parent::foo method. You have declared it, the class is not a template - so you have to defin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.