question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,901,239 | 69,902,363 | Points depth buffer not sorting properly | I am fairly new to OpenSceneGraph and I am working on an application that generates point clouds. We first create an osg::Geometry object containing the points of a particular area, we then create an osg::Geode that contains the geometry and then we add it as a child to an osg::Group that contains all of the terrain po... | As suggested by @Scheff'sCat, depth testing was not enabled. Adding the following line fixed my problem.
m_terrain_group->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
|
69,901,249 | 69,918,732 | UE4 C++ APlayerController::GetHUD always return null | Here is my code.
void AFpsCharacter::ClientRPCInitializeHud_Implementation()
{
AFpsPlayerController* PlayerController = (AFpsPlayerController*)GetOwner();
if (IsValid(PlayerController))
{
AFpsPlayerState* State = PlayerController->GetPlayerState<AFpsPlayerState>();
UE_LOG(LogTemp, Log,... | I guess the problem is the default HUD instance isn't created by default HUD class of GameMode. I don't know well why it is happened even i checked default HUD class in GameMode. So i choose temporary solution. Using APlayerController::ClientSetHUD(TSubclass<AHUD>). In my case, each ACharacter has TSubclassOf<AHUD> and... |
69,901,358 | 69,902,111 | Comparing same types with different names | I've got
typedef void* TA;
typedef void* TB;
I need to compare names of types as different types.
There are std::is_same<TA, TB>::value and typeid(TA)==typeid(TB) return true, but I need false.
| That is not possible because they are the same type.
If you are trying to use these as opaque handles with strong type-checking, another thing you can do is to forward-declare the classes in a header, and define them in your implementation file:
// ta_tb.hpp
typedef struct ta_impl* TA;
typedef struct tb_impl* TB;
Lat... |
69,901,406 | 69,901,715 | How to define the include & lib path when building pybind11 proj | I am building a pybind11 project with Visual Studio (2017). The setup file is like below:
from setuptools import setup, Extension
import pybind11
# The following is for GCC compiler only.
#cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
cpp_args = []
sfc_module = Extension(
'test_sample'... | I know where to add more include paths, and the lib paths. One need to add them in the system environment variables: INCLUDE and LIB.
Control Panel->Edit Environment Variable. Then add all the intended paths for include files to the variable INCLUDE, and add all the library paths to the variable LIB.
Then the rebuild s... |
69,901,682 | 69,903,562 | Debug Assertion Fail (vector subscript out of range) | I found that my result.push_back(make_pair(a[i], b[j]));, which
causing this error but i dont know why (i don't even access vector<pair<int,int>>result;)
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<utility>
using namespace std;
void input(int n,vector<int>&a) {
int temps;
... | if (j > b.size() - 1) { break; } //(1)
if (a[i] + b[j] >= check) { //(2)
j++; plate2++; // HERE IS YOUR PROBLEM (3)
result.push_back(make_pair(a[i], b[j])); //(4)
Assume that j == b.size()-1 at the beginning. The if (j > b.size() - 1) clause is false, so the loop does not... |
69,901,741 | 69,902,171 | Automate repeated code for various types? | Is there is any way by which I can automate this
DeserializeComponent<IDComponent>(json, e);
DeserializeComponent<NameComponent>(json, e);
DeserializeComponent<PointLightComponent>(json, e);
// ...
As you can see here, the same code is executed for different types, but in C++ you can't store types in a std::vector as ... | Types can't be stored in variables. Types are only for the compiler. Even RTTI doesn't store types in variables, but rather "names" of types.
I think you just want to make the code shorter by not having to type DeserializeComponent<>(json, e); over and over. Well, you can do that with parameter pack expansion.
template... |
69,901,977 | 69,902,567 | How to get all child objects of a class | Is it possible to retrieve a list of child objects (of a cetain type) of an object ?
For example in this code I have an App with several available Commands. A function print all availible commands this way the user knows what he can do.
I want to iterate over each object of type Command found in App to print his doc, t... | This may solve your problem.
#include <cassert>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class Command {
public:
std::string Name;
std::string Description;
Command(std::string Name, std::string Description)
: Name(Name), Description(Description) {}
virtua... |
69,902,222 | 69,902,302 | Print struct pointer using function c++ | The problem is that the program does not print any values when using the pointer, I searched a lot and there seems to be no solution. any ideas?
#include <iostream>
using namespace std;
struct Brok{
string name;
int age;
void pt(){
cout << "Name : " << name << "\nAge : " << age;
}
};
int mai... | You need to allocate the object a1 is "pointing to", e.g. Brok *a1 = new Brok();.
EXAMPLE:
/*
* SAMPLE OUTPUT:
* g++ -Wall -pedantic -o x1 x1.cpp
* ./x1
* Name : John Wick
* Age : 46
*/
#include <iostream>
using namespace std;
struct Brok{
string name;
int age;
void pt(){
cout << "Na... |
69,902,400 | 69,902,517 | While loop breaks early | I've made a program that asks for student information (name, course and grade) and it is configured to break whenever the input name of a course or a student is stop
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> v;
string name;
string course;
... | For starters this if statement
if (name != "stop") {
should be enlarged and include the inner while loop that should be rewritten as a do while loop.
For example
while (name != "stop") {
cout << "Please type a student name: ";
getline(cin, name);
if (name != "stop") {
v.push_back(name);
... |
69,902,639 | 69,903,739 | How can I avoid relative paths in #includes when building with Bazel | I'm struggling to understand the logic of how includes work in Bazel targets. I want my code to be modular, so I am trying to avoid #include statements with relative or long absolute paths.
Suppose I have the following workspace structure:
tree . ... | That includes should go in //lib:graphs, so that anything which depends on it (has it in deps) uses it. lib/BUILD should look like this:
cc_library(
name = "graphs",
hdrs = ["graphs.h"],
srcs = ["graphs.cpp"],
includes = ["."],
visibility = ["//visibility:public"],
)
Then you drop includes from is_... |
69,902,741 | 69,902,889 | Constructor invocation in C++ | I tried to find out the output of this program in C++.
#include<iostream>
using namespace std;
class MyInt {
int i;
public:
MyInt() {
cout<<1;
i = 0;
}
MyInt(int i) {
cout<<2;
this->i = i;
}
int value(){
return ... | MyInt i;
The above line invokes MyInt::MyInt(), creating an object and outputting 1.
i = 10;
The above line invokes MyInt::MyInt(int i), creating another object and outputting 2. The second object is then assigned to the first object, which outputs nothing.
cout<<i.value();
The above line invokes MyInt::value(), ou... |
69,903,058 | 69,903,138 | Why move assignment in my class wasn't called? | Consider this code:
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
struct BigInteger
{
vector<int> arr;
BigInteger()
{
cout << "default constructor" << endl;
this->arr.push_back(0);
}
BigInteger(initializer_list<int> il)
{
cout <<... | Primarily, move assignment operator isn't called because you aren't assigning anything. Type name = ...; is initialisation, not assignment.
Furthermore, there isn't even move construction because BigInteger({0, 1, 2}) is a prvalue of the same type as the initialised object, and thus no temporary object will be material... |
69,903,174 | 69,903,753 | C++ how to copy contents of std::array to another? | Its fairly well known on how to copy a standard c array into another:
char test[20] = "asdasd";
char test2[19] = "asdassdsdfd";
strcpy_s(test, sizeof(test), test2);
But how can I do the same with a std::array? (preferably without for loops)
std::array<char, 20> test = {"asdasd"};
std::array<char, 19> test2 = {"asdassd... | There are many ways. You could use strcpy_s(test.data(), sizeof(test), test2.data()), but I wouldn't recommend it. The more-generic version of basically the same thing is std::copy_n(test.begin(), test.size(), test2.begin()); which would continue to be correct even if the type in the std::arrays changes. Given they are... |
69,903,891 | 69,904,034 | Is it legal to cast array of wrapper structs containing POD to the array of POD type it contains? | Is this C++ code valid or undefined behaviour? The idea is to be able to wrap a POD you have no control over into another struct to provide helper functions but still be able to use it as if it was the original POD.
struct Data
{
...//POD
};
struct Wrapper
{
Data data;//contains only this
void HelperFuncA();
vo... | Now, this code is not valid. There are several reasons for this. First, casting a pointer to the first member of the struct to the struct itself violates strict aliasing rule. This you can fix by making Wrapper a child class of the Data.
The second issue is more problematic, as you are trying to treat an array (vector ... |
69,904,119 | 69,904,212 | Minimum number of squares | There is a problem that states:
John has a piece of paper with NxM dimensions, he wants to cut it into
1x1 squares, with the rules:he can cut the piece of paper only once at
a certain time, every cut has to go all the way around the paper
This is the code for it:
int n , m;
cin >> n >> m;
cout << (n - 1) + 1LL * n *... | This is my understanding of the question based on the answer:
You cut the paper into N equal length pieces. Each has a length of 1 and width of M. This requires (N-1) cuts.
For each of these N sheets, you cut them into M equal pieces which have 1 width and 1 length. This requires (M-1) for each sheet so, N * (M-1) in ... |
69,904,152 | 69,904,279 | Reading integer then rest of the line as a single string from input | Suppose I'm trying to read from the following input.txt
6 Jonathan Kim Jr
2 Suzie McDonalds
4 Patty
... and I want to store the first integers from every line and the rest of the strings as a string variable. This is what I have tried:
int num;
string name1, name2, name3;
while ( ins >> num >> name1 >> name2 >> nam... | By default, the >> operator splits on a space, so you could use that to pull the integer into the variable. You could then use getline to grab the rest of the line, and store that into the variable.
Example (if you are reading from std::cin):
int num;
std::string name;
std::cin >> num;
std::getline(std::cin, name);
|
69,904,573 | 69,905,066 | Optional template parameter combinatorials | I have a set of template specializations (C++11) that uses the base template below, where both tPayLoad and tReturnType is present:
template <class tDerivedOperation, class tBridgeType, class tPayLoadType = void, class tReturnType = void> class OperationT ...
The 1st specialzation is when there is neither tPayLoadTyp... | The following
#include <iostream>
template<class tDerivedOperation, class tBridgeType, class tPayLoadType = void, class tReturnType = void>
struct OperationT {
static constexpr auto overload = "base";
};
template<class tDerivedOperation, class tBridgeType>
struct OperationT<tDerivedOperation, tBridgeType, void, vo... |
69,905,020 | 69,905,092 | What is the best/most intuitive way for a class to store a reference to a unique_ptr? | I have a class that manages a vector of unique_ptrs:
class Foo
{
public:
...
private:
std::vector<std::unique_ptr<SomeClass>> vec_;
};
I have another class, Bar, that I want to store some reference type that refers to an object in the vector. What is the most logical and intuitive way to achieve this?
The ones I c... |
The whole reason we use smart pointers is to avoid having to work with raw pointers
No: the whole reason we use smart pointers is to avoid having to work with owning raw pointers.
See, for reference, the C++ Core Guidelines:
R.3: A raw pointer (a T*) is non-owning
We do indeed prefer smart pointers to own resources... |
69,905,120 | 69,908,358 | How to put what the user picks for the row and column in the board | So my question is how do I put what the user enters, for example, they put row : 1 and column: 2 in my board that I made. I'm working on this in the void playerChoice function.
I've thought of some solutions to this problem like board[row][column] = 'X' in like an if statement with board[row][column] = 'O' as well. Is ... |
I've thought of some solutions to this problem like board[row][column]
= 'X' in like an if statement with board[row][column] = 'O' as well.
Yes. You can try the code below:
if (arr[row - 1][columns - 1] == '*')
{
arr[row - 1][columns - 1] = name;
}
else
{
cout << "Retry" << endl;
playerChoice(arr, name);
... |
69,905,226 | 69,910,082 | Display modified data from QAbstractListModel in QTableView | I have a QAbstractListModel that has a bunch of custom objects stored in it, and you can access the different fields of the custom objects in the model by specifying a role (if this is an improper use of Qt roles let me know because I must be confused). I want to display this data in a user friendly QTableView. I can g... |
and you can access the different fields of the custom objects in the model by specifying a role
If you look at the documentation for Qt::ItemDataRole, you would see that Qt models should indeed provide different data for different roles but each role means some distinguished purpose of the data corresponding to the r... |
69,905,233 | 69,905,767 | How can I fix my C++ code ? (no match for operators) | How can I fix my C++ code ? (no match for operators)
I got an error : no match for "operators-". What can be the problem and how can I solve it?
Can anybody help me to fix it ?
error: no match for 'operator-' (operand types are 'std::set::iterator' {aka 'std::_Rb_tree_const_iterator'} and 'std::set::iterator' {aka 'st... | std::set doesn't have random-access iterators. That is why you are getting the error.
To access the first and last elements of a set, use orai.begin() and std::prev(orai.end()). These return iterators, which will have to be de-referenced with operator*. So, correcting what I think you are intending to do, leads to the ... |
69,906,614 | 69,906,677 | C++ how to check for all variadic template type in a member function | e.g. I have the following Foo class with the foo() to check if all the types are std::int32_t
class Foo {
public:
/// check if all the types are std::int32_t
template<typename ...Ts>
bool foo() {
return true && std::is_same<Ts, std::int32_t>::value...;
}
};
int main()
{
Foo f;
std::cou... | https://en.cppreference.com/w/cpp/language/fold
return (true && ... && std::is_same<Ts, std::int32_t>::value);
# or
return (std::is_same<Ts, std::int32_t>::value && ... && true);
# or really just
return (std::is_same<Ts, std::int32_t>::value && ...);
|
69,906,870 | 69,906,904 | const int, member array size | My code basically:
class myclass : public singleton<myclass> {
public:
myclass();
private:
const float myfloat = 6000.0f;
const int sz_arr = (int)myfloat;
int arr[sz_arr]; // compiler complains about this line
};
Need to create arr at compile-time. Size of arr is known at comp... | Firstly, sz_arr can't be used to specify the size of the array, you need to make it static. And mark myfloat as constexpr to make it known at compile-time (and better for sz_arr too).
class myclass : public singleton<myclass> {
public:
myclass();
private:
constexpr static float myfloat = 6000.0f... |
69,907,247 | 73,815,163 | Eigen sparse solvers give drastically different solutions for the same linear system | I am trying to solve a sparse linear system as quickly as possible using eigen.
The docs give you 4 sparse solvers toc hoose from (but really it;s more like these three):
SimplicialLLT
#include<Eigen/SparseCholesky> Direct LLt factorization SPD Fill-in reducing LGPL
SimplicialLDLT is often preferable
Simpl... | https://eigen.tuxfamily.org/dox/group__TopicSparseSystems.html => SimplicialLDLT only for SPD matrices. You might try a least squares approach https://snaildove.github.io/2017/08/01/positive_definite_and_least_square/
|
69,907,324 | 69,907,505 | Word counter returning incorrect number of words | I've been trying to create a program that reads text from a file and stores it in a string. I feed the string to a function that counts every word in the string.
However its only accurate assuming the user leaves some whitespace at the end of a line and doesn't creates blank lines.... not a very good word counter.
Cre... | Your code is basically a state machine. To complete your solution, just count in the string ending.
Add this to the end of your code:
if(countingLetters) { // word at the end of string, without any space charactor
wordCount++;
}
Or if you can be sure it's C-style string, like std::string, you can just index 1 pass ... |
69,907,598 | 69,916,648 | Why doesn't the Variadic Template Function inside a while loop print to the console? | I want to try the flag-controlled while-loop statement that prints a statement and accept user input using variadic template function? Is this possible?
#include <iostream>
template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }
template<typename... __args> void read(__args && ...args... | As mentioned in comment, the variable a is not initialized. Hence, the variable contains a garbage value, so it will result into a runtime error.
Therefore first initialize the variable, then run a while loop on it.
And the code need to take the user input using variadic template function. So you can do this:
#include ... |
69,907,633 | 69,908,116 | In C++, why the 'iterator object' becomes invalid after calling 'erase()'? | I know the 'grammatical why'.
What I'd like to know is, 'techincal why'.
As far as I know, the 'iterator object' is mimic 'pointer'.
If it really mimics 'pointer', it should 'point' the erased index in the container.
Like, if a vector contains
index 0 1 2 3 4
val 10 20 30 40 50
and
vector<int>iterator iter = vec... |
If it really mimics 'pointer', it should 'point' the erased index in the container.
This inference doesn't make sense to me. Pointers are iterators for arrays. It isn't possible to erase elements from arrays, so they cannot be used as an example of how iterators should behave on erasure.
Even if the inference was app... |
69,907,901 | 69,908,739 | Understanding template function declarations | First place I saw syntax I didn't understand was here.
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Had a couple other small questions as I read this.
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
}... | Let's start with:
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Say you call sgn(42). Because 42 is an int, sgn<int> will be need to be instantiated so the signature becomes int sgn(int val) to match the call. Then the body becomes return (int(0) < val) - (val < T(0));, which makes... |
69,907,931 | 69,908,099 | Zig-zag pattern in C++ using cout function, for and if-else statements | While I was making a program in C++ for a zig-zag pattern I coded it as follows:
#include <iostream>
using namespace std;
int main () {
cout << "how many stars you want in zig zag pattern";
int n;
cin >> n;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= n; j++) {
if ((i + j) ... | You program is printing extra spaces because of the way you have wrote the if statements. Look at these statements:
if (((((i+j)%4)==0) && (i==1) )){ cout<< "*";}
if ((( j%2)==0) && ( i==2 )) { cout<< "*";}
if ( ((i+j)%4==0) && (i==3)) { cout << "*";}
else { cout<< " ";}
note that every... |
69,908,310 | 73,515,621 | cannot open source file "locale.h" (dependency of "iostream") | I continue to run into this include error / cannot open source file. I have now also tried resetting all of vs codes setting to default, but nothing I have tried has worked so far. Any advice on where to look would, or what's causing this would be extremely appreciated!
I have tried editing configurations in the json,... | I had the same problem.
Adding this to the include path fixed it:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1
I got the path from running:
gcc -v -E -x c++ -
Which outputs information about your gcc compiler.
I'm on an M1 Mac running Monterey.
This i... |
69,908,612 | 69,908,776 | Cast QList of derived to QList of base | I have these classes:
class IParameter {};
class ModuleParameter : public IParameter {};
Now I have QList of derived:
QList<ModuleParameter*> list;
When I cast single item it's ok:
IParameter *p = list[0]; // ok
When I cast the list I've got an error.
QList<IParameter*> *list = static_cast<QList<IParameter*>*>(&list... | QList is a template without common base class type and QList<ModuleParameter*> is a type unrelated to QList<IParameter*>, you can't access QList<ModuleParameter*> polymorphically through a pointer to QList<IParameter*>. What you trying to do is impossible to do this way.
Instead you may store pointers to ModuleParamet... |
69,908,758 | 69,908,836 | What is the difference between {} and () in std::visit function? | The following code is basically a more "naive" version of the example on variant found on CPP Reference. It defines a std::variant type (line [1]) and uses std::visit to iterate through a vector of that type. Here, I used a functor (line [2]) inside the std::visit function as an attempt for a better understanding of ho... | Print() is a call to constructor of class Print. Print{} is list initialization of class Print. In this case the difference is only int that list initialization actually would be aggregate initialization and would init members of Print if it had any, the constructor would not.
In both cases you pass an instance of Pri... |
69,908,798 | 69,909,053 | Difference Between Double's Notation | On the learncpp.com there is advice to write doubles as:
double num {5.0}
Is there any real difference between that and:
double num {5}
It seems that my compiler (VS 2019) treats those as equivalent.
| For that specific case, they are effectively equivalent, however, that's not always the case.
For example:
#include <iostream>
void foo(int v) {
std::cout << "foo(int) called\n";
}
void foo(double v) {
std::cout << "foo(double) called\n";
}
int main() {
foo(5.0);
foo(5);
}
That program produces:
foo(double... |
69,908,818 | 69,908,844 | C++: How to create a "conditional" constructor/avoid destruct on assignment? | Let's start with some example code:
class Shader {
public:
static absl::StatusOr<Shader> Create(const std::string &vertexShaderFile, const std::string &fragmentShaderFile) {
ASSIGN_OR_RETURN(GLuint vertexShader, gl::createShader(GL_VERTEX_SHADER, readFile(vertexShaderFile)))
ASSIGN_OR_RETURN(GLuin... |
I want to avoid the copy + destruct.
Normally, when your function return type matches the type of the variable you return, you don't need to do anything. There is no copying and no destruction taking place. Read about copy elision.
In your case, you construct Shader but return absl::StatusOr<Shader>. So there are two... |
69,908,968 | 69,909,207 | How to count words in huge file by spliting data? | I try to count word in huge file. I want to use max of CPU resources and i try to split input data and count words in threads. But i have a problem, when i split data it can split the words and in the end i have wrong answer. How can i split data from file to avoid spliting words? Can somebody help me?
#include <iostre... | The problem right now is that you're reading in a fixed-size chunk, and processing it. If that stops mid-word, you're doing to count the word twice, once in each buffer it was placed into.
One obvious solution is to only break between buffers at word boundaries--e.g., when you read in one chunk, look backwards from the... |
69,909,294 | 69,910,477 | How do I get the IPv4 address of my server application? | Even after sifting through many related posts I can't seem to find a suitable answer. I have a winsock2 application (code for server setup is adapted for my needs from the microsoft documentation) and I simply want to display the server IPv4 address after binding.
This is the code I have so far (placed after binding to... | Example code from Microsoft
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
// Link with Iphlpapi.lib
#pragma comment(lib,"IPHLPAPI.lib")
#pragma comment(lib,"Ws2_32.lib")
const unsigned int WORKING_BUFFER_SIZE = 15 * 10... |
69,909,424 | 69,909,694 | C++ Template: Kind of like infinite recursion but not really | I have the following code:
#include <cstdint>
template <uint32_t test_value, uint32_t ...Vn>
struct is_prime_tmpl;
template <uint32_t test_value>
struct is_prime_tmpl<test_value> {
static constexpr bool value = true;
};
template <uint32_t test_value, uint32_t V1, uint32_t ...Vn>
struct is_prime_tmpl<test_value, ... | Your ternary operator does not stop recursion, which makes your code fall into infinite recursion. You should use if constexpr to prevent recursion when the argument does not meet the condition.
Something like this:
template <uint32_t max_target, uint32_t test_value, uint32_t ...Vn>
struct generate_prime_helper_tmpl<ma... |
69,909,847 | 69,911,589 | Logic for the string to not fall in the middle of another string | I need help in figuring out the logic or code to when I want my string not to fall in the middle of another string. For example my given word is "Birthday!" and the other string to look for it is "Happy Birthday Scott". It's going to return a false value because it's missing an exclamation point. Here is the code that ... | Here is a super simple program for you to look at.
All you have to do for this problem is create your strings using std::string, determine if they are inside the big string using find(), and lastly check if it was found using string::npos.
#include <iostream>
#include <string>
using namespace std;
int main()
{
st... |
69,909,851 | 69,910,199 | How to use it->empty() in an iterator | I want to use an iterator as a condition of a for loop, but when I define it, it->empty() always reports an error. I don’t know where the error is. When I change it to (*it).empty() It will also report an error later
The error is: the expression must contain a pointer type to the class, but it has type "char *"
#includ... | The problem is that you are trying to access a member function called empty through a non-class type object(a char type object in this case). You can change your code to look like below:
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
std::vector<std::string> vec = {"some", "string", "... |
69,910,819 | 69,911,669 | Binary addition using char array | #include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
int main(){
char Pbuf8[9]={"01100000"};
char Mbuf4[10]={"01110000"};
int num=0;
char Snum[9]="0";
int carry=0;
for(int c=7;c>=0;c--){
//Convert a string to a number and add
num=(Pbuf8[c]-'0')+(... | You have 3 minor bugs in your code.
Snum must be initialized with everything being 0. Otherwise it will just be filled with one 0 and the lower part of the addition will not be visible
You need to convert "num" back to a number, before adding it back to the char array. So, num+'0'
Delete the "sprintf", It will overwri... |
69,911,010 | 69,912,440 | ReadFile only returns after newline | I'm trying to read every character pressed in my console in realtime.
I'm using ReadFile to read from stdin, but it seems to only complete the read operation after a newline (when I press enter).
Here is my code:
char buf[1] = { 0 };
HANDLE stdInHandle = GetStdHandle(STD_INPUT_HANDLE), stdOutHandle = GetStdHand... | As I've mentioned in a comment you could use SetConsoleMode to disable line-buffering:
#include <windows.h>
int main()
{
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
// Get the current console mode
DWORD mode;
GetConsoleMode(hInput, &mode);
... |
69,911,242 | 69,911,490 | SdFat write floats to file ESP32 | I Need to write float or Strings value into the SDVolume Cache in SDFAT library, I'm using ESP32 with SdCard module.
uint8_t* pCache = (uint8_t*)sd.vol()->cacheClear();
memset(pCache, ' ', 512);
for (uint16_t i = 0; i < 512; i += 4) {
pCache[i + 0] = 'r'; // I Need to write a Float value or String into t... | First:
// I Need to write a Float value or String into this cell
makes no sense - that "cell" is a single character, like 'e'. How do you write a full float value into a single character?
You probably just want to fill pCache with a string representation of your float. So do that!
We've got all C++ at our disposal, ... |
69,911,364 | 69,925,141 | What's the difference in results of cv::boundingRect() and cv::minAreaRect()? | I tried reading the docs but couldn't understand the difference.
I was expecting the same results when the target is a 3x3 square,
but I get 3x3 with cv::boundingRect() and 2x2 with cv::minAreaRect().
I'm using OpenCV 4.4.
Here is a sample code.
char data[25] = {
0, 0, 0, 0, 0,
0, 255, 255, 255, 0,
0, 255, ... | OpenCV has inconsistencies and sloppy/no "definitions", especially in those old parts.
Some of that stems from the reluctance to return fractional values to express that a line (contour) should be between pixels. Some more stems from not being clear on whether the "bottom right" of a rectangle is the last pixel in it, ... |
69,911,367 | 69,912,180 | What is the use of a test fixture in google test? | Google recommends to use the text fixture constructor/destructor when possible instead of SetUp()/TearDown() (https://google.github.io/googletest/faq.html#CtorVsSetUp). Assuming I do it this way, what is the use of even using a test fixture? How are the following different, and what is the advantage of the first?
TEST_... | The advantages are visible when there are more than one TEST/TEST_F.
Compare:
TEST(MyTest, shallX)
{
MyTest test;
test.setUpX();
test.objectUnderTest.doX();
}
TEST(MyTest, shallY)
{
OtherTest test;
test.setUpY();
test.objectUnderTest.doY();
}
with
TEST_F(MyTest, shallX)
{
setUpX();
objectUnd... |
69,911,406 | 69,911,528 | Type-pun uint64_t as two uint32_t in C++20 | This code to read a uint64_t as two uint32_t is UB due to the strict aliasing rule:
uint64_t v;
uint32_t lower = reinterpret_cast<uint32_t*>(&v)[0];
uint32_t upper = reinterpret_cast<uint32_t*>(&v)[1];
Likewise, this code to write the upper and lower part of an uint64_t is UB due to the same reason:
uint64_t v;
uint32... | Using std::bit_cast:
Try it online!
#include <bit>
#include <array>
#include <cstdint>
#include <iostream>
int main() {
uint64_t x = 0x12345678'87654321ULL;
// Convert one u64 -> two u32
auto v = std::bit_cast<std::array<uint32_t, 2>>(x);
std::cout << std::hex << v[0] << " " << v[1] << std::endl;
/... |
69,911,628 | 69,917,424 | Getting REG_DWORD from windows registry as a wstring | I am working on a test which should check the registry value. My goal is to take 3 windows registry variables. I am using the modified solution from this LINK. The issue is that when I try to get the value which is REG_DWORD it just prints empty brackets. When I try to use it on REG_SZ it works perfectly fine. For now ... | if (type != REG_SZ && type != REG_DWORD) ...
You just have to treat REG_SZ and REG_DWORD differently.
Also add an extra +1 for the null terminator to be safe.
wstring ReadRegValue(HKEY root, wstring key, wstring name)
{
HKEY hKey;
if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
... |
69,911,849 | 69,912,024 | c++ map threadsafe behavior through iterator | My need is just like below:
One thread (named thread 1)just keeps inserting pairs into the common map.
And the other thread (named thread 2)keeps getting the element at the begin position(no matter if it is still the begin while other thread insert an element at the begin position) and do some operation to the element ... | It's not thread safe if the underlying map is std::unordered_map. With unordered_map insert may invalidate iterators (if rehasing occurs).
With std::map iterators aren't invalidated on insert so I think the code would be ok.
|
69,912,336 | 69,912,356 | Creating a vector with n elements in a struct | If I just write this code:
std::vector<int> vec(24, 3);
It'll create a vector called vec with 24 elements all equal to 3.
But if I have a struct:
struct Day
{
std::vector<int> days(24, 3);
};
And try to do the exact same thing it doesn't work, why is this?
| Syntax would be:
struct Day
{
vector<int> days = vector<int>(24, 3);
};
You cannot call constructor with () syntax there (to avoid vexing parse) (but can with {}or = /*...*/).
|
69,912,392 | 69,912,451 | C++ move constructor for a class with string member | I've wrote a class with following code:
class Test {
public:
...
Test( const Test &&that ) : i(that.i), s(std::move(that.s)) {
cout << "move contructor." << endl;
}
...
private:
int i;
std::string s;
};
if I disassemble the generated code I see:
.type Test::Test(Test const&&), @functi... | Rvalue references to const types aren't very useful. They say that code can steal from the object, but must do so without changing its value?
Since std::string doesn't have a string(const string&&) move constructor, overload resolution can only use the string(const string&) copy constructor.
A normal move constructor d... |
69,912,402 | 69,912,466 | Using a variable to define other variable before taking it as input | In the below code I defined both n and k initially and then if I define n as k/2 after I take k as input using cin, the code is successful but instead of this if I define n=k/2 before cin function I get an infinite loop as output? Please tell why is defining below or after cin function is affecting the output.
#include... | The order of statements makes a difference:
int k = 2;
int n = k/2;
k = 4;
is different than
int k = 2;
k = 4;
int n = k/2;
In the first case, you get n = 1, and in the second n = 2. This really shouldn't surprise you! You might need to revise your programming basics before dealing with loops if it does :)
Other thin... |
69,912,672 | 69,912,757 | Implicit conversion from char to int for constructors in C++ | class A {
int x;
std::string s;
public:
A(std::string _s): x(0), s(_s) {
std::cout << "\tA(string)\n" ;
}
A(int _x): x(_x), s("") {
std::cout << "\tA(int)\n" ;
}
A(const A &other): x(other.x), s(other.s) {
std::cout << "\tA(A& other)\n" ;
}
};
int main() {
st... |
But C++ standard allows only 1 implicit conversion.
Thats not correct.
From cppreference:
Implicit conversion sequence consists of the following, in this order:
zero or one standard conversion sequence;
zero or one user-defined conversion;
zero or one standard conversion sequence.
From the language point of view,... |
69,913,008 | 69,913,185 | How to center numbers and add list | i made a program for converting Celcius to Fahrenheit and have some troubles with modifying it. I need to all numeration for each line and center numbers in lines. rn my program outputs all to left. Can you please help me with this?
#include <stdio.h>
#include <iostream>
int main(){
// Table header
setlocale(LC_ALL, "... | As I already stated in the comments, 'padded output' may be able to help you.
There's some finetuning to be done here, maybe use sprintf to get the number of characters and prepend/append spaces accordingly, but here you go with a C-Style answer.
setlocale(LC_ALL, "");
system("color F0");
printf("\tTable Output\t");
pr... |
69,913,259 | 69,913,321 | How to make multiple vectors in c++ | Brief :-
How to make multiple vectors ?
We generally make vectors using - vector<int> vector_name;
But any method to make multiple vectors at once ?
| I assume that you're trying to create multiple vector at once and store them. You can use a simple for loop, or use a vector of vectors!
For example:
#include <vector>
// Using a for loop
//#define VECTOR_COUNT 5 (EDIT)
constexpr int VECTOR_COUNT = 5;
std::vector<int> myFiveVectors[VECTOR_COUNT];
for(int i = 0; i < VE... |
69,913,286 | 69,913,455 | Is f(U(*)()) just a specialized version of f(U*)? | When reading a wiki page, I found this sample code
template <class T>
struct is_pointer
{
template <class U>
static char is_ptr(U *); #1
template <class X, class Y>
static char is_ptr(Y X::*);
template <class U>
static char is_ptr(U (*)()); #2
static double is_ptr(...);
static T t;
enum { value = ... |
To me, #2 is just a specialization of #1, so it seems superfluous.
An overload, not a specialization. And yes, it is superfluous. In a template accepting U* for a parameter, U can resolve to an entire function type. It's what makes is_pointer<int(*)(char)>::value be true, despite the fact int(*)(char) will not match ... |
69,913,307 | 69,913,733 | Is it acceptable for all ".h" files import "macros.h" to set verbosity with preprocessing directives | As described in the title, the question is if it considered a good practice to set a code's verbosity by making all ".h" files import one single ".h" file where preprocessing directives are defined? e.g.
macros.h contains
#ifndef VERBOSE
#define VERBOSE true
#endif
then functions1.h could be
#include "../macros/macros... | Littering code with ifs or #if defined is madness and makes a codebase difficult to read and work with.
If you are going to have a common header to define macros, then make the expansion of the macros be what you actually want (instead of making them only be a condition that must be checked.) I'm not a big fan of macr... |
69,913,536 | 70,719,124 | Executing multiple self-avoiding walks, recursively | I have a 3D simple cubic lattice, which I call Grid in my code, with periodic boundary conditions of size 20x20x20 (number are arbitrary). What I want to do is plant multiple polymer chains with a degree of polymerization N (graphs with N nodes) that do no overlap, are self-avoiding.
At the moment, I can plant one poly... | Self-avoiding walks has been studied at least since the 1960s and there's a vast literature on them. Fortunately, the problem you face belong to the simplest ones (walks' length is fixed at a relatively small value).
1
The first thing you should be aware of is that your question is too broad to have a unique answer. Th... |
69,913,808 | 69,915,947 | Semaphore latency faster than expected - why? | Acquisition of a semaphore is done by blocking. According to the internet and clockres, the interrupt frequency / timer interval on Windows shouldn't be under 0.5ms. The program below measures the time between the release and acquisition of a semaphore in different threads. I would not expect this to be faster than 0.5... | Your confusion is coming from the faulty assumption that this comes into play:
According to the internet and clockres, the interrupt frequency / timer interval on Windows shouldn't be under 0.5ms.
Preemptive / timer-based scheduling does not have to be the only opportunity for an OS to assign threads to CPU cores. Ex... |
69,914,394 | 69,914,581 | variadic number of methods as template input parameter | Is it possible to specify a member-function template parameter pack?
Something like this:
template <typename foo, void (foo::*bar)(void) ...>
void application()
{
}
None of my solutions work, and I would like to avoid putting every function that I'm gonna use in a struct.
| The syntax for this is
template <typename C, void (C::*...mfuncs)()>
void application()
{
// ...
}
or with typedef:
template <typename C>
using MemberFunc = void (C::*)();
template <typename C, MemberFunc<C>...mfuncs>
void application();
|
69,914,457 | 69,915,496 | How to handle connect errno in cpp socket programming | I am new to Network Programming and am currently following Beej's Guide to get familiar with this content.
When the book was introducing the getaddrinfo() function, it told me about using gai_strerror() to interpret the error code returned to readable strings. However, the book doesn't cover the error handle method for... | From connect function reference:
If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set to indicate the error.
So, you need the following code:
fprintf(stderr, "connect: %s\n", strerror(errno));
getaddrinfo error handling is kind of exception, most API set errno on error... |
69,914,464 | 69,914,699 | Is it valid to pass use nullptr as a streambuf, to default initialize std::istream? | Is this code standard-compliant?
class MyIstream : std::istream {
MyStreamBuf buf;
public:
MyIstream():
std::istream(nullptr)
{
set_rdbuf(&buf);
}
}
Do I have to create MyDummyStreamBuf, to bypass lack of default istream c-tor?
| https://en.cppreference.com/w/cpp/io/basic_ios/rdbuf
says
Returns the associated stream buffer. If there is no associated stream buffer, returns a null pointer.
Seems to me like it is valid to have an istream (basic_istream/basic_ios) with no stream associated, iow with nullptr.
BTW, I would perhaps use rdbuf(...),... |
69,914,624 | 70,235,898 | How do I properly initialise the input/output arguments for this C++ for openCL kernel? | This is my first time writing OpenCL compute units, so I'm starting small; Here is my basic test kernel:
kernel void test_kernel(global float* in, global float* out)
{
int thread_id = get_global_id(0);
printf("%d", thread_id);
out[thread_id] = in[thread_id] + thread_id;
}
And here is the c++ code that is t... | Your test_kernel looks good.
But on the C++ side, you are missing a few things:
Create the buffers on the device context, so OpenCL knows on the memory of what device it should allocate the memory:
const int N = 5;
cl::Buffer input_buffer(context, CL_MEM_READ_WRITE, N*sizeof(float));
cl::Buffer output_buffer(context, ... |
69,914,635 | 69,914,672 | How do I make an Int in C++ have a limit? | Is there any way I could ensure an int doesn't cross a certain limit? and if it needs to (if the program is adding numbers to the int and it crosses the limit) it goes back to 0 and does the job from there?
| It sounds like you want the modulo operator %.
If the upper limit is limit then
value = value % limit; // Or value %= limit
will "reset" the value back to zero if it's about to pass the limit.
|
69,915,393 | 69,915,510 | How to use class in a different class constructor | I started learning C++ recently and I'm having a problem with an assignment I need to write, my assignment requires that I will create a class constructor that has another variable of a different class type.
my main class is 'person' and I have two other classes 'address and 'job', in my assignment I need to create set... | If all you want is to avoid the default constructor being called, all you have to is use an initializer instead.
person::person(person::person(const char *nameP, const char *phoneNumberP, const char *emailP, address AddressP, job JobP) :
Address(AddressP),
Job(JobP)
{
//Do your stuff
}
This way, the defaul... |
69,915,569 | 70,274,713 | Modern CMake: How do you deal with .dll files on Windows? | I am currently in the process of porting a Linux codebase on Windows. I finally got everything to compile and run, except for one thing: I do not know how to handle .dll files. So far I have been copying them manually because I was working on a single cmake configuration, but this is far from ideal.
So my question is: ... | I have managed to partly solve this problem using CMake 3.21's $<TARGET_RUNTIME_DLLS:tgt> generator expression. However, this will only work if the libraries tgt links with are properly set as SHARED. In theory, this will handle all dependencies. In real life, a lot of package config files were written with UNKNOWN typ... |
69,916,043 | 69,916,135 | C++ Templates for classes | in this code I tried to make a template for my class, and also 2 template functions, one for standard types and one for my template class, but I wanted to see if I can make a template in a template to get a defined function (I don't know if this was the right way to make it). Finally, after I run the code it gives me s... | compl is a c++ keyword (as an alternative for unary operator ~). You used compl as your operator overload parameters.
I didn't know this just a few minutes ago. How did I find out? I pasted your code into godbolt.org and it highlighted the words "compl" as if they were keywords. One Internet search later, they are inde... |
69,916,044 | 69,916,116 | Implementing Factory Function with STL by Replicating Abseil Example | Trying to better understand Tip of the Week #42: Prefer Factory Functions to Initializer Methods by replicating the example using the standard template library. OP provides the example code:
// foo.h
class Foo {
public:
// Factory method: creates and returns a Foo.
// May return null on failure.
static std::uniq... | You still need to define Foo::Foo()
In the header you can do Foo() = default, even in the private section
In the cpp you can do Foo::Foo() = default or Foo::Foo() {}
|
69,916,126 | 69,918,014 | Unaligned address in vtable | I don't know if this is the right place to ask a question like this, so please redirect me if needed.
I am working on an embedded MCU (STM32L5) and am having trouble with some C++ code crashing with a hard fault. After further investigation, I determined that the cause is a branch to an unaligned (i.e., no word aligne... | Thank you to @11c for pointing our about "thumb" instructions. It turns out that my problem is no actually where I think it is and is thus not a compiler issue. What I believed to be an unaligned address was actually normal behavior for the processor.
For reference, see the following:
https://www.embedded.com/introd... |
69,916,244 | 69,916,941 | C++ getting lowest level of a tree | I need to know how many leafs have a tree but with some conditions.
All the children or leafs, will be always on the same level, but it can be the level 1,2,3,4,5 ... I don't know which one will be. So you can't count grandhildren + grandgrandchildren ... they will be at the same level and will be the lower of them, ... | For recursive functions, you start with the assumption that the function, when operating on a node, will return all relevant information about that node. Each node then only needs to inspect its children and itself to decide what to return to the level above it.
If the node has no children, then the result is trivial: ... |
69,916,654 | 70,010,102 | PyImport_Import segmentation fault after reading in TSV with C++ | I am using C++ as a wrapper around a Python module. First, I read in a TSV file, cast it as a numpy array, import my Python module, and then pass the numpy array to Python for further analysis. When I first wrote the program, I was testing everything using a randomly generated array, and it worked well. However, once I... | Note that you don't have to use arrays for storing the information(like double values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input file(data.m... |
69,917,163 | 69,922,574 | How to draw the content of a NavigationView page? | I'm trying to make an UWP app.
I decided to add a NavigationView object, and I created some sections. I read the documentation, but I didn't find out how to draw the content of the page.
There is a Content property, but it sets the content of the page's label in the menu, not the content of the page of a single label ... | Update:
For the setting page, if you are using the default item of the NavigationView by enabling the IsSettingsVisible property, you could check the IsSettingsInvoked value of the NavigationViewItemInvokedEventArgs.
Here is the code that you could refer to
void App3::MainPage::nvSample_ItemInvoked(Windows::UI::Xaml::C... |
69,917,276 | 69,917,801 | Can you delete a specific file before building in Visual Studio 2019/2022 | The project I am working on creates a cache file the first time it is built and ran, but if you make a code change and then re-run the project the file doesn't replace the cache and will instead run the old version of the code. To fix this you have to manually delete the file every time, but I was wondering if there is... | A good idea would be use Visual Studio Build Events.
Read the doc about how to personalize Build Events here.
Using custom Build events you can run command before or after a compiling process.
|
69,917,287 | 69,926,289 | c++20, clang 13.0.0, u8string support | I'm using clang 13.0.0 in a CMAKE-based project, CMAKE_CXX_STANDARD is defined as 20. The following code causes a compilation error (no type named 'u8string' in namespace 'std'):
#include <iostream>
#include <string>
int main() {
#ifdef __cpp_char8_t
std::u8string sss = u8"a"; // <---- this branch is picked up
#e... | Frank's suggestion was correct - the problem is in that Clang was using an older version of libstdc++ and not libc++;
target_compile_options(clang_test PRIVATE -stdlib=libc++)
fixes the issue for me. Though I don't entirely understand why it doesn't work with libstdc++, if you have any idea, please, share it here - I... |
69,917,696 | 69,917,856 | How do I test if a type is within another class exists? | I was thinking that I could test (with C++14) if a class contained a type, I could do this:
#include <type_traits>
struct X {
using some_type = int;
};
struct Y {};
template <typename T, typename = void>
struct has_some_type : std::false_type {};
template <typename C>
struct has_some_type<C, typename C::some_type>... | Why does the has_some_type trait fail?
It's because the deduction of the second template argument only uses the primary template, and doesn't "take hints" from your template specialization.
Think of your partial specialization of has_some_type when you substitute X for C:
template <>
struct has_some_type<X, int> : std:... |
69,918,132 | 69,918,499 | Localization of Special Folder Constants | Does anyone happen to know if there is a complete list of Windows 10 localized folders (like this one just for all folders)?
I am trying to create a custom explorer where the folder should be displayed in the user's native language.
I have already tried to get a complete list of localized folders using the ShellSpecial... | Microsoft does not provide a list because you are not supposed to know, you are supposed to use the special/known folder API. This is to prevent people from hard-coding c:\Program files etc. In older versions of Windows the folders on disk were often localized. In Vista this changed and the real names are English now.
... |
69,918,203 | 69,918,969 | Executing threads taking turns | I have a function that just prints thread id it is called from. I want 2 threads call this function taking turns n times. I had implemented this functionality in pthreads with a condition variable but it is too verbose. What I want program to print as follows:
id: 0
id: 1
id: 0
id: 1
id: 0
id: 1
...
In the end, "id: ... | You can check the thread number against your iteration count and implement the handoff with a barrier.
#include <omp.h>
#include <cstdio>
int main()
{
/* note that it is not pragma omp parallel for, just a parallel block */
# pragma omp parallel num_threads(2)
for(int i = 0; i < 10; ++i) {
if((i & 1) == (omp... |
69,918,360 | 69,918,594 | For loops counting past the limit C++ | I have a really strange problem with for loop. I have to make a program that given the sum of three dice it has to find all possible combinations of those three dice that yield that sum. The problem is that for loops are counting past the limit that they have and I don't have any idea why.
for (k1 = 1; k1 <= 6; k1++) /... | This is happening because you have k2,k3 variables which are allocated higher.
As for loop works until it will end loop when k3=7. So, k3 will save it and after loop when you're getting it, you got 7.
You could use one of proposed approaches by Seth Faulfner or Yksisarvinen.
If you want to save values for future using,... |
69,918,542 | 69,918,685 | Can std::bit_cast be used to cast from std::span<A> to std::span<B> and access as if there was an array of object B? | #include <array>
#include <bit>
#include <span>
struct A {
unsigned int size;
char* buf;
};
struct B {
unsigned long len;
void* data;
};
int main() {
static_assert(sizeof(A) == sizeof(B));
static_assert(alignof(A) == alignof(B));
std::array<A, 10> arrayOfA;
std::span<A> spanOfA{arrayO... | No. While std::span in C++23 will be defined such that it must be trivially copyable, there is no requirement that any particular span<T> has the same layout of span<U>. And even if it did, you'd still be accessing the objects of type A through a glvalue of type B, which violates strict aliasing if A and B aren't allow... |
69,918,587 | 69,919,210 | I am getting the warning for a piece of code, but the c++ book by bjarne stroustrup is saying it should be an error. what is right here? | As per book The C++ Programming Language, 4th Edition -
In C and in older C++ code, you could assign a string literal to a
non-const char*:
void f()
{
char* p = "Plato"; // error, but accepted in pre-C++11-standard code
p[4] = 'e'; // error : assignment to const
}
It would obviously be unsafe to accept that a... | The GCC compiler is somewhat permissive by default and allows some extension such as implicitly converting away the constness of a string.
Most likely this extension was added to keep compatibility with C.
To disable those extensions, simply add the --pedantic-errors flag that will make the compiler refuse invalid code... |
69,919,338 | 69,920,625 | LibAV FFmpeg C++ av_find_input_format("dshow") returning nullptr | I'm trying to use DirectShow devices with FFmpeg in a C++ program. I'm using DLLs built with vcpkg using the command .\vcpkg install ffmpeg[nvcodec]:x64-windows. The vcpkg log shows Enabled indevs: dshow
av_find_input_format is returning nullptr for me (no "dshow" devices found).
If I query the downloaded FFmpeg execut... | You have to call avdevice_register_all() before av_find_input_format("dshow").
The following code returns a valid pointer:
avdevice_register_all();
AVInputFormat* inFormat = av_find_input_format("dshow");
I don't know much about the subject, but I guess avdevice_register_all() expands the list of available formats.
|
69,919,768 | 69,923,791 | How to get back to project after adding a header file in Visual Studio | I have added a header file for a project I am working on and I can't figure out how to get out of the header file and back to where I code. Am I just being stupid?
| Take it easy, you only need to copy the header file you want to add to the project file and you can use #include" "to call the header file. In my example, I copied the Header.h file to the project file, and then Use #include"Header.h" in the .cpp file, which can use the content in the header file.
|
69,919,780 | 69,919,949 | Why rebind<U>::other are deprecated in C++17 and removed in C++20? | I know that it deprecated and removed only in std::allocator. And I can implement it on my own allocators. But why it is deprecated?
| rebind was a clunky, pre-C++11 way of taking an allocator type for T and converting it into an allocator type for U. I say "pre-C++11" because C++11 gave us a much more convenient way to do it: template aliases.
allocator_traits template has a member template alias rebind<U> that computes Allocator<U> for the allocator... |
69,919,801 | 69,919,936 | Read Input of different data types in one line C++ | The program I'm working on requires a user to input something like i v or r v, where i means insert, r means remove, and v would be an integer to be inserted or removed.
How can I read the input and separate it into two variables, one for the operator (as in i or d) and another for the value?
Example:
cout << "Enter de... | If you want to read something into a std::string (which I assume is what decision is), you should use std::getline. Formatted input, like cin >> decision;, will only read one word by default. Any whitespace character will make it stop reading.
if(std::getline(std::cin, decision)) {
// successfully read a line
}
Yo... |
69,920,357 | 69,920,683 | Eigen vector constructor initialization vs comma initialization | For Eigen vectors of a fixed size (eg Eigen::Vector3d, Eigen::Vector4f) there is the option to initialize the vector using the constructor as follows:
Eigen::Vector3d a(0.0, 1.0, 2.0);
However, Eigen also offers a way to use comma initialization of a general Eigen matrix that can be used in this case:
Eigen::Vector3d ... | One advantage of the first version is that it will fail at compile time if you pass the wrong number of arguments, e.g. because you misstyped Vector2d as Vector3d.
Performance-wise, the compiler is able to optimize both the same. Checked it with GCC.
|
69,921,199 | 69,923,873 | Is it possible to determine how many messages are in a POSIX message queue? | I am working with POSIX running on a RHEL machine. Is there a way to check the number of messages that are remaining in a message queue (System V Preferably)?
The purpose of this is simply a desire to know which queues have the most messages at a given time so that I can make a "managing" thread receive the messages in... | You said in comments that you are using msgget() to create the message queue. In that case, you can use msgctl() to get the number of messages in the queue, via the returned msqid_ds::msg_qnum struct field.
|
69,921,481 | 69,921,564 | Code to take value from file and print average, max and min does not work | I want to take a large number of different numbers from a file and give back the Average, Max, and Min values to the command line. I came so far, just to loop over the code, not further. I have tried many ways but nothing is working. Can you please guide me?
fstream my_file ("values.txt");
vector<int> nums;
double inpu... | Your code looks OK, except for you need to accumulate after you populate your vector:
fstream my_file ("values.txt");
vector<int> nums;
double input;
while (my_file >> input )
{
nums.push_back(input);
}
double average_value = accumulate(nums.begin(), nums.end(), 0) / nums.size();
|
69,921,650 | 69,922,030 | Extraction Operator reaching EOF on istringstream, behavioral change with int/char/string | So I am doing some simple file I/O in c++ and I notice this behaviour, not sure if I am forgetting something about the extraction operator and chars
Note that the file format in Unix.
ifstream infile("test.txt");
string line;
while(getline(infile, line)){
istringstream iss(line);
**<type>** a;
for(...){
... | getline has extracted and discarded the newline, so line contains 100 100 100, not 100 100 100$, where $ is representing the newline. This means reading all three tokens from the line with a stringstream and the >> operator may reach the EOF and produce the FAIL message.
iss >> a; when a is an int or a string will skip... |
69,921,670 | 69,921,703 | patsubst in GNU make returns nothing | I am trying to have my cpp source files and my object files in separate directories, so I'm trying to use Make's patsubst to replace the paths. After nothing was compiling, I made a phony target to simply print out the relevant variables and I discovered that patsubst was returning nothing. This doesn't make a lot of s... | Like (virtually) all programming languages, makefiles are case-sensitive. $(FOO) is not the same as $(foo), and $(PATSUBST ...) is not the same as $(patsubst ...).
In fact, $(PATSUBST ...) is nothing and expands to the empty string.
|
69,922,029 | 69,922,102 | How can a array provide storage? | In C++ draft The first paragraph is talking about situations where an array provides storage:
If a complete object is created ([expr.new]) in storage associated
with another object e of type “array of N unsigned char” or of type
“array of N std::byte” ([cstddef.syn]), that array provides storage
for the created obje... |
In these cases array is refering to an unsigned char C[1] or to std::array?
"Array" refers to arrays such as T[N].
"Array" doesn't refer to std::array. std::array isn't an array, but rather it is a class template. std::array may contain an array as a member.
array (with formatting that signifies code) refers to std:... |
69,922,229 | 69,949,698 | C++ compiler error MDM2009 Duplicate type found processing metadata file referencing 2 Windows Component Libraries that both reference another library | My solution structure looks like this:
The compiler complains that it finds duplicate types (of every public interface/class) in WCL1.winmd b/c that winmd file already exists in WCL4's bin directory.
One problem is that I know absolutely nothing about C++ and the link offered in the Answer to this question provides a C... | Well....it's not perfect but this is how I got around the problem...Add the following line to each ProjectReference in each Component .csproj file:
I'm not sure what the intention of this particular Xml element was, but by setting Private=false, the compiler doesn't copy the InterfaceDefinitionComponent.winmd file int... |
69,922,431 | 69,922,469 | Copy temporary buffer to out buffer | In C++, how do I copy a temporary buffer (buffer) to out buffer (outBuffer) using strncpy?
void writeSensorStatus(SensorStatus& data, char* outBuffer[256])
{
// create temporary buffer
char buffer[256];
const size_t capacity = JSON_OBJECT_SIZE(3);
StaticJsonDocument<capacity> doc;
serializeJson(data, buff... | void writeSensorStatus(SensorStatus& data, char* outBuffer[256])
When char* outBuffer[256] is passed as a function parameter, it decays to a pointer to a pointer to char, not a string.
Change this to:
void writeSensorStatus(SensorStatus& data, char* outBuffer)
But this will affect sizeof(outBuffer), so you can use wh... |
69,922,638 | 69,922,709 | Conversion from `const char[]` to non-scalar type requested | I'm trying to make a class that wraps a pointer around another type. With all of the extraneous bits removed, it looks like this:
template<typename T>
class field {
std::unique_ptr<T> t_;
public:
field() : t_(nullptr) {}
field(const T &t) : t_(std::make_unique<T>(t)) {}
field<T> &operator=(const T &t... | The problem is that two class-type conversions are required:
const char[6] to std::string
std::string to field<std::string>.
There is a rule that implicit conversion can have at most one class-type conversion (the official term is "user-defined" conversion although this includes class types that are part of the stand... |
69,922,718 | 69,922,787 | How to get a field object using its name in proto3 | I am migrating schemas from proto2 to proto3 syntax. I want to eliminate extensions as they are not supported. Is it possible to get an object using a field name in proto3, similar to what MutableExtension does in proto2.
For example,
Schema in proto2 syntax
message Foo {
message Bar {
unint32 a = 1;
}
extend... | It's not clear why you need this but what you are asking for is kinda feasible.
Foo::b is a garden variety member function, which means that &Foo::b is a regular pointer-to-member-function.
So you can use it as such using the regular c++ syntax for these entities:
auto b_ref = &Foo::b;
Foo::Bar b_val = (foo.*b_ref)();... |
69,923,184 | 69,924,659 | C++ Overloading the plus operator to add an element to an object | Constructor for object
Set<T>::Set() {
buckets = new forward_list<T>[9];
numBuck = 9;
numElem = 0;
maxLoad = 9;
}
Overloading of plus operator
Set<T>::operator+(T elem){
Set<T> res;
return res;
}
I don't quite know where to begin with this. This overloaded operator add its parameter elem to a ... | You can just make a copy function in the set, and use the Add function inside the overload. Demo code:
Set<T>::operator+(T elem)
{
Set<T> result;
result.Copy(*this);
result.Add(elem);
return result;
}
NOTE: Or you can follow @jxh's answer and use the default copy constructor. I would make a Copy functi... |
69,923,609 | 69,923,677 | Please help me to know what is happening in this code | string kthDistinct(vector<string>& arr, int k) {
unordered_map<string, int> m;
for (auto &s : arr)
++m[s];
//Frome here
for (auto &s : arr)
if (m[s] == 1 && --k == 0)
return s;
return "";
//to here
}
Especially in this part
for (auto &s : arr)
if (m[s] == 1 && --k == 0)
ret... | That block of code is a bit on the dense side. If we rewrite the same logic in a more verbose manner, we get:
for (auto &s : arr) {
if (m[s] == 1) {
k -= 1;
if (k == 0) {
return s;
}
}
}
return string{""};
Since m contains the number of time a string appears within arr, we can interpret this as:... |
69,924,241 | 69,924,289 | Move a std::map vs move all the elements of a std::map | std::map<int, Obj> mp;
// insert elements into mp
// case 1
std::map<int, Obj> mp2;
mp2 = std::move(mp);
// case 2
std::map<int, Obj> mp3;
std::move(std::begin(mp), std::end(mp), std::inserter(mp3, std::end(mp3));
I am confused by the two cases. Are they exactly the same?
| No, they are not the same.
Case 1 moves the content of the whole map at once. The map's internal pointer(s) are "moved" to mp2 - none of the pairs in the map are affected.
Case 2 moves the individual pair's in the map, one by one. Note that map Key s are const so they can't be moved but will instead be copied. mp will... |
69,924,357 | 69,924,519 | assigning an unsigned value to integer data type | I wrote code:
int a = -1U;
cout << a;
Why the output is -1 not 2^w-1?
As in the case of:
long long a = -1U;
cout << a;
The output comes out as
4294967295
| -1U is the negation of 1U. As an unsigned cannot have a negative value the result is incremented by (UINT_MAX + 1). Result UINT_MAX is 4294967295 on OP's machine.
In both of OP's cases, code is initializing a signed integer variable with 4294967295u.
int a = -1U;
Why the output is -1 not 2^w-1?
2w - 1 (w being th... |
69,924,835 | 69,924,894 | Finding the size of datatypes in C ++ | I tried to write a program like this
#include<iostream>
using namespace std;
int main(){
int a ;//declaration
a = 12 ;//initialization
cout<<"size of int"<<size of (a)<<endl;
return 0;
}
and the output came like this
datatypes.cpp: In function 'int main()':
datatypes.cpp:8:26: error: 'size' was not d... | There is no size of () function/operator in C++, there is only sizeof. C++ doesn't allow names to have spaces.
Note: sizeof is an operator, not a function.
You should change this to:
#include<iostream>
// using namespace std; is bad
int main(){
int a;
a = 12;
// sizeof is an operator, so you can do sizeof ... |
69,925,214 | 69,952,288 | I cannot display the linked list in c++ | I have a problem, I have created a new node.
And then I created a new node, to insert at beginning and show its display.
And then I created another node to insert it at the end but I cannot display it in the display function.
Can anyone tell me what's the issue here?
The display literally doesn't show up for the final ... | Your code is producing segmentation fault, look at these lines of code:
while (location != NULL) {
location = location -> link;
}
location -> link = temp;
location = temp;
you are running the loop until location is null and then assigning null -> link = temp (as location is already null) this is what is causing a se... |
69,925,454 | 69,931,862 | Bespoke C++ Windows app crashing and producing an empty dmp file | We have an in-house c++ app that we are running via task scheduler. We are attempting to trace an issue with the app which causes a crash, a windows event and we would usually look for the .dmp file to enable us to track the issue in visual studio.
However, these windows dump files [appname. dmp] is zero bytes.
Is the... | MSDN notes one very important restriction: writing a minidump from inside a just-crashed process is not reliable. It's not clear from your question whether you're using a separate process to write the dumps ("redacted.exe"?), so this is definitely a possible cause.
|
69,925,923 | 69,956,878 | How to write a custom exception class derived from std::invalid_argument? | How should I write an efficient exception class to show the error that can be prevented by fixing the source code mistakes before run-time?
This is the reason I chose std::invalid_argument.
My exception class(not working, obviously):
class Foo_Exception : public std::invalid_argument
{
private:
std::string Exceptio... | I solved this problem based on the feedback that I received from others through comments and answers. So I decided to leave my own answer/solution here for future readers.
Below can be seen what I came up with after much thought and research. This solution is fairly simple and readable.
Here is the exception class inte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.