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 |
|---|---|---|---|---|
65,407,617 | 65,407,756 | Why char* Name = "string"; is not working in C++? | When I write a function like below and use it in main(), it doesn't work.
Why does this happen? (I am a beginner).
void addBst(char *name, char *num);
int main(void)
{
addBst("a", "b");
return 0;
}
| In C++, a string literal is a const char[N] array, where N is the length of the string, including the null terminator.
Since C++11, it is illegal to assign a string literal to a non-const char* pointer, as your code is doing. You need to use a const char* pointer instead, eg:
void addBst(const char *name, const char *n... |
65,408,371 | 65,408,665 | How to use Python to input to and get output from C++ program? | I'm currently trying to automate the testing of a C++ program which takes input from the terminal and outputs the result onto the terminal. For example my C++ file would do something like below:
#include <iostream>
int main() {
int a, b;
std::cin >> a >> b;
std::cout << a + b;
}
And my Python file used fo... | You could use subprocess.Popen. Sample code:
#include <iostream>
int sum(int a, int b) {
return a + b;
}
int main ()
{
int a, b;
std::cin >> a >> b;
std::cout << sum(a, b) << std::endl;
}
from subprocess import Popen, PIPE
program_path = "/home/user/sum_prog"
p = Popen([program_path], stdout... |
65,408,512 | 65,408,534 | C++ -> Which is faster?? int a(5); or int a = 5; | I know this is easy one but I'm confused whether int a (5); is faster than int a=5; in C++, as I read somewhere, if a constructor with only one parameter is defined in the class, the initialisation can be done with an equal sign.(A statement can be written with an equal sign)
So I thought may be first one is bit of a e... | The two forms tell the compiler the same thing in different ways (the statements have the same ultimate meaning). Since the compiler is told the same thing, it should generate the same code.
(It is theoretically possible somebody could design a compiler to do different things with these statements, but that would be a ... |
65,408,531 | 65,413,239 | Boost ASIO Tcp Client/Server object connect issue | I'm trying to make an "connection handler" for Client and server the server-side works quite well with an other client but when i try to connect a client made the object, i've always the same crash and it appears right after the socket->connect.
this is the error from the client:
terminate called after throwing an inst... | You're missing a break statement:
TCP::TCP(TYPE type) {
switch (type) {
case (CLIENT):
setup_client();
break;
case (SERVER):
setup_server();
break;
default:
break;
}
}
This means that your client also tries to open an acceptor on the same port. That is normal... |
65,408,539 | 65,408,864 | How to properly manage dynamically allocated pointer arrays in C++? | Currently I'm working on a microprocessor that only has a small RAM capacity (128 MB). I'm running multiple threads of execution to analyze performance but the essence of the problem lies on storing large amounts of data (floats and integers) in dynamic space in order to reduce the possibility of data copy/allocation t... | The routine resizeArray doubles current_capacity with current_capacity*=2; in each iteration of its inner loop. The first time it is called, this results in arr[0][0] being set to point to memory for 6 int, while the loops continue and ultimately leave current_capacity set to 1536. For the rest of program execution, re... |
65,408,732 | 65,409,324 | enable_if fails without decltype in return type | I have 3 overloads of a function each guarded by enable_if
struct thing{
typedef int data_type;
template <typename T, int N = 0, typename = typename std::enable_if<N == 0 && std::is_same<T, data_type>::value>::type>
data_type data() { return 1; }
template <typename T, int N = 0, typename = typenam... | Those are not overloads; they are redeclarations (and redefinitions) of the same function template:
template<class, int, class> auto data();
Default template parameters do not make a different function template; nor does a different deduced return type, however swapping auto for decltype(auto) does make a different fu... |
65,408,815 | 65,409,047 | Opposite of const_cast | I have an std::vector<int*> v and I'd like to prevent further writes to it. The C++ compiler does not accept this
const std::vector<const int*>& w = v;
but it accepts this
const std::vector<const int*>& w = reinterpret_cast<const std::vector<const int*>&>(v);
The latter does work with Microsoft's compiler, meaning th... | This is Undefined Behavior.
std::vector<const int*> and std::vector<int*> are two different classes (generated by the same template, but that is irrelevant). They cannot alias each other and you cannot reinterpret_cast between them.
My solution is to use std::span:
const std::span s{const_cast<const int* const*>(v.data... |
65,409,062 | 65,409,225 | C++ Template function not working in Visual Studio 2019 [Error 2668] | In getting a error using template functions in that generic swap function:
#include <iostream>
#include <complex>
using namespace std;
template <class T>
inline void swap(T& d, T& s)
{
T temp = d;
d = s;
s = temp;
}
int main()
{
int m = 5, n = 10;
double x = 5.3, y = 10.6;
complex<double> r(... | using namespace std is the likely culprit here, since it pulls std::swap into the global namespace.
So you can either remove that and fully qualify the relevant identifiers (recommended) or rename your own swap function.
|
65,409,371 | 65,424,268 | Is there a way to include both WICTextureLoader and DDSTextureLoader without 'redefinition' errors? | I'm trying to load a DDS texture. For that, I'm using DDSTextureLoader11 provided by DirectXTex. I already am using another texture loader from the same library - WICTextureLoader11.
The problem is, I don't get errors with WICTextureLoader11, however I do get errors either when including only DDSTextureLoader11, or whe... | I was confused once again with DirectXTex and DirectXTK.
I resolved the issue by:
Removing DirectXTex
Downloading DirectXTK
Running the DirectXTK_Desktop_2019_Win10 solution
Changing the Build to Release and x64
Opening the properties
Finding the option Runtime Library
Choosing Multi-threaded /MT
Building the solution... |
65,409,966 | 65,482,267 | Converting a C++ implementation of Error Level Analysis to C# | I am trying to implement Error Level Analysis in C#. I have found examples in C++ using OpenCV and Python using PIL, but cannot find any in C#, so I am trying to convert C++ code using the OpenCvSharp library.
Here is the example I have used:
// Control
int scale = 15,
quality = 75;
// Image containers
cv::Mat input_i... | You can use EmguCV instead, which you can install from here. Then you can transform the code to C# like this.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Emgu.CV;
using Emgu.CV.CvEnum;
class Program
{
// Control
readonly int scale = 15, quality = 75;
// Imag... |
65,410,729 | 65,411,417 | How to use operator overloading for const using templates | I am trying to overload the << operator just for understanding purposes. I was successful but I am having issues with const data types and objects. The compiler gives me the following:
Use of overloaded operator '<<' is ambiguous (with operand types 'std::__1::ostream' (aka 'basic_ostream') and 'const char')
I am using... | As the above comments mentioned that you cannot overload the primary type for stream out. It had been defined in the standard library. Therefore, in order to print your overlaod, you have to invent some user-type that is not belonging to the primary type, and stream out the user type. This will direct to your overload... |
65,411,100 | 65,411,678 | C++ allocator to store objects of different types | I have a bunch of objects wrapped by unique_ptrs.
Each object is of its own type.
I would like to create a kind of memory pool to store all those objects to avoid heap allocations for every last object. Like this:
Allocator allocator(1024); // should be extendable
unique_ptr< A > a = allocator.allocateAndWrapToUPtr... | It is not possible to use one allocator everywhere around the project.
Dynamic allocator example can be found at dmitrysoshnikov.com/compilers/writing-a-pool-allocator, it allows to solve the initial problem with unique_ptrs.
But it is not stl compliant so can not be used for collections for example.
|
65,411,700 | 65,411,941 | Algorithm: improve c++ sorting | I have a program that asks to input N-numbers (N<=100000) and then it should output those numbers in sorting order. All numbers are int-s.
I have the following code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n,x;
cin >> n;
vector<int> v;
... | As a vector grows, it sometimes needs to relocate all the data. If you can avoid that, it'll often be faster.
One way is to reserve the number of elements you know that you need. Another is to create the vector with the correct number of elements from start.
vector<int> v(n); // created with n elements
... |
65,411,750 | 65,413,967 | Why do references take up memory? | It would seem, a reference is simply an alias, yet, adding reference-fields to a struct, for example, increases the structure's size even when the reference is initialized at declaration as an alias for another field of the same structure.
For example:
#include <iostream>
using namespace std;
int
main(int, char **)
... | Even with the first and second structures being defined the way you do, I think, those reference members cannot be optimized away (if we are talking not about the particular program you wrote, but in the general case of using those structures). For example, suppose at some point in code, you'll decide to create an inst... |
65,412,074 | 65,412,240 | Find index of symbol in string | I want to find index of '-' in string "book-Buch". What should I do? I mustn't use this function or any others. Any ideas?
int indexOf(int ch, int fromIndex)
| #include <iostream>
#include <string>
int main() {
std::string word("book-Buch");
// The easy way
std::cout << word.find("-", 0) << '\n';
// The manual way
for (std::size_t i = 0; i < word.length(); ++i) {
if (word[i] == '-') {
std::cout << i << '\n';
}
}
}
If you just want to find the ind... |
65,412,174 | 65,412,509 | Why does libstdc++ implement both <L,R> and <LR> overloads for binary operators on iterators? | In libstdc++3, in the header bits/stl_iterator.h (GCC 10 source here), every binary operator for __normal_iterator has two overloads defined (here is == for example):
template<typename _IteratorL, typename _IteratorR, typename _Container>
_GLIBCXX20_CONSTEXPR
inline bool
operator==(const __normal_iterator... | The comment above that complains about std::rel_ops, which provide a template<class T> bool operator!=(const T& lhs, const T& rhs).
Reducing __normal_iterator to it's bare essentials to show the problem, we get this:
#include <utility>
template<typename T>
struct normal_iterator {
T m_base;
const T& base() co... |
65,412,383 | 65,416,427 | Difference of Pointer Values | am a novice programmer and I was mingling with pointers to get my base strong for DSA . The following is my code
int main() {
int AnArray[20];
int* plocation6, * plocation0;
plocation6 = &AnArray[6];
plocation0 = &AnArray[0];
cout << (int)plocation6 << endl << (int)plocation0<<endl;
cout << "Di... | To build on top of the previous answers:
It is true, since an int takes 4 bytes, that the two pointers are 24 bytes apart.
The reason that you are getting 6 is because the - operator (for pointers) is defined as the difference between the two pointer's addresses divided by the size of the data type the pointers point t... |
65,413,053 | 65,413,054 | Am I incorrectly sourcing environment variables from a file in CLion, or is env file syntax incorrect? | I want to be able to source one or more environment variables from a file within a particular run/debug configuration in JetBrains CLion.
As far as I'm aware and as of this writing, this particular question has not been answered on Stack Overflow. I think it should be useful for users of other JetBrains IDEs.
Coming fr... | CLion does not follow the expected syntax, but the documentation is not explicit about that:
Use the Load variables from file field to point CLion to a script that configures the environment.
The clue is the word script. If you want the environment variable to be available outside the script, you need to export it, s... |
65,413,470 | 65,416,522 | Scalable login/lobby servers for a multiplayer game | I am developing a multiplayer game (client-server model) and I am stuck when it comes to scaling its servers.
I understand that most games never even reach 10 000+ players, and I don't think mine will either.
Though if I would be very lucky to get that I want to develop the servers so they cannot become a huge obsticle... | All your problems and questions are solved by serverless cloud based solution AWS Lambda e.g. or similar. In this case the scalability is not your problem. Just develop the logic. This will save you much time.
If you would like to make servers as single app hosted by your own server. Consider using something like e.g. ... |
65,413,635 | 65,413,716 | Splitting a string in c++ | I'm writing a function to reverse words in a string. My idea is to split a string by ' ', push the words into a stack and pop them out to print the string with their words reversed.
But , I am not able to split the string using stringstream class.
My code is as follows:
#include<iostream>
#include<stdlib.h>
#include<st... | In your case, the stream extractor (operator >>) stops reading after the space in Hello world so s="Hello".
To solve this use getline(cin,s);
Edidted to include more detail as told by @Pete Becker
|
65,413,819 | 65,422,284 | ERROR: 0:1: '' : Version number not supported by GL2 | I'm trying to make shader, but it gives me this error:
ERROR: 0:1: ' ' : Version number not supported by GL2
ERROR: 0:3: 'layout' : syntax error parse error
Please help!
This is my vertex shader code:
#version 330
layout(location = 0) in vec4 position;
void main()
{
gl_Position = position;
}
And this is my ... | Since your graphics driver and card only support OpenGL 2.0, you cannot use a GLSL shader with version 3.30. You need to use GLSL 1.10 which corresponds to OpenGL 2.0.
See OpenGL Shading Language 1.10 Specification and OpenGL specification - Khronos OpenGL registry
An appropriate shader would be:
Vertex shader
#version... |
65,414,097 | 65,414,312 | Passing void function as argument into double function in c++ | I'm trying to use NLopt library for an optimization problem in c++. The docs indicate the input function to be optimized should look like this:
double myfunc(const std::vector<double> &x, std::vector<double> &grad, void *my_func_data);
I don't understand how to use the void *my_func_data argument, which accepts addit... | You have to define struct containing required data:
struct ExtraData
{
double xM = 1.;
double yM = 1.;
double xF = 1.;
double yF = 1.;
};
I do not know this library - but probably it has function accepting void* and pointer to your function - let's refer to it as Xxxx:
Xxxx(..., double(*)(const std::... |
65,414,455 | 65,414,547 | Removing duplicates from a sorted list (New Approach) | This is my program for removing duplicates from a sorted linked list. I am traversing from the head node of the linked list and using temp1 variable, I am checking whether there are any duplicates of the same value. If we find a data which is different from the current node, then we link that to current node and make i... | You have UB for list of one element, as forw is then used uninitialized.
(that UB should probably do, in your case, infinite loop, so TLE).
|
65,414,504 | 65,414,606 | Really basic piece of code returns no error but does not work? (exits with code -1073741571) | As the title says - I have a really basic piece of code which should read two numbers, and then a 2D float array. I get no error but when I run my program, it crashes with code -1073741571 and I can't understand why.
Here's the code:
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
voi... | You get a stack overflow. You should use new [] operator to allocate the array in dynamic memory or just use std::vector (which will be simpler, 'cause you don't need to allocate every internal array using for cycle).
|
65,414,521 | 65,414,669 | How to extend the regular expression that works for one pair to many pairs | I have written a code to find all matches to the pattern like 23<=34 or 123<>2000 in the given file. More generally, a(sign)b where sign ∈ { =<, =, >, <=, <>, >= } and a,b ∈ N.
Now, I got stuck on extending this code to identify many joint patterns like a(sign)b(sign)c(sign)...(sign)d. This reminds me of finding the gc... | It seems you are looking for
REGEX_NUMBER "(" REGEX_SIGN REGEX_NUMBER ")+"
Regex demo with \d+((<|=|>|<=|<>|>=)\d+)+
C++ Demo.
|
65,414,611 | 65,416,101 | Delete and replace a Specific Line in .txt file | I'm struggling with my C++ project related to file handling and need one help.
Here is my movies.txt file
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 44
6, Schindler's List, 33
7, The Lord of the Rings: ... | Here is a working example of what you want to do: it increments the number of likes for a movie. It does not store the contents of the whole file into the buffer. The file might be of a large size, so it might not be very efficient.
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::fstrea... |
65,414,765 | 65,673,008 | How to implement a template common for maps and sets? | I'm loading various data from database, and have already implemented a template-method:
template <typename R>
bool
loadMap(map<const string, R> &store, const char *query) {
{
...
for (auto row : rows(query)) {
store.insert(make_pair(row[0], R(row[1], row[2], ....));
}
}
The method sends the query... | Having solved the problem of distinguishing between maps and sets, I was able to implement different insert-functions for different container-types.
My loadMap templatized function is simply calling the insert(store, key, value) -- and the correct insert implementation is picked at compile time depending on the type of... |
65,414,766 | 65,415,102 | How to fix "Program terminated with signal SIGFPE" | The question is :-
Given an integer, for each digit that makes up the integer determine whether it is a divisor. Count the number of divisors occurring within the integer.
Complete the findDigits function in the editor below.
findDigits has the following parameter(s):
int n: the value to analyze
int findDigits(int n) {... | int findDigits(int n) {
vector<int> digits;
int temp = n;
int result = 0;
while(temp!=0){
digits.push_back(temp%10);
temp/=10;
}
for(int i=0 ; i<digits.size() ; i++){
int s = digits[i];
if(n % s == 0 && s != 0)
result ++;
}
return result;
}
Its a Runt... |
65,415,016 | 65,427,850 | Maximum sum of strictly increasing susequence of size 4 | Is there any more efficient way to get the maximum sum of strictly increasing subsequence of size 4?
I have used DP where DP[i][j] = max(DP[k][j-1]) such that k < i and A[k] < A[i], j < 4, A is the array.
This solution has a time complexity of n^2.
I want to reduce the time complexity.
Let the array be 1, 10, 6, 8, 9, ... | For each i from 1 to 4, keep by descending maximum and sum, the best options that you have found already. (You can use a skiplist, binary tree, or whatever for this.) This will be kept strictly descending by both maximum AND sum.
Then your update logic looks like this:
for i in [1, 2, 3, 4]:
for j in your array:
... |
65,415,036 | 65,415,166 | How to bypass commented lines in external text file using ifstream in C++ | I'm having trouble filtering the 'commented' lines in a text file.
I want to filter the lines beginning with # or // in the text file.
Thanks!
string code, name, year, semester, value, data;
char delimiter = '|';
ifstream ifsUnits;
ifsUnits.open("./data/units.txt");
if (ifsUnits.fail())
cout << "\nError reading ... | You're already pulling one line into a string at a time. Just check if that string starts with your comment characters and if so, continue:
while (getline(ifsUnits, data)) // more robust than eof check
{
if ((data.size() > 1 && data[0] == '/' && data[1] == '/')
|| (data.size() > 0 && data[0] == '#')) { cont... |
65,415,889 | 65,416,711 | Are empty base virtual methods optimized out? | Are compilers smart enough to optimize the call to Foo() when derived class does not override it?
struct Base {
virtual void Foo(int x) {}
};
struct DerivedA : Base {};
struct DerivedB : Base {
void Foo(int x) override { Bar(x); }
};
void Call(Base* b) {
b->Foo(42); // Is this optimized out for DerivedA?... | It depends. I just pasted your example in Godbolt compiler explorer. I had to delcare a function void Bar(int) to make it compileable, and I added missing deletes. Clang optimizes it with "-O2" pretty well to
Call(Base*): # @Call(Base*)
mov rax, qword ptr [rdi]
mov rax, ... |
65,415,896 | 65,417,215 | Error handling with (boost::)outcome : use in constructor with composition and inheritance | In my environment I cannot use exceptions so I need an alternative solution for error-handling. Returning an int as the error code is not a good way in a new modern project because this interface prevents to return other data.
std::expected is not yet available; maybe there are some sample implementations but I need so... |
Being A ctor protected, the following declaration is not valid.
You cannot indeed use non-accessible constructors, but move constructor is public,
so you might write your X_ctor differently:
B(A&& a) noexcept : a_(std::move(a)) {} // use public A(A&&)
static result<B> B_ctor() noexcept
{
result<A> a = make<A>();... |
65,416,229 | 65,416,799 | pointer equality test with same address yields false | Why is this pointer comparison not working?
// in handleSlot()...
void* ptr1 = m_expected; // defined as SimpleBase*
void* ptr2 = sender(); // defined as QObject*
if (ptr1 != ptr2)
return; // this should not be reached, since the debugger shows ptr1 and ptr2 are the same
The background here is that I have a templa... | It seems you can dynamic_cast<SimpleType*>(sender()) or dynamic_cast<QObject*>(m_expected) assuming both are unique and have a virtual function. Multi-inherited bases do have different actual addresses and you can’t compare them for equality using void* always.
|
65,416,243 | 65,416,936 | How do I make 0 auto cast to an enum? (|= works but not =) | If you take a look at the code below you can see I overloaded |= to allow ORing with ints. However I can't figure out how to overload =. Clang seems to say I need = to be in the enum body AND that the enum body can't have overloads. So I'm confused and it seems impossible?
I mostly want 0 to be an acceptable value of T... | The reason for the perhaps misleading error message content is:
[over.ass/1]: A simple assignment operator function is a binary operator function named operator=. A simple assignment operator function shall be a non-static member function.
This is also why there's no workaround: an enum (even a scoped enum) is not a ... |
65,416,400 | 65,416,536 | How to call a function every x seconds but be able to do stuff in the meantime | I'm building a tetris game and I need the pieces to fall every x seconds; something like:
while(true){
moveDown();
sleep(x)
}
The problem is, I need to be able to move the pieces left and right in the meantime, i.e., call a function while it's sleeping.
How can I do that in c++?
| This problem is solvable in multiple ways (another idea that comes to mind is multithreading, but that seems overkill). One approach would be to keep track of the number of "game cycles" and execute some function every n-th cycle like this:
for(int32_t count{1};;count++)
{
if (!count % 5)
{
// do someth... |
65,416,432 | 65,416,521 | Passing user input to server for C++ compilation | I`m building an online c++ compiler for a school project. Right now I can send the c++ code a client writes in the web page to the server, use g++ to compile it, that run it and redirect output to a file and send the result right back to the client. The problem is my server stops working when the code contains somethin... | You might use redirection as with pipe |:
cat input.txt | ./a.out
or
echo $user_input | ./a.out
|
65,416,909 | 65,417,018 | overridden method not working on the range_expression of a range based loop | The first call to operator* (live example line 38) is doing what is expected, it calls the overridden method operator_deref(). Whereas the second (live example line 40) is calling the parent method instead. What I'm missing here?
Live example
#include <iostream>
class RangeP{
protected:
int _iter = 0, _last;
... | The reason for it can be found at https://en.cppreference.com/w/cpp/language/range-for
As stated:
{
auto && __range = range_expression ;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
What you see here is that __begin is a copy of the b... |
65,417,264 | 65,417,444 | How to have a static counter for global types? | I'd like a static counter that is incremented each time I create another type, class. Here is what I've tried:
template <typename Type>
class Sequential_ID_Dispenser
{public:
static inline int nextDispensed = 0;
static int getID() { return nextDispensed++; }
};
struct DummyTypeForComponentIDs {}; // So that th... | You don't need inheritance for (runtime) counters on types.
You might even use a template variable (C++14):
std::size_t getId()
{
static std::size_t counter = 0;
return counter++;
}
template <typename T>
std::size_t Id = getId();
Demo.
|
65,417,446 | 65,417,505 | Clang++ makes linker fail on template classes (but it works with g++) | I have a program that works nicely with GCC, but compiling it with Clang instead makes the linker fail.
I think my issue is with template classes, so I implemented this small example.
test.cpp:
#include "Point.h"
int main()
{
Point<int> p1;
Point<int> p2{ 3, 6 };
}
Point.h:
#ifndef POINT_H
#define POINT_H
te... | Your explicit instantiation should be where definitions are visible, so at the end of Points.cpp
From class_template#Explicit_instantiation:
An explicit instantiation definition forces instantiation of the class, struct, or union they refer to. It may appear in the program anywhere after the template definition, and f... |
65,417,777 | 65,418,154 | Ascii character codes in C++ visual studio don't match up with actual character symbols? | I am trying to represent 8 bit numbers with characters and I don't want to have to use an int to define the character, I want to use the actual character symbol. But when I use standard ASCII codes, everything outside of the range 32-100 something are completely different.
So I looped through all 256 ascii codes and pr... | It should be a problem of codepage. Windows console applications have a codepage that "maps" the 0-255 characters to a subset of Unicode characters. It is something that exists from the pre-Unicode era to support non-american character sets. There are some Windows API to select the codepage for the console: SetConsoleO... |
65,417,937 | 65,465,493 | <Int 16h> BIOS interruption with GCC Assembly in Linux? | I'm using QTCreator 3.5.1 and a virtual OS which is Linux Mint 18.3 Cinnamon 32-bit, GCC Compiler.
I have to write a code that uses interruptions, obtaining a key pressed on the keyboard using assembly commands.
The code that should've been working on windows is like this:
#include <iostream>
unsigned char x;
int main(... | The service int 16h is a BIOS service. It only works in real mode and is usually used in boot loaders or DOS programs. It cannot be accessed from neither Windows (any version, unless executing a DOS program in which case the service is emulated) or Linux (any version) or any other protected mode operating system for th... |
65,418,314 | 65,418,813 | Template class with only static methods Implementation using .cpp file giving error | I'm trying to implement a class in C++ which contains most of the functions which I might need to use across different class hierarchies (the project has multiple different inheritance trees).
After reading through and taking advise from multiple answers for this kind of implementation on Stack overflow, Why can templa... | I figured it out finally. I needed to let the compiler know that it needs to use a more recent version of C++. So, g++ -std=c++17 -o test main.cpp testImpl.cpp compiled the code for me perfectly fine.
The need for using -std flag arises only when you're using the gcc version 7.5.0. All versions of gcc after it, work w... |
65,418,773 | 65,418,806 | Why const function can use a static member object's non-const function? | Code1:
#include <iostream>
using namespace std;
class Test1 {
public:
Test1() { num_ = 10; }
int GetNum() { return num_; }
private:
int num_;
};
class Test2 {
public:
int GetNum() const { return t1_.GetNum(); }
private:
static Test1 t1_;
};
Test1 Test2::t1_;
int main(int argc, char *argv[]) {
Test2 t2... | As non-static data member, t1_ becomes const accordingly in const member function. Then t1_.GetNum() leads to the error because non-const member function can't be called on const object.
On the other hand, static data member doesn't belong to object; it won't become const just because in const member function.
|
65,418,804 | 65,419,114 | Implementing a QAbstractListModel subclass for QML ListView? | How can you implement the data function of QAbstractListModel such that it returns something with properties that are visible from a QML ListView's delegate?
For the item type, I tried implementing a QObject subclass that has Q_PROPERTYs, but QAbstractListModel::data returns QVariant, and a QObject* can't be converted ... | If you want to encapsulate a QObject in a QVariant then you must use QVariant::fromValue:
return QVariant::fromValue(item);
MWE:
main.cpp
#include <QAbstractListModel>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
class MyListItem : public QObject {
Q_OBJECT
Q_PROPERTY(QS... |
65,418,805 | 65,421,253 | C++: Problem of Korean alphabet encoding in text file write process with std::ofstream | I have a code for save the log as a text file.
It usually works well, but I found a case where doesn't work:
{Id": "testman", "ip": "192.168.1.1", "target": "?뚯뒪??exe", "desc": "?덈뀞諛⑷??뚯슂"}
My code is a simple logic that saves the log string as a text file.
My code was works well when log is English, but there is a p... | You could set UTF-8 in File->Advanced Save Options.
If you do not find it, you could add Advanced Save Options in Tools->Customize->Commands->Add Command..->File.
|
65,418,953 | 65,418,978 | How do I tell Visual Studio that my header should be C++ and not C? | I have a C++ project, and the main file with the main function is a .c, but when I include my .h that is supposed to be C++, I think I am getting errors because it thinks it is C. How can I tell it that my header should be C++ and not C, like my main?
| You cannot #include C++ header in a C source file. A header is not compiled separately. All that #include does - it makes the compiler work as if the header was a part of the file.
|
65,418,957 | 65,418,999 | Why does a char casted to an int not equal the original char? | Why does a casted char c stored in an int not be the same as the original char?
I have looked all over for an explanation and I can't seem to be able to store a char in an int and be able to compare it to another int.
#include <iostream>
using namespace std;
int main() {
char c = 255;
int x = (int)c;
cout... | The cast isn't the problem here. Trying to assign 255 into a char, which is an 8 bit signed type, is. This most likely results in all bits being set, and is interpreted as -1, but you shouldn't be doing it in the first place. Try with 127 or lower, and it will print 1.
|
65,419,337 | 65,420,604 | static member of the templated class not created unless referenced | #include <iostream>
template <typename T>
class Temp {
public:
static Temp temp;
Temp() { std::cout << "hi!"; }
};
// Definition.
template <typename T>
Temp<T> Temp<T>::temp;
I created a simple template class. I thought that instantiating Temp object is enough to construct static temp in Temp.
int main() {
T... | You can explicitly instantiate the class to make it more likely that the static member is included without referencing it:
template class Temp<int>;
Note, however, that depending on compiler/linker options, unreferenced code isn't necessarily included into the final binary. In particular, any attempt to register somet... |
65,419,486 | 65,420,546 | wxWidgets - Adding data to DataViewListCtrl | I'm trying to make a application for managing audio sample library using wxWidgets, I have a DirCtrl on left and a DataViewListCtrl on right, when user navigates to a folder and double clicks on a file it should extract its tags and audio properties using taglib and add them to specific columns. I'm having some trouble... | Based on the way you're trying to add data to the list view, I'm assuming that the columns were set up something like this:
m_dataViewListCtrl->AppendToggleColumn("Fav");
m_dataViewListCtrl->AppendTextColumn("Title");
m_dataViewListCtrl->AppendTextColumn("Artist");
m_dataViewListCtrl->AppendTextColumn("Channels");
m_da... |
65,419,576 | 65,420,180 | Is there a good way to resolve the ambiguity between nullptr_t and pointer overloads? | When using the literal 0 in C++, the compiler can't disambiguate between pointer and nullptr_t overloads of a function.
Code that illustrates the problem:
struct Bar {};
void foo(Bar*) {
std::cout << "Bar*" << std::endl;
}
void foo(std::nullptr_t) {
std::cout << "nullptr_t" << std::endl;
}
TEST(NullPtrTest, ambi... | Templates were not on the exclusion list - make it a template, constrained to only accept Bar*:
#include <iostream>
#include <type_traits>
struct Bar {};
template <typename T>
typename std::enable_if<std::is_same_v<T, Bar>>::type foo(T*) {
std::cout << "Bar*\n";
}
void foo(std::nullptr_t) {
std::cout << "nul... |
65,420,384 | 65,420,463 | Scalar deleting error when deleting std::shared_ptr | I am trying to find out how can I delete children of my Block class. I tried to do it with raw pointer. I don't know why, but it didn't work. I was getting the scalar deleting error. I now tried to do this with std::shared_ptr. I t didn't work as well. I am removing the children with:
void Block::remove(Block* block)
... | You are mixing shared_ptrs with raw pointers, and that is a bad practice. If I understand correctly, you store the blocks in the vector of shared pointers, and that means that this vector has an ownership on these objects. When you create an additional shared_ptr out of a raw pointer you create another object that has ... |
65,420,582 | 65,421,024 | How to optimize the return value of rvalue parameter to avoid copy | I am writing a network module, using the envelope model, The following is a sent function, the function parameter uses rvalue reference:
Envelope NatsTransport::Send(Envelope&& envelope)
{
// do somthing...
if (!natsConnection->Send(envelope.GetContent(), envelope.Length()))
{
return envelope.With<... | Moving const objects (as in your original post) selects regular copy constructor over move constructor.
You would need Envelope(const Envelope&&) which has actually really few usage.
When argument is not const
return std::move(envelope) should call move constructor (if available).
return envelope call copy constructor.... |
65,420,911 | 65,421,082 | gcc: cannot execute 'cc1plus' | I have just downloaded the C++ compiler MinGW, checked everything in the MinGW Installation Manager, and put the \bin location. But when I test the compiler in one of my C++ compilers, I get the following error:
gcc: fatal error: cannot execute 'cc1plus': CreateProcess: No such file or directory
compilation terminated.... | Install gcc-c++ or g++, and then set the environment variable.
You can also run g++ -v to check whether g++ was installed correctly or not.
|
65,421,105 | 65,421,339 | String vector iterator in c++ | I'm just trying to get the iterator over a vector of strings, getting the iterator passed to 'pos' and transfered together with the value at pos to another function, but the compiler tells me there was an invalid conversion at the lambda argument from 'const char*' to 'size_t'. I'm also getting this for header stl_algo... | When iterating a vector of strings with std::for_each(), the parameter passed to the lambda will be a string, not a size_t index. That is why you are getting a conversion error.
If you need an index, then you will have to change your lambda to track the index separately, eg:
size_t pos = 0;
std::for_each(main_menu.lin... |
65,421,107 | 65,421,218 | I am trying draw a man in C++ | #include<iostream>
using namespace std;
int main()
{
cout<<" O"<<endl;\\print O
cout<<"/ || \<<endl;\\print /||\
cout<< "/ \" <<endl;\\print / \
return 0;}
I am to print a standing man in console out that are upper given .but when I am compile it it give me error like (missing terminator character). If ... | \ has special meaning, it starts an escape sequence.
Your code should be
#include<iostream>
int main()
{
std::cout << " O" << std::endl; // print O
std::cout << "/ || \\" << std::endl; // print / || \ . some extra character to avoid final backslash in comment
std::cout << " / \\" << std::endl; // print... |
65,421,161 | 65,421,370 | Visual Studio Code cannot open source file "iostream" | I am new to C++ and Visual Studio Code, so I'm not sure how to fix this issue. I've tried to go through the tutorial in Using Clang in Visual Studio Code, but I can't seem to paste their "Hello, World!" code without the iostream, vector, and string errors.
I've also seen posts on here indicating that I should change th... | Your includePath only has ${workspaceFolder}. You need to add the path to your system directory. Run this command and make sure all of the paths printed out are listed in your c_cpp_properties.json file: gcc -v -E -x c++ -
|
65,421,510 | 65,423,403 | why address of variable is different to what is returned by pointer? | i am using this manipulate function to get the pointers address but it returns anything else.
#include<iostream>
using namespace std;
int *manipulate( int &b) {
int *a=&b;
cout<<&a<<" "<<&b<<" "; // why memory add of 'a' and 'b' different ?
return a; // is it returing pointer which stores addr... | in manipulate function you receive &b by reference.
in this line:
int *a=&b;
you have defined a pointer variable a with value of b address
in this line:
cout<<&a<<" "<<&b<<" ";
you have printed the address of a (the pointer) and address of b
if you want them the same you could:
cout<<a<<" "<<&b<<" ";
and finally you... |
65,421,570 | 65,421,649 | Code it being affected by a cout which is not need it code | The program simply have a function which checks if a number is a perfect number. A perfect is the one for which sum of all its factors(excluding number itself) is equal to number it self. Like 6(1 + 2 + 3 = 6) also 28
I am seeing a werid behavior. There is cout << "". If we remove this line code will not work properly ... | The code has nothing to do with the cout. Look in the loop in isPerfect function. The variable i has undefined value as it is not initialized. Initialize it like this:
for(int i = 1; i<a; i++){
|
65,422,518 | 65,422,595 | Arduino - Optimisation for Arduino based math calculator? | How can I optimise my code?
#include <Keypad.h>
const byte ROWS = 4;
const byte COLM = 4;
char keys[ROWS][COLM] =
{
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {13, 12, 11, 10};
byte colmPins[COLM] = {9, 8, 7, 6};
Keypad keypad = Keypad(make... | Okay, so your code here can be optimized in several ways. Using methods for operators that are already built in to C++ is not very optimal. Also rather than the methods returning an integer, it would be better to return a long, double or float.
Here is your optimized code
#include <Keypad.h>
const byte ROWS = 4;
const... |
65,422,861 | 65,423,604 | why c++ insert a junk to array? | I wrote a function to insert an element by index into an array and this is the function:
bool insertByindex(int array[], int size, int index, int element) {
if (index > size || index < 0) {
cout <<"Invalid position!";
return false;
} else {
for (int i = size; i > index; i--) {
array[i] = array[i -... | Here is the culprit:
for(int i=size; i>index;i--){
array[i]=array[i-1];
At first iteration i is the size of the array, so you assign past end of the array!
It invokes Undefined Behaviour and bad things start to occur... Here the implementation has probably put the size variable just after the array and you... |
65,423,430 | 65,423,811 | Overlaying text and graphics (stroked rectangles) on desktop screen | For an accessibility desktop application I must overlay the desktop screen with numbers, text and a grid of rectangles (stroked with e.g. red brush).
Ideally this should work on any window manager system (windows, linux KDE/GNOME, possibly even mac).
What is the standard approach to something like this? I was thinking ... | There is a library that could help you out in making cross-platform applications. glfw, this is capable of making an application window for windows, mac, Linux, and more.
For the graphics stuff, you could use OpenGL or Vulkan(personally not advised for new users) graphics APIs which are cross-platformed. I was thinkin... |
65,423,895 | 65,502,243 | How to get serial communication data and use it in C++? | I only have a UART to USB converter module, and I'm connecting that module with a GPS module. So now the GPS module is connected to the converter, and the converter is connected to my PC through micro USB cable.
I have used PuTTY to read the serial data coming from the GPS. However, I want those same data to be read fr... | I have attached a small sample that I use to test my USB to serial adapter.
#include<windows.h>
#include<iostream>
int main()
{
HANDLE hComm;
std::string port_name = "COM1"; //change port name
char write_buffer[] = "Test Data";
char read_buffer[100];
DWORD dNoOFBytestoWrite; // No of byte... |
65,423,970 | 65,426,067 | Hide/fold/dim arbitrary lines of code by regex (e.g. to hide logging) | There is a lot of logging in my C++ project. The logging is done via a log stream and the log lines have the following format:
APP_LOG_XXX() << ... ;
Those log lines blend with the rest of the code and make it harder to be read.
I want to somehow make these log lines appear in dimmed colors, or even better to hide/fol... | You can use extension Highlight.
Set the color to a version close to your theme background color
Add to your settings.json
"highlight.regexes": {
"(APP_LOG_XXX\\(\\) <<[^;]+;)": {
"regexFlags": "mg",
"decorations": [
{ "color": "#f0f0f0" }
]
}
}
Or you can use the opacity decorati... |
65,424,131 | 65,424,389 | Difference between returning by value and returning that value through a void function | Here is an example of what I'm trying to understand:
//no param function
std::string getPassword()
{
std::string password;
getline(std::cin, password);
return password;
}
//param function by ref
std::string getPassword(std::string& password)
{
getline(std::cin, password);
return password;
}
//v... | std::string getPassword() is the best way. It is just as efficient as using a reference parameter, thanks to return value optimization. In fact, it could even be more efficient since there is only a limited amount of parameters that can be passed via registers, so if you have a function that takes many parameters, it's... |
65,424,162 | 65,424,586 | How to implement binary128 in C? | I started to try and implement new data types, specifically floating-point values, using C. I came up with this sort of way on implementing binary128 using longer_int which I haven't fully understood.
The way how I started was to implement it via copying the code and modifying it. However, the code is C++, and C doesn'... | You should begin with something like this: a struct instead of a class, ignore the public/private keywords, the constructors are methods that return the my_int128. There is no overloading in C, so each different constructor must have a different name. Another school of thought would say that you don't need specialized ... |
65,424,525 | 65,428,997 | Distribute and centre items over wxBoxSizer's full orientation without stretching | I am just learning about sizers and am kind of confused on how to accomplish this.
If I have a single horizontal box sizer in a frame and add two buttons to it (each with proportion "1") then they will both stretch to take up the full horizontal width of the sizer (which equals the full horizontal width of the frame) a... | One way to do it is with stretch spacers:
buttonSizer->AddStretchSpacer();
buttonSizer->Add(buttonOk, 0, wxALL, 10);
buttonSizer->AddStretchSpacer();
buttonSizer->Add(buttonCancel, 0, wxALL, 10);
buttonSizer->AddStretchSpacer();
|
65,424,564 | 65,424,750 | minimizing the number of if clauses | help with ranking scores
Hello I want to ask you all for an efficient algorithm regarding ranking scores.
We take three things into account. The amount of balls in the goal, the amount of balls that the haven't been shot by the players yet/each player has five balls) and the player number( player 1 , player 2)
If two p... | First define a data structure:
struct player {
int goals = 0;
int balls = 0;
};
Then use a vector:
std::vector<player> players;
Then use std::sort to sort it:
#include <algorithm>
std::sort(players.begin(),players.end(),[](const player& a,const player& b) {
return .... put logic to decide if a is be... |
65,424,643 | 65,466,606 | libtorch : How to create a gpu tensor base on data_ptr? | create a gpu tensor base on data_ptr?
int main{
auto ten=torch::randn({3,10},torch::kCuda);
auto p=ten.data_ptr<float>();//I believe "p" is a gpu pointer?
auto ten2=torch::from_blob(p,{3,10});//ten2's device=cpu,that's the problem
cout<<ten2;//then I got error:"interrupted by signal 11... | I believe you should declare ten2's device to be GPU, like that :
int main{
auto ten=torch::randn({3,10},torch::kCUDA);
auto p=ten.data_ptr<float>();//I believe "p" is a gpu pointer?
auto options = torch::TensorOptions().device(torch::kCUDA);
auto ten2=torch::from_blob(p,{3,10}, options);
cout<<te... |
65,424,719 | 68,442,209 | Memory leak in gRPC async_client | I am using gRPC async client in similar way to the example.
In this example (published in the gRPC official github) the client allocate memory for the message to send, using the address as tag for the completion queue, and when the message is being answered in listener thread the memory (known by the tag- address) is f... |
Does the gRPC protect me from this situation?
Kinda. gRPC guarantees that all queued operations will end up in their matching completion queue sooner or later. So your code is ok as long as:
No exception is thrown at an unfortunate time.
You don't make a change to the code that creates a code path that doesn't inclu... |
65,424,751 | 65,425,910 | A weird issue about converting a reference type to another by using operator reinterpret_cast | #include <iostream>
int main(){
int& rf = reinterpret_cast<int&>((int&&)1);
}
In this example, GCC and MSVC do not accept this code. Instead, Clang compiles it successfully. The result is here.
Through researching the relevant rule, the corresponding rule is:
expr.reinterpret.cast#11
A glvalue of type T1, designati... |
So, according to the rule [expr.unary#op-1], the value category of *reinterpret_cast<T2 *>(p) is lvalue.
No, because [expr.reinterpret.cast]/11 doesn't say the reference-casting expression is equivalent in every way to *reinterpret_cast<T2*>(p). It says the expression's result is the same as that expression's. Here ... |
65,425,293 | 65,425,405 | Can't catch thrown exception by reference in c++ | #include <iostream>
using namespace std;
int main() {
int a = 3;
cout<<"Address of a = "<<&a<<endl;
try{
throw a;
}catch(int& s){
cout<<"Address of s = "<<&s<<endl;
}
return 0;
}
Output:
Address of a = 0x7ffeee1c9b38
Address of s = 0x7fbdc0405900
Why are the addresses of a and s different??
| They have different adresses, because they are different objects. From cppreference about throw :
throw expression
[...]
First, copy-initializes the exception object from expression
[...]
The reason to catch by reference is not so much to avoid a copy, but to correctly catch exceptions that inherit from others. ... |
65,425,401 | 65,426,037 | How do you call types that tend to spread over the whole codebase like a string type? | When watching C++ videos on YouTube, I heard people use a special word for types that tend to spread over the whole codebase, because they are very commonly used and often used to make interfaces more expressive, like std::string, QString, QPoint, std::path etc.
I think they used the name lexical type but I am having a... | I think the term is vocabulary type. At least, that is the term used during discussions at Committee meetings.
|
65,425,427 | 65,439,642 | How to keep a Form always on top without stealing focus from the active Window? | My question: how I can keep my Form always on top (I can do it setting TopMost = true) without stealing the focus from the Window currently active when my Form is interacted with.
Take a look at the images to better understand my question: the Form is on top and when I focus on any other Input control outside my Form, ... |
Make a standard Form, set its FormBorderStyle = none. Make it TopMost (this setting is another topic per se, I'm no going to discuss it here).
Override CreateParams to set the WS_EX_NOACTIVATE and WS_EX_TOOLWINDOW extended styles. This prevents the Form from being activated when mouse events are generated inside its s... |
65,425,572 | 65,425,899 | The default constructor cannot be referenced | I am making a school project and I need to create a library system with bidirectional list and structures. I want to implement constructors to make my code more clear. The problem shows up when i want to creacte struct for bidirectional list and reserve memory space for list element using new list_of_books. The error m... | struct User {
std::string name;
std::string surname;
User(std::string name, std::string surname)
: name(name), surname(surname) {}
};
this constructor is harmful. You have an aggregate -- a type that is its data -- and a constructor that just repeats the members in order.
Do this:
struct User {
std::stri... |
65,425,755 | 65,426,144 | in c++ i get the error: cannot convert 'bool' to 'bool*' in return | Im new to c++ and im trying to get a bool* function with a dynamic array as its parameter and its size to return true or false when none of them is zero but im getting an error: cannot convert 'bool' to 'bool*' in return.
bool* noneZero(int *zero, int N) {
int PL = 0;
for (int i = 0; i < N; i++) {
if (i... | Problem:
A bool* must return a pointer a pointer to a bool, not a bool itself.
You're checking the value of i, not the values of the array.
Solution:
Change the function from a bool* to a bool.
Change i == 0 to *(zero + i) == 0.
Additional information:
Seems like you're using using namespace std;. using namespace ... |
65,425,950 | 65,428,453 | Check if list item is repeated comparing to start date | I have a list of objects which has some properties.
class Accounts
{
long id;
CString account;
CTime start;
CTime end;
};
To show it better it looks like something like this:
ID Account Start End
-----------------------------------------
1 Bob 23-Jun-20 23-Jun-20
2 ... | In single loop you can re-arrange your data to find out which account is active/inactive. Also arrange all IDs in a list for same account.
Sample below (is_active is just a function or logic to determine account is active and not expired, for example : start < 120 in your case):
std::map<string, bool> accountStatus;
st... |
65,426,136 | 65,435,602 | The byte stream type of the given URL is unsupported MediaFoundation | I need to create a reader from buffer(that is wav bytes) in order to do it I am using such approach:
void co_AudioEncoderMF::load_from_memory(unsigned char const * data, long data_size)
{
unsigned char * buf = new unsigned char[data_size]; //JUST FOR TEST IN ORDER TO BE SURE THAT I HAVE THIS DATA
memcpy(buf, da... | In my case problem was in that I tried to call this method MFCreateSourceReaderFromByteStream on stream that was created on wav bytes, but it didn't includes .wav header. So, I was needed to add a header. I used this method
/*static*/ void Utils::append_data_to_wav_header(unsigned char * buff, int buff_size, int num_of... |
65,426,246 | 65,426,395 | Why should extern be used in a variable declared in a header file? | I was researching in depth about C ++ header files after I often received the LNK2005 error in the Visual Studio compilation, and realized that the error was that I was declaring a variable twice, in the header file and in main.cpp, and I also found several users giving the solution how to use the extern type variable_... | In C++ a variable declaration at namespace scope is a definition unless it is declared extern. The extern prevents the declaration from being a definition. You can define a variable only once within a program (unless you make it inline). As headers are normally included in multiple translation units you’d get multiple ... |
65,426,325 | 65,427,016 | C++ | Derived class is accessing private members of the base class rather than its own private members | sorry if this is an obvious one but I've searched around and I'm still unclear about how to solve this issue. Here is my code:
#include <iostream>
#include <string>
using namespace std;
class PermMagnet {
public:
string name;
int ac_rating;
int dc_rating;
int mass_kg;
int age;
PermMagnet(){
... | Inheritance uses an "is a" relationship. Meaning, you should be able to say that a child object "is a" base object. If you cannot say this, you shouldn't be using inheritance.
What this means for the building of a derived object is that it is a composite, containing your base object, and whatever extra bits have been a... |
65,426,477 | 65,426,704 | How can I get 2 integer values from one input? | I'm only in 10th grade and there is an exercise where I have to get an input like (input = 1/2) and this input needs to be stored in 2 different integers and I don't know how to do that.
Any help is appreciated.
Sorry if this question sounds dumb, but this is my first post here and I don't know the etiquette.
Thanks in... | Simply use the existing iostream functionality. There is nothing complicated about that. String parsing is not necessary. The inserter operator will skip whit spaces. Additionally, it will convert your given values into an integer variable. The slash will be read, checked and then discarded.
#include <iostream>
int ma... |
65,426,585 | 65,426,794 | std::move(std::string) not making passed argument to empty state | I'm bit confused why the std::move(std::string) not making the passed std::string argument to an empty state (I mean std::string size as 0 and its internal buffer to point to nullptr after call to std::move(std::string)). This is a sample code
#include <iostream>
#include <string>
void print(std::string& str) {
st... | std::move is not moving anything. It cast its argument to an rvalue-reference. To actually move you need to pass str as rvalue-reference to move constructor(or move assignment) of another string as below.
std::string new_str(std::move(str));
print(str);
|
65,426,651 | 65,433,675 | Can't find what's causing access violation in array | !!!I have to stick with these functions as I'm not allowed to use any different!!!
A little explanation what I need to do: user input a search directory, then if nothing was found an error message pops up. If something is found, I create an array of one row because at least one file was found and it saves the name of f... |
fileNames.str = (wchar_t**)malloc(sizeof(wchar_t*) * fileNames.rows);
len = wcslen(FindFileData.cFileName)+1;
fileNames.sym = (wchar_t*)malloc(sizeof(wchar_t) * len);
wcscpy_s(fileNames.sym, len, FindFileData.cFileName);
This issue exists in above lines. You allocate memory for str but you don't allocate memory for... |
65,426,854 | 65,438,580 | How to solve "IServiceProvider" is ambiguous when using "wininet" and "windows.h"? | I'm trying to check if the internet connection exists or not by using the InternetCheckConnection function of wininet.
Here's my CheckerClass: which handles the process of checking.
#pragma once
#include <Windows.h>
#include <wininet.h>
#pragma comment(lib,"wininet.lib")
#include <String>
public ref class CheckerClass... | What kind of CheckerClass do you have? Classes are normally split up into two files. Which mean you should have CheckerClass.h and CheckerClass.cpp. Where is that code above from those two files?
In any case, here's example of a working class base on your code.
In your CheckerClass.h file, you should have;
#include <st... |
65,427,083 | 65,428,012 | Can you tell me what is the time complexity (Big-O) of my function? | Function receives an array, length of array
and number of consecutive elements of an array.
I run an array and look for the maximum sum of 'K' consecutive elements
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int GetLargestSum(int array[], int length, int k)
{
int largestSum = 0;
int ... | The point of analysing complexity is to find out largely how much time (time complexity), storage (storage complexity) or memory (memory complexity) an algorithm is using. For this we tend to think about (infinitely) large dimensions, because if the dimensions are very small, we tend not to care them about too much. Yo... |
65,427,185 | 65,445,501 | How to fix the blurry Form or UI of Visual Studio 2019 on C++ Project? | The issue of blurry form or UI of VB.Net on Visual Studio 2019 can be solved by adding and configuring the app.manifest.xml of the project and adding the <dpiAware>true</dpiAware> into it.
However, I tried using the same approach on my C++ project in Visual Studio 2019 but there's no available manifest to add to the pr... | So C++ Project on Visual Studio 2019 has a different approach when setting the DPI Awareness of the UI.
In order to do so, Right-Click on the Project then open the Properties > Manifest Tool > Input and Output > DPI Awareness and select the option High DPI Aware, click Apply and OK buttons then run the project and viol... |
65,427,439 | 65,427,525 | Why is this iterator arithmetic not working? | I am learning C++ for fun. I am trying to understand iterator arithmetic and have written a simple program that sums the first element in a vector with the last element. Next the second and second-to-last elements are summed. The process continues until all elements have been summed in this manner.
The issue seems to b... | Subtracting 2 iterators with a.end() - 1 - it gives you the distance between them. You can't dereference a distance with * and so you get a compiler error.
This distance from a.begin() to the element you want to get at is needed in the expression. You can adjust the expression slightly by just adding a.begin() to that ... |
65,428,317 | 65,428,528 | reinterpret_cast of __uint128_t | As I know reinterpret_cast must not lead to data loss.
So it is not possible to compile such code in X86_64 due integer is smaller than pointer
#include <cstdio>
int main() {
int a = 123;
int res = reinterpret_cast<int>(reinterpret_cast<void*>(a));
printf("%d", a == res);
}
The question is: why I can compi... | It's explained here https://en.cppreference.com/w/cpp/language/reinterpret_cast
A pointer can be converted to any integral type large enough to hold all values of its type (e.g. to std::uintptr_t)
That's why you have an error for the first case
A value of any integral or enumeration type can be converted to a poi... |
65,428,348 | 65,428,449 | C++ Kill a Thread In Destructor | I have a class that starts another thread that accesses some of its data at constant intervals. This means I have two threads that access the same data (the original thread and the newly created thread). This introduces the need for a mutex. All goes well until the destructor of the class is called (at the end of the p... | If you want a thread to die, you should ask it to exit. It's the only reliable way to do it cleanly.
Just change
while (true)
to
while(this->keepRunning)
and synchronize it appropriately. Either don't detach the thread (so the destructor can join it) or add some way for the thread to indicate that it has exited (so t... |
65,428,350 | 65,428,421 | maximum value of a vector displays as 0 | I enter a vector A = {0,10}.
Then I add 2 to each element that is less than the average and subtract 2 from each element that is more the average. After this operation, the new vector is {2,8} but when I try to print the maximum value of this vector, I get 0 for some reason.
int smallestRangeI(vector<int>& A, int K) {
... | std::max returns the larger of the 2 elements. You are passing it two iterators, the larger of which is A.end(), and then you're dereferencing that, which invokes undefined behavior.
It appears you are looking for std::max_element instead, which gives you an iterator to the largest value in A which you can then derefer... |
65,428,577 | 65,428,930 | Get error message from a Google Test after running it | I'm implementing a custom runner for Google Testing Framework that runs a concrete TestInfo separately and checks its status:
TestInfo* info = ...;
testing::GTEST_FLAG(filter) = std::string(info->test_case_name()) + "." + info->name();
RUN_ALL_TESTS();
std::cout << (info->result()->Passed() ? "Success :)" : "Error :(")... | Just downloaded GitHub repo of googletest and looked through code. Seems that your FAIL() message can be retrieved by next code (don't have any gtest project to test correctness of code):
for (auto const & pr:
testing::internal::TestResultAccessor::test_part_results(*info->result()))
if (pr.fatally_failed())
... |
65,429,218 | 65,429,338 | C++20 | std::is_constant_evaluated() and const variables | Let's consider the following code:
#include <type_traits>
int foo(int arg) {
if (std::is_constant_evaluated()) {
return 1;
} else {
return 0;
}
}
int main() {
const auto b = foo(0);
return b;
}
It returns 0 with both gcc and clang. I would have expected it to return 1 instead.
I... | std::is_constant_evaluated() returns true if and only if [meta.const.eval]:
evaluation of the call occurs within the evaluation of an expression or conversion that is manifestly constant-evaluated
This term, "manifestly constant-evaluated" (defined here), refers to contexts that have to be constant-evaluated. A call ... |
65,429,349 | 65,429,416 | Add methods which return same class objects to a existing class in C++ | One way to add methods to a class without changing it is with inheritance (e.g., Add a method to existing C++ class in other file). However, this solution causes a problem to the toy program below:
#include <vector>
class c_A {
public:
std::vector<int> v;
c_A one_element(void) {
... | You can add your own one_element() wrapper along with a c_Aext constructor that'll take a c_A:
class c_Aext : public c_A {
public:
c_Aext() : c_A() { } // just call parent's default
c_Aext(const c_A c) : c_A(c) { } // call parent's copy
c_Aext one_element() { return c_Aext(c_A::one_element()); }
};
Full ... |
65,429,537 | 65,429,576 | Specify insertion or append to linked list in c++ | I want to ensure before I add the value to the linked list if the number is odd I want to add it to head (my alias is left) if else I want to add it to the last(my alias is right) here is my code
The Node struct
struct Node{
int data;
Node *next;
};
The Linked List class
class LinkedList{
Node *left;
N... | You're forgetting to link the last (rightmost) node to your new node in append(). Before you update right, you need to add:
if(right != nullptr) { right->next = temp; }
So it'll become:
void append(int value)
{
Node *temp = new Node();
temp->data = value;
temp->next = NULL;
if(right != nullptr) { righ... |
65,429,853 | 65,429,926 | How to understand the definition of "manifestly constant-evaluated"? | P0595 introduced the std::is_constant_evaluated() function. The paper discusses how there are some situations where the containing expression is a constant expression, but one that the compiler is not required to evaluate at compile time. The example given is:
constexpr double power(double b, int x) {
if (std::is_con... | This is my favorite. It doesn't say " a constant expression." It says "a constant-expression."†
constant-expression is a grammar term. It's a stand-in for those places in C++ grammar where a constant expression is mandated.
For instance, the grammar (specifically, the grammar) for a template-argument is constant-expres... |
65,430,044 | 65,430,169 | Why is array initialization with brackets () marked as error by compilers? | I was researching the initializer syntax in C++, and according to cppreference, there are three possible ways of writing it, 1) brackets, 2) equal sign, 3) braces.
When trying to initialize an array with the 1) brackets syntax, I encounter an error.
int test() {
int a[](1);
return 0;
}
Testing that on Compile... | The feature that you're trying to use was added in C++20, and is called "Parenthesized initialization of aggregates". As can be seen from the compiler support page, GCC supports this from GCC10, whereas Clang doesn't support this feature yet.
|
65,430,224 | 65,430,288 | Why does string::c_str() return a const char* when strings are allocated dynamically? | Why does it return a constant char pointer? The C++11 standard says:
The pointer returned points to the internal array currently used by the string object to store the characters that conform its value.
How can something that is dynamically allocated be constant(const char*)?
| In C and C++, const translates more or less to "read only".
So, when something returns a char const *, that doesn't necessarily mean the data it's pointing at is actually const--it just means that the pointer you're receiving only supports reading, not writing, the data it points at.
The string object itself may be abl... |
65,430,266 | 65,430,422 | C++ Wait in main thread for future without while(true) | Question
I want to know if it is possible to wait in the main-Thread without any while(1)-loop.
I launch a few threads via std::async() and do calculation of numbers on each thread. After i start the threads i want to receive the results back. I do that with a std::future<>.get().
My problem
When i receive the result i... | I'd approach this somewhat differently.
Unless I have a fairly specific reason to do otherwise, I tend to approach most multithreaded code the same general way: use a (thread-safe) queue to transmit results. So create an instance of a thread-safe queue, and pass a reference to it to each of the threads that's doing to ... |
65,430,599 | 65,434,015 | Using multiple VBO in a VAO | I try to use 2 VBO inside a VAO and I end up with a crash (far beyond my app).
The idea is to make a first VBO (and optionnally an IBO) to stucture the geometry.
This worked well, until I get the idea to add a second VBO for the model matrix as a vertex attribute instead of an uniform.
So, when I declare my mesh I do a... | I found the error glVertexAttribDivisor() is part of the old ways (like glVertexAttribPointer(), ...), I switched to glVertexBindingDivisor()/glVertexArrayBindingDivisor() and now there is no crash at all.
Answers were there : https://www.khronos.org/opengl/wiki/Vertex_Specification#Separate_attribute_format
|
65,430,677 | 65,434,037 | Concept for type name int | I am trying to write a concept for type name int but not been able to find one. I can't think of any operation that is valid just on int type and not valid for double, float, etc. Is it possible to write this with current standards? Thank you in advance.
Note: My aim is to make this code work by fixing the part with qu... | Concepts are defined by boolean expressions
template<typename T>
concept Int = std::is_same_v<T, int>;
But due to concept ordering issues, it's better to use
template<typename T>
concept Int = std::same_as<T, int>;
However, you should always use simpler tools when they suffice. In your case, simply overloading is fin... |
65,431,193 | 65,431,311 | C++ primer 5th ed function template specialization | Hello I have this code from C++ primer 5th ed:
Primary function template:
// first version; can compare any two types
template <typename T>
int compare(T const& x, T const& y)
{
std::cout << "compare(T const&, T const&)\n";
if(std::less<T>()(x, y))
return -1;
if(std::less<T>()(y, x))
return... | With respect to your first question: the function is an overload and not a specialization. There is no way to partially specialized a function template to start with. Beyond that, a specialization would mention an empty template parameter list. For example, the version for char const* is a specialization:
template <>
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.