question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
63,203,401 | 63,203,494 | Extract words from a file and put them into a `std::vector` of `std::array<string,4>` | The following is the file(ka.txt) from which I want to read lines :-
ASD|BSD|CSdsa|ood
fmads|aok|pdski
kdijf|okmdsomf|opkasd|okd
asdas
kamkd|aoda|kked|ok
The following is the code that I've written to put this data into a vector of std::array<std::string, 4>.
#include <iostream>
#include <string>
#include <vector>
#in... | This is because the array istd is used without initializing, so data from previous lines remains when no data is read there.
std::array<std::string, 4> istd;
should be after
while(std::getline(file, *line)){
|
63,203,474 | 63,203,529 | Why use a non-type parameter in C++? | I was reading the documentation for the array object in C++ here: https://en.cppreference.com/w/cpp/container/array and I saw that the template header was
template<
class T,
std::size_t N
> struct array;
Why is N passed as a non-type parameter rather than the struct having a constructor that takes a size as a ... | Non-type template parameters are consumed at compile time, and instantiating a template with a unique value creates a new type or function. This information can then be used for "configuration" that is impossible at run time. This is somewhat horizontal to a template type - a class template parameter T achieves reusabi... |
63,203,564 | 63,204,403 | Access Qt GUI objects globally | I am trying to create a source and header file with common functions that I can use in all of my projects with the goal of just having to #include "functions.h" to make them work.
The problem is that I do not know how to make the GUI objects for my app accessible. Here is what I have:
myapp.h
#ifndef myapp_H
#define my... | I have found the solution. In functions.h, I was doing void log(QTextBrowser& textBox, QString message) instead of void log(QTextBrowser* textBox, QString message). It works now.
|
63,203,568 | 63,214,011 | C++ class override for const and non-const reference member | So I'm making a bitmask class that stores a reference to an std::byte as a member and the index of the individual bit to allow accessing the value of that bit and also assigning to that bit. I also want it to be possible for the value of the std::byte passed to optionally be a const, and if it is a const, I want the cl... | So, despite there being some really nice answers here, I didn't find any of them particularly elegant, so I decided to delve deeper and solve my own problem. Note that this solution isn't entirely mine, and was originally inspired by @ildjarn 's answer, so props to them as well.
This is how I ended up solving my proble... |
63,203,754 | 63,203,777 | Calculate the offset of the pointer in C++ | I am a c++ novice
After I calculated the pointer of the Player structure, the result was beyond my surprise
struct Player
{
const char* Name = "ab";
uintptr_t Health = 6;
uintptr_t Coins = 3;
} player;
std::cout << &player << std::endl; // 0100C000
uintptr_t* playerBaseAddress = (uintptr_t*)&player;
s... | Like this
uintptr_t playerBaseAddress = (uintptr_t)&player;
In your version you have a pointer, so when you added 4 to your pointer the result was multiplied by the size of the object being pointed at. Clearly on your platform uintptr_t has size 4, so you got 0100C000 + 4*4 which is 0100C010.
This would also work
char... |
63,203,902 | 63,204,963 | Is nodiscard necessary on operators? | Is the [[nodiscard]] attribute necessary on operators? Or is it safe to assume the compiler will emit a warning like it does for most suspiciously discarded things?
E.g. an overloaded operator+, should one apply the attribute? What about special operators like function-cast operators or new operators? When is it pedant... | Let me cite the following paper by N.Josuttis: "[[nodiscard]] in the library" (with some omissions, see the full paper):
C++17 introduced the [[nodiscard]] attribute. The question is, where to apply it now in the standard library. It should be added where:
not using the return value always is a “huge mistake” (e.g. a... |
63,204,053 | 63,204,122 | Why pybind11 converts double to int? | I created .pyd file:
#include <pybind11/pybind11.h>
#include <iostream>
#include <typeinfo>
namespace py = pybind11;
int add(int num) {
float a = 1.0;
for (int i = 0; i <= num; i = i + 1) {
a = (a + i)/a;
}
std::cout << "dll is typing: " << a << '\n';
std::cout << typeid(a).name() ... | This function
int add(int num)
takes an int as parameter and returns an int. The "problem" is not with pybind. Try this to see:
int main() {
auto x = add(42);
std::cout << "return value: " << x << '\n';
std::cout << typeid(x).name() << std::endl;
}
If the function should return a float you have to declare... |
63,204,350 | 63,205,390 | Visual Studio 2019 doesn't display the complete list of class methods | After update to Visual Studio 2019 I had seen the problem.
In context menu(when I write . or -> after class object) with list of class methods I don't see all methods. But I can manually write name of method and it's ok.
For example, std::shared_ptr hasn't method get() in context menu, but I can write of the method man... |
First ensure that your code do compile. If you have errors before in your file (or included headers) like an extra }, IntelliSense might not works.
If you open large solution or do a lot of change, it can take some time before the IntelliSense database get up-to-date.
If you always have the same problem, then make a p... |
63,204,508 | 63,213,972 | UE4: Set texture to material (C++) | I'm new to unreal coding, I want to apply texture to material, but I'm stuck with creating:
UMaterialInterface* Material = CreateDefaultSubobject<UMaterial>(TEXT("MyMaterial"));
UMaterialInstanceDynamic* DynamicMatierial = UMaterialInstanceDynamic::Create(Material, this);
I've got this error message:
NewObject... | After 4 days of searching I've found correct answer to my texture problem in this post:
https://forums.unrealengine.com/development-discussion/c-gameplay-programming/46406-how-to-initialize-umaterial-and-assign-texture-to-it#post466817
|
63,204,558 | 63,259,532 | How to sort an array of vectors in c++? | I have created an array of vectors. After taking the input I have to sort them, I guess I need to use a comparator function but I cannot understand how do I use it.
int main()
{
int n, k;
cin >> n >> k;
vector<long long> times[4];
for (int i = 0; i < n; ++i)
{
ll t, a, b;
ci... | For ascending order,
sort(times.begin(),times.end());
For Descending order,
sort(times.begin(), times.end(), greater<int>());
Another way,
void cmp(ll a, ll b) {
return a < b;
}
// Use the below statement anywhere you want -
sort(times.begin(),times.end(),cmp);
|
63,204,831 | 63,210,266 | Qt visual studio building | I have ms visual studio solution with qt project. When I working from visual studio all works fine. When I try to run *.exe file from building folder I see message that say Qt5Guid.dll(and other dll's) is not found.
What settings need to be changed that QT dll's moves to general building folder ?
| You can find in Qt installation dir application windeployqt.
Run it like this:
windeployqt --debug <path-to-app-binary>
It will deploy all needed Qt files to your application's folder. You can read more about deploying here: https://doc.qt.io/qt-5/windows-deployment.html
Also you can try to add directory of Qt to PAT... |
63,204,959 | 63,204,989 | Move constructor should be called by default | In following case where i have created move ctor in Integer class, i am expecting that it should be called by default on rvalue reference while creating Product object but i am getting call of copy constructor only.
Gcc - 7.5.0 on Ubuntu 18
#include<iostream>
using namespace std;
class Integer
{
int *dInt = nullp... | You need std::move to "propagate" rvalue-reference-ness.
Inside the body of the following function:
void foo(int&& x);
…an expression x is an lvalue int. Not int&&.
References don't really "exist" — even though they are powered by the type system, they are supposed to be treated as aliases (rather than separate entiti... |
63,204,973 | 63,205,136 | Why is no deduction for template parameters only used as return type? | If I do not use tempate parameter (type) in a function argument list -> only as return type, then there is no deduction:
template <typename T>
T zero() { return 0; }
int main()
{
int x = zero();
}
gives:
a.cpp:15:18: error: no matching function for call to ‘zero()’
int x = zero();
^
a.cpp:1... | Generally it is not possible to deduce function based on its return type. But if you use automatic types conversion c++ feature then you could achieve what you need:
template <typename T>
T zero() { return 1; }
template <>
float zero<float>() { return 3.0f; }
struct Zero
{
template<typename T>
operator T()
... |
63,205,847 | 63,206,861 | (C++ & OpenGL) I'm trying to rotate a group of vertices (which it'll simulate a square) in a Batch Renderer, but it's not 100% working :( | I'm trying to rotate an object, or a group of 4 vertices that're inside a Batch Renderer (it's a dynamic one so it can update their verts and indices at any time).
I'm currently using a method called "Rodriguez Matrix" which i learned how to use it thanks to this StackExchange post
And it works really well but the prob... | This is a simple example of how to rotate a rectangle around a point using Translation and Rotation matrices. I hope this help you:
#include <iostream>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
void rotateRectangleAroundSomePoint(glm::vec3 vertices[4], float angle, glm::vec3 rotationCenter, glm::vec3 axis)
{
c... |
63,205,850 | 63,205,877 | This simple code should work but I am getting warning | #include <iostream>
using namespace std;
int *i = new int;
*i = 0;
int &j = *i;
j++;
//cout << *i << endl;
I have a code like that, and I know this syntax is true but it gives warning in Visual Studio Code like this:
quiz2_q8.cpp:5:4: error: expected constructor, destructor, or type conversion before '=' token
*i =... | You can't have arbitrary statements in the global namespace. You need to put it into a function, e.g. like this:
int main() {
int *i = new int;
*i = 0;
int &j = *i;
j++;
}
|
63,205,953 | 63,206,011 | Why can't inner class and outer class have same name? | My question is simple, why a class and its nested class cannot have same name, but namespaces can?
for example:
class Test {
class Test {};
};
is invalid, but
namespace Test {
namespace Test {}
}
is valid
| Class X already has a member named X, referring to itself. This is known as an injected class name. It's then invalid to add another member with the same name.
|
63,206,258 | 63,206,391 | Multiplying using recursive function C++ | I did a recursive function to calculate x*y with x and y are all integers (x and y >= 0). My formula is:
x * y =
0, if x is equal 0
(x >> 1)*(y << 1), if x is an even number
(x >> 1)*(y << 1) + y, if x is an odd number
"<<" and ">>" are Left Shift and Right Shift Bitwise Operator. Here is my c... | Your problem is wit x % 3, what happens if x = 5? you skip it. Here is improved version of your code.
int multiply(int x, int y) {
if (x == 0)
return 0;
else if (x % 2 == 1)
return (multiply(x >> 1, y << 1) + y);
return multiply(x >> 1, y << 1);
}
or maybe even this:
int multiply(int x, in... |
63,206,456 | 63,206,484 | Insertion sort implementation using iterators and vectors | I'm trying to implement insertion sort algorithm using iterators and it doesn't seem to work as I thought... Do you have any ideas of how to implement it?
Also, I can't use code like this one: https://www.geeksforgeeks.org/insertion-sort-using-c-stl/ because I'm intending to make an animation and it will get more compl... | Here's a very elegant implementation of insertion sort using iterators lifted directly from the reference page on rotate:
// insertion sort
for (auto i = v.begin(); i != v.end(); ++i) {
std::rotate(std::upper_bound(v.begin(), i, *i), i, i+1);
}
All you have to do is understand how std::rotate works, and this becom... |
63,206,667 | 63,206,834 | No instance of function template matches the argument list, argument types are: (std::string, CommandLineArgumentTypes) | I have a function template that takes a std::string and an enum value that describes the type of data contained within the string. It converts the string into and returns a std::string, int, unsigned int, or bool depending on the enum value.
template <typename T> T parseInput(std::string &input, CommandLineArgumentType... | I see two problems:
the template argument T isn't deducible from the type of the arguments (input and type).
I understand that your intention is deduce it from the value of the type, but this, simply, doesn't works in C++.
You have to explicit it, calling the function; by example
parseInput<bool>(arg, type);
your ... |
63,206,703 | 63,206,797 | How is #define S64_MIN defined in linux data types? | I am trying to understand the definition of a linux macro S64_MIN used in the following else condition i.e. draw = S64_MIN.
Which exact decimal value is meant here for S64_MIN?
if (weights[i])
{
u = hash(bucket->h.hash, x, ids[i], r);
u &= 0xffff;
ln = crush_ln(u)... | You can look up these macro definitions in Linux source code:
#define U64_MAX ((u64)~0ULL)
#define S64_MAX ((s64)(U64_MAX >> 1))
#define S64_MIN ((s64)(-S64_MAX - 1))
This means:
U64_MAX has all bits set to 1.
Then S64_MAX has all but the highest bit set to 1.
And finally, S64_MIN will have only the high... |
63,206,760 | 63,206,815 | How can I safely overload custom deleter of std::unique_ptr? | I am trying to reduce code duplication while using std::unique_ptr and it's custom deleter.
I have the some containers Foo, Bar which are allocated using one custom allocator, so cannot be freed with delete.
So the current code is:
struct UniqueFooDeleter
{
void operator()(Foo* foo)
{
internal_free(foo);
... | You can make the UniqueInternalDeleter as templated functor and static_assert, if the T is not Foo or bar.
#include <type_traits> // std::is_same_v
template<typename T>
struct UniqueInternalDeleter /* final */
{
static_assert(std::is_same_v<T, Foo> || std::is_same_v<T, Bar>,
" T must be either Foo or Bar");
... |
63,206,882 | 63,207,068 | How to create an array by reading a file in c++ if every line contains an integer? | In C++ I should read a file in which every line contains an integer and transfer every integer into an array. I tried doing count the lines with getline() function. And created array however when I count the lines, it consumes and if I use getline() function again, it won't work. What should I do? Thank you.
ifstream i... | Reset fstream before second while loop
inFile.clear();
inFile.seekg(0, std::ios::beg);
while ( getline( inFile, line )) {
....
|
63,207,012 | 63,207,163 | C++. std::condition_variable and multiple wait-threads | I have some class, with queue of std::function<void()> member and methods Push and Pop.
I want to implement addition method PushAndWaitUntilExecuted. It is easy when you have one consumer-thread(who call Pop) and one producer-thread(who call Push) - just simple std::condition_variable will be enough.
But my applicatio... | More than just a condition variable needs to be introduced here, in order to avoid several different race conditions. A mutex and a job completion flag are also required.
At this point, it becomes cleaner to replace your std::function<void()> with a small class that contains this closure, as well as all the additional ... |
63,207,285 | 63,213,804 | C++ WinAPI - reading and converting values from a file | Am newbie in using WinAPI in C++. Just searched the internet for similar issues but unable to find correct one.
Am trying to read a file, which includes integer values and to save the values to a string Buffer. Then I need to convert the string to int array in order to calculate average values of all array elements.
At... | Here's how you can read integers from a file into a vector. I am assuming that the integers are separated by white space only (i.e. there are no commas or similar characters in the file). If this is not true then the code has to be slightly more complicated (but not much).
// open the file
ifstream File("RandomValues.t... |
63,207,327 | 63,207,537 | how to resolve Error C2440 'initializing': cannot convert from '_Ty' to '_Objty' | I am trying to write an algorithm for finding a subset of a given vector that has a certain requested sum.
I am trying to use the 'meet in the middle' technique as described in 'the competitive programmer's handbook' by Antti Laaksonen. here is my code:
vector<int> subset_with_sum1(vector<int> set, int requested_sum) {... | This issue is on these lines:
vector<int> temp(subsets_a.begin(), subsets_a.end());
temp.insert(temp.end(),subsets_b.begin(), subsets_b.end());
Here temp is of type vector<int>, but subsets_a and subsets_b are of type vector<vector<int>>. Since the value types are int and vector<int> respectively, they don't match, an... |
63,207,598 | 63,208,278 | Building Pybind11 - Test Case will not Run? | I am currently trying to set up Pybind on my Mac. I am following these instructions: https://pybind11.readthedocs.io/en/stable/basics.html.
I have cloned the pybind repo on my computer, created the build directory within that repo, and have ran the test cases (make check -j 4).
Here is my directory layout:
Home/
--... | The file <pybind11/pybind11.h> is not on your include path. You can install it into your machines default include path, or add -I path_to_directory_containing_pybind11 to your compile command.
|
63,207,771 | 63,207,864 | Writing a copy constructor for a class in C++ that has a set containing pointers | Say you had a class in C++ like below:
template<typename T>
class my_class {
public:
private:
std::set<T*> class_set;
int elements_in_set;
}
I'm trying to write a copy constructor for this class, and so far I'm stuck at the following, where I only know how to copy over the integer elements_in_set, but I'm not sure... | Depends. Do you want a shallow or a deep copy?
For a shallow copy (both instances of my_class sharing the same T objects) just copy the set in the same way as the int member.
For a deep copy (the new instances gets its own copy of the T objects) you need to run through the original set, create a new T and insert it int... |
63,207,875 | 63,210,213 | apple cpp breaks macro-parameter pasting | Compile the following test.cpp
# define TopLevelProject X11
#define Concat3(a,b,c) a/**/b/**/c
# define ProjectRulesFile Concat3(<,TopLevelProject,.rules>)
#include ProjectRulesFile
cpp -I. test.cpp
The expected behavior is that an include statement be generated
# 1 "test.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
... | Concat3(a,b,c) a/**/b/**/c is an ancient, pre-standard, long deprecated method of concatenating stuff. It generally doesn't work on anything modern (that is, past 1990 or so). It may work specifically for concatenating header names with some compilers, because that's an implementation-defined area.
6.10.2/4 The method... |
63,208,066 | 63,208,128 | How do I safely convert a double into an integer in C++? | Is there a way to convert a double into an integer without risking any undesired errors in the process? I read in Programming - Principles and Practice Using C++ (a book written by the creator of c++) that doubles cannot be turned into integers, but I've put it to the test, and it converts properly about 80% of the tim... | It it not possible to convert all doubles to integers with no risk of losing data.
First, if the double contains a fractional part (42.9), that fractional part will be lost.
Second, doubles can hold a much larger range of values than most integers, something around 1.7e308, so when you get into the larger values you si... |
63,208,138 | 63,208,167 | Unable to re-access inner menu (while loop and switch) | I have the following reproducible example:
#include <string>
#include <iostream>
using namespace std;
int main()
{
int choice;
bool run = true;
char inner_choice;
bool inner_run = true;
while(run != false)
{
cout << "Pick a selection" << endl;
cout << "1) Case 1" << endl;
... | You executed inner_run = false; when q is entered and after that inner_run is not set to true at anywhere.
This will prevent it from entering choice for the inner menu.
To fix, you should set inner_run to true before the loop like:
inner_run = true; // add this
while(inner_run !=... |
63,208,279 | 63,209,037 | Does GLFWwindow * window still points to valid glfw object? | I Initialize Glfw, create window and set scroll callback:
GLFWwindow * window = glfwCreateWindow (...);
glfwSetScrollCallback(window, GlScrollInput);
I have somewhere else function:
GlScrollInput (GLFWwindow * window, double x, double y){...}
Lets say after first usage I stored this pointer GLFWwindow * window. Is th... | You need to keep track of that yourself. In general, it's impossible for any C++ framework to check whether a raw pointer is still valid.
If the memory a pointer points to is freed, accessing its contents is now undefined behaviour. Any value could be in that section of RAM, thus any check you do will give you a random... |
63,208,314 | 63,208,331 | warning C4715: not all control paths return a value c++ - cant pass a test | I'm having an issue with this code:
The problem is I'm constantly getting warning C4715 despite the fact .exe is running correctly and it gives correct answer to a problem I'm trying to resolve. The warning makes it impossible to pass the task inside the app. Please give me a clue why 'return' used by me in the if sent... | Your solve function won't execute return statement if a == 0 || b == 0 is not true and either one of a >= 2 * b or b >= 2 * a is true.
It seems that the two solve(a, b); in the solve function should be return solve(a, b);.
|
63,208,442 | 63,208,507 | copying std::map with pointer as key | If I have the following C++ class:
template <typename T>
class my_class {
public:
private:
struct assessment {
int mark;
String grade;
} std::map<T*, mark> class_map;
}
If I were doing a deep copy with a copy constructor, how would I ensure that the content of the pointers in the keys are copied over, wh... | Create new T objects by new and T's copy constructor. But keep in mind, that order in map will be lost in copied map.
my_class(my_class const& other) {
auto it = other.class_map.begin();
while (it != other.class_map.end()) {
T* newKey = new T(*it->first);
class_map[newKey] = it->second;
++it;
... |
63,208,476 | 63,208,513 | Visual Studio unable to set conditional expression in breakpoint | How do I set a conditional breakpoint in Visual Studio 2019 (Enterprise or Community Edition) that evaluates using an overloaded operator[] ? I attach a minimal non-working example.
#include <memory>
struct Point3D
{
private:
int* _Coordinates = (int*)malloc(3 * sizeof(int));
public:
int& oper... | The VS debugger won't evaluate overloaded operators. You'll have to do that yourself in the debugger expression. So you should set the conditional breakpoint using point._Coordinates[1].
|
63,208,834 | 63,231,026 | Share scoped variable in OpenMP | I'm working with OpenMP and would like to share variable that's declared inside scoped block between threads. Here's overall idea of what I'm doing:
#pragma omp parallel
{
// ...parallel code...
{
uint8_t* pixels;
int pitch;
#pragma omp barrier
#pragma omp master
{
// SDL vid... | One way to overcome this problem is to use OpenMP tasks. Here is an example:
#pragma omp parallel
{
// ...parallel code...
// May not be needed
#pragma omp barrier
#pragma omp master
{
uint8_t* pixels;
int pitch;
// SDL video code must be run in main thread
SDL_Loc... |
63,208,887 | 63,209,056 | Leaking memory when not freeing internal cells? | My professor wrote the following code:
template <class T>
Set<T>& Set<T>::operator=(const Set<T>& set) {
if (this == &set) return *this;
T* data_temp = new T[set.size];
try {
for (int i = 0; i < size; ++i) {
temp_data[i] = set.data[i];
}
} catch (...) {
delete[] temp_data;
throw;
}
del... | Lets remove some complications from this code. Lets assume T == int and instead of storing many ints we only store one:
int_store& int_store::operator=(const int_store& set)
{
int* temp_data = new int; (1) allocate
try
{
*temp_data = *set.data; (2) assign
}
catch (...)
{
de... |
63,209,146 | 63,209,211 | Python - Unexpected behavior when generating the powerset in range [0, n-1] | I am trying to recursively generate the powerset in the range [0, n - 1] without passing extra parameters to the inner search function.
def powerSet(n):
all_subsets = []
curr_subset = []
def search(c):
if c == n:
all_subsets.append(curr_subset)
else:
search(c + 1)
curr_subset.append(c... | Change
all_subsets.append(curr_subset)
in the original to
all_subsets.append(curr_subset[:])
You need to capture the contents of curr_subset at the time it's being appended. As is, you merely append 8 instances of the same list, which is empty by the time your function ends.
|
63,209,166 | 63,209,633 | c++ : target of instance of std::function returns null pointer | The following code compiled:
#include <iostream>
#include <functional>
typedef void (*f_type) (int a);
void say(int a)
{
std::cout << a << "!" << std::endl;
}
int main()
{
int a=5;
say(a);
std::function<void(int)> fn{say};
f_type fn_pointer = fn.target<void(int)>();
if(fn_pointer)
... | Reproduced it on VS2017, seems like the target method returns a pointer to pointer (as in returning a pointer to the actual function pointer stored in the object), and expecting its template type argument accordingly. Here is a modified example that works:
#include <iostream>
#include <functional>
typedef void(*f_type... |
63,209,256 | 63,209,354 | Printing c++ variables with other variables changes the value | why does the value of counter variable become 0 when it is printed the first time and then when it is printed the second time alone it shows the correct value?
//global counter variable
int counter = 0;
int fibo(int n){
counter++;
if(n<=1)
return n;
else
return fibo(n-1) + fibo(n-2);
}
i... | You're confused about the order things happen. Specifically you are making assumptions about the order of things in your cout << statement which are not justified.
Something like the following is happening
1) The value of `counter` is checked and saved somewhere (the value is zero)
2) `fibo` is called are the result sa... |
63,209,661 | 63,209,863 | boost::allocate_unique yields non-deafult constructible and non-move assignable unique_ptrs | I have a question about allocate_unique from Boost. It looks like that resulting unique_ptrs are quite limited - they cannot be default constructed to nullptr without providing a deleter (even an invalid one), and also, move assignment does not work.
Luckily, move construction does work, so I was able to hack around no... | Polymorphic allocators are stateful, which means they cannot be default-constructed - because they wouldn't know about the memory resource they're supposed to work with.
This is not particular to PMR or unique pointers, it will also crop up when e.g. using Boost Interprocess allocators on a vector - you will always hav... |
63,209,819 | 63,210,395 | Use union to defer member variable construction | I want to defer the construction of my member variable until the constructor's body and I am trying to use union to do that. Until now, it's achieving what I want but I want to ask is there any reason I shouldn't do this?
Example:
#include <iostream>
struct A {
A() {
std::cout << "Construct A" << std::endl;
}
... | One of the reason you should not use the work around is that it does not make sense.
Apply try-catch on hole constructor will work well.
struct C {
A a;
C() try {
} catch (...) {
}
};
|
63,209,879 | 63,210,010 | How do you print the values from an RGBQUAD structure? | I'm trying to take an 100 by 100 square screenshot of the upper left of my screen and then print all the pixel color hexadecimal values to the console. Right now it is just printing blank spaces.
Here's my code:
#include <wingdi.h>
#include <windows.h>
#include <iostream>
using namespace std;
int main(){
HWND de... | Here's a helpful function:
void Print_RGBQUAD(const RGBQUAD& r)
{
std::cout << " " << setw(2) << hex << (unsigned int)(r.rgbRed);
std::cout << " " << setw(2) << hex << (unsigned int)(r.rgbGreen);
std::cout << " " << setw(2) << hex << (unsigned int)(r.rgbBlue);
std::cout << " ";
}
This example shows ... |
63,210,034 | 63,210,918 | Boost Asio Async Connection Race Condition? | I am looking at the Boost Asio Blocking TCP Client timeout example with a special interest on how connection timeouts are implmented. How do we know from the documentation that the callback handler and subsequent checks don't introduce a race condition?
The Asynchronous connection command
boost::asio::async_connect(soc... | The Asio library is gearing up to be standardized as NetworkingTS. This part is indeed the deal:
Handlers are invoked only by a thread that is currently calling any overload of run(), run_one(), run_for(), run_until(), poll() or poll_one() for the io_context
You are correct in concluding that the whole example is 100... |
63,210,100 | 63,210,354 | What are this properties in libjpeg and in libpng? | I'm actually using the libjpeg to read and save JPEG images.
So first what are the possibilities of pixel size (info.output_components;) ?
What are the possibilities of color space (info.out_color_space;) ?
And can a JPEG image have an alpha channel ?
I'm using the libpng too.
So first what is the bit depth (png_get_bi... |
So first what are the possibilities of pixel size (info.output_components;) ?
From the doc
output_components is 1 (a colormap index) when quantizing colors; otherwise it
equals out_color_components. It is the number of JSAMPLE values that will be
emitted per pixel in the output arrays.
int out_color_components; ... |
63,210,543 | 63,210,563 | Why is this function not adding one to an int called number? | Why is this code not adding one to the int numbers?
Forgive me for posting a very easy question, I am new to c++.
The value of numbers seem to be unaffected when appearing in the console.
Am I incorrectly passing the function's argument?
#include <iostream>
int number = 0;
int addOne(int a);
int m... | Function arguments are copied by default, so modifying the copy (in this case a) won't affect the original (in this case number).
To have functions modify caller's variables, you should use reference.
Also note that int addOne(number); in your main function is not a function call but a declaration of a variable addOne ... |
63,210,687 | 63,210,806 | should I use a lock if I am sure that every thread will always write the same value to shared memory? | C++ : I have a vector<bool> , no thread will ever write false to any of the indices . Should I still use a lock ? I don't think it will cause a race condition as all threads are writing the same value .
The functions being accessed by multiple threads looks like :
void setVal(int index)
{
if (boolvec[index] == false... | To get by without a lock you should use a std::vector<atomic_flag_wrapper> where atomic_flag_wrapper wraps a std::atomic_flag similar to the code in this answer.
With std::vector<bool> you must use a lock, the standard explicitly tells you so:
Notwithstanding [res.on.data.races], implementations are required to avoid ... |
63,210,880 | 63,210,972 | Ifstream is opening the file, but doesn't output the lines inside the file | Im new to c++ and i was trying to open a ".txt" file using ifstream. the file im using is called "ola.txt" which literally just contains two lines of text without punctuation just plain and simple text. The code that i wrote is this
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#includ... | You are trying to open the inFile twice. First time during inFile construction, ifstream inFile("C:\\Users\\ruial\\Desktop\\ola.txt"), second time you try to open it again with inFile.open("C:\\Users\\ruial\\Desktop\\ola.txt"), when it's already open, which is erroneous, and flags the stream as no longer good.
3 possib... |
63,210,947 | 63,210,990 | C++: Smart Pointers & Fluent Design Pattern with References | I'm trying to learn C++ after being spoiled with high-level languages for all of my life.
I would like to use the fluent design pattern with a class, but I'm worried that I'm making a mistake somewhere and sacrificing performance.
Say that I have a class Builder, and it has some member properties and methods. All of it... | There's nothing wrong here, but there also isn't any need to allocate the Builder object on the heap. Consider instead:
Builder builder;
builder.doSomething(someVal)
.doAnotherThing(someOtherVal)
.doAFinalThing(someOtherOtherVal);
You could even use a temporary Builder and remove the variable entirely:... |
63,211,172 | 63,212,022 | Automatic size deduction for two-dimensional array | I am trying to make a fixed-size matrix class. The intent is to make it inherit or utilize a std::array of std::array:
template <size_t Rows, size_t Columns, class T=double>
struct Matrix : public std::array<std::array<T, Columns>, Rows> {
};
I would like to provide an initializer that can automatically deduce the si... | The problem is that the compiler can't deduce {} when used as an argument. This works with for initializer_list (for contructors, because of some special rules). But then you are missing the size.
A workaround are built-in arrays:
template <typename T, size_t N>
using Row = const T (&)[N]; // for readability
template ... |
63,211,202 | 63,279,101 | Issue with vcvars32.bat when trying to use cl Visual Studio command for command line build via the system() function in a c++ program | I'm trying to compile a generated cpp file from within another c++ program.
To begin (to see if the cl command works) I'm trying to use the Visual Studio command line build from the c++ program like this:
command("cl");
Since the c++ command prompt isn't a native tools command prompt I first call:
command("C:"/Progr... | I solved the problem, as S.M pointed out, system() opens a new shell between each call.
I resolved it using the operator & and run the vcvars32.bat and the cl command in the same system call as proposed by Paul Sanders.
|
63,211,720 | 63,211,741 | Wrote a program that displays the fibonacci number corresponding to user input, but it starts at zero instead of one? | std::cout << "Input a number: ";
int userParameter{};
std::cin >> userParameter;
int firstNumber{0};
int secondNumber{1};
int sumNumber{firstNumber + secondNumber};
for(int i{1};i <= userParameter;i++)
{
sumNumber = firstNumber + secondNumber;
... | If I was looking to change the first number in the sequence, I'd probably start by looking at the line:
int firstNumber{0};
I suggest you just initialise that value to one rather than zero. That will change your sequence from {0, 1, 1, 2, 3, 5, 8, ...} to {1, 1, 2, 3, 5, 8, 13, ...}.
However, if the problem is actual... |
63,211,737 | 63,211,799 | Sorting a vector of class pointers based on two attributes? | I am trying to sort my vector of class pointers vector <Building*> company. Below is my code
sort(company.begin(), company.end(), [] (Building* lhs, Building* rhs)
{
return (lhs->getCompanyName() > rhs->getCompanyName() && lhs->height() > rhs->height());
});
I am trying to sort based on two attributes in the clas... | If you want to sort first by increasing values of getCompanyName() and then by decreasing values of height(), your predicate needs to be:
sort(company.begin(), company.end(), [] (Building* lhs, Building* rhs)
{
return lhs->getCompanyName() < rhs->getCompanyName() // increasing getCompanyName()
|| (lhs->g... |
63,211,806 | 63,211,827 | Invalid use of member function (did you forget the ‘()’ ?) | I have this error come up, and I cannot fully see why is happening. I am trying to use a template function inside a base class as such:
in .h file
class CylindricalWave {
public:
virtual ~CylindricalWave() {}
virtual double intensity(double r, double z, double t) = 0;
virtual std::complex<double> efield(dou... | Add this line somewhere in GaussianBeam:
using CylindricalWave::efield;
Otherwise, efield member in GaussianBeam hides all members named efield in the base class. And since GaussianBeam::efield is not a template, the compiler assumes that the angle bracket in gauss.efield<Nx, Ny>(X, Y, 0) is the less-than operator.
|
63,212,178 | 63,216,737 | Why does seekp() fail in this case? | I am using this program to modify every vowel in text.txt to become the hashtag ('#')
#include <fstream>
#include <iostream>
int main()
{
std::fstream iofile{ "text.txt", std::ios::in | std::ios::out };
char chChar;
while (iofile.get(chChar))
{
switch (chChar)
{
case 'a':
... | It's a good question! I was able to reproduce your issue using Microsoft Visual Studio Community Edition 2019. However, using Visual Studio Code and g++ 9.3.0, I didn't get the same problem. It seems to be a compiler issue, specifically with Microsoft Visual C++.
The C++ standard refers to the C standard library regard... |
63,212,484 | 63,235,868 | OpenCL race condition with clSetKernelArg | From the Khronos website on the thread safety of clSetKernelArg:
All OpenCL API calls are thread-safe except clSetKernelArg, which is safe to call from any host thread, and is safe to call re-entrantly so long as concurrent calls operate on different cl_kernel objects. However, the behavior of the cl_kernel object is ... |
where kernels can read and write from a single kernel object from multiple threads?
By "kernels" you mean pieces of code executing on GPU, and by "single kernel object" you mean cl_kernel in host code ? Kernels on GPU don't ever see the cl_kernel struct that exists on the host side. I assume you're talking about usin... |
63,213,170 | 63,213,319 | Expected an identifier | I was trying to find the absolute sum of an array.
#include <iostream>
#include <vector>
using namespace std;
int getAbsSum(vector<int> arr) {
int result = 0;
for (int i = 0; i < arr.size(); i++)
{
result += abs(arr[i]);
}
return result;
}
int main() {
cout << getAbsSum([3, 2, -3, -4]... | The meaning of [ ] is not what you convey in your example. [ ] is used to indicate array indices, and it only supports one argument. Hence, the expression 3, 2, -3, -4 in this context means evaluate 3, then evaluate 2, then -3, then -4 and return the result of evaluating -4. See
https://en.cppreference.com/w/cpp/langua... |
63,213,192 | 63,213,259 | User Defined Literals for a String versus for a Hex Value | Regarding this question, why does a a user defined literal for a hex value map to a different string literal operator than a string does? That is, why does the code
std::vector<uint8_t> val1 = 0x229597354972973aabbe7_hexvec;
map to
std::vector<uint8_t> operator"" _hexvec(const char*str)
{
// Handles the form 0xFFa... |
What makes the size_t necessary when both are null terminal strings?
There ain't no rule in C++ that a string literal cannot have NUL characters embedded in it. "Nul\0character" is a valid C++ string literal. And when doing UDL processing, the C++ language wants to make sure that you know which bytes are actually par... |
63,213,417 | 63,213,564 | Acces read violation c++ task scheduler | I'm Trying to delete a scheduled task called MicrosoftInputProcessor but i get:
Unhandled exception thrown: read access violation.
pRootFolder->**** was 0x4D005C.
Any help please?
I think it's because of NULL ptr in CoInitializeSecurity but i dont know what to do.
PS: I'm opening VS c++ as administrator .
#define _WIN3... | You're calling pRootFoolder->DeleteTask after you've Released the object pointed to by pRootFolder. Move your call to pRootFolder->Release() after your loop.
|
63,213,610 | 63,213,727 | Why variable is null in Unreal Engine? | I want to call function, which changes the text inside the widget.
There is a virtual function NativeConstruct, which calls automatically. And it changes text of widget, but I need to call function F1 and send a text to it, which I want to display. But when I call it, the variable Name is nullptr. And by some reason, i... | Your UPROPERTY the Name has not initialized to nullptr in the beginning. Therefore, it could contain any garbage value inside it.
Initialize it to nullptr in the class definition or in the constructor of UAccessWidgetFromCpp(if any). For instance, this will fix the issue
UPROPERTY(BlueprintReadOnly, meta = (BindWidget)... |
63,213,832 | 63,214,328 | ordering in std::set of unique pointers | I have a std::set of unique pointers in a class like std::set<std::unique_ptr<T>> my_set{};, and I want to write a method that produces a sorted vector of the values pointed to by these unique pointers.
Currently I've got:
auto convert() -> std::vector<T> {
auto vec = std::vector<T>();
for (auto... | The set is sorted by the pointer value, not by the values; so you need to sort the result after (note that there may be duplicates because the pointers are to unique instances, but the values pointed to may be equivalent for the order relation on T).
I actually find this design quite confusing... if you care about iden... |
63,213,954 | 63,216,365 | How to serialize a libtorch vector of tuple(std::string, torch::Tensor) using protobuf? | How should I define the ProtoBuf schema so that I can serialize this vector of shape?
std::vector<std::tuple(std::string, torch::Tensor)>
All I could find were simple trivial examples. I have no idea how I should be defining the torch::Tensor or the tuple in the ProtoBuf schema!
| You can use string to represent torch::Tensor in the ProtoBuf schema.
Example:
syntax = "proto3";
package tensor;
message Lookup {
message Tuple {
string key = 1;
string tensor = 2;
}
repeated Tuple tuples = 1;
}
Use torch::save() and torch::load() APIs to convert to/from std::string via... |
63,214,363 | 63,214,382 | Why all pointers in my vector are pointing on the same element? | it seems like I have a fundamental problem in understanding pointers in C++. In my understanding, the following code example should print "53" in the console, but instead it prints "33".
// Example program
#include <iostream>
#include <vector>
int main()
{
std::vector<int*> v;
{
int z = 5;
v.push_back(&z);... | This:
{
int a = 3;
v.push_back(&a);
}
Results in undefined behavior: you are storing the address of a temporary and using it later. This means anything could happen: the program could print "I'm sorry David, I can't do that."
As soon as the scope ends (with }), the lifetime of a ends, and the address it used to o... |
63,214,519 | 63,215,281 | Visual Studio 2019 C++ - incorrectly reporting errors when compiling | I'm using Visual Studio 2019 to make a shared library using C++ and when I try to compile my project a bunch of errors come up that do not appear in the code via red jagged underlines. Some of the errors are actual errors (which has mostly been forgetting to forward-declare classes) but others do not make any sense. I ... |
Is my C++ installation/Visual Studio broken
No, your Visual Studio install is fine. Everything you describe is normal for C++ and IDEs.
When I try to compile my project a bunch of errors come up that do not appear in the code via red jagged underlines. Some of the errors are actual errors (which has mostly been forg... |
63,214,632 | 63,214,788 | How to create right nested loops? |
An array is given for 15 values. Take the absolute values for every three numbers in the array, going one after the other, and calculate the area of a triangle with sides, the values of which correspond to the taken numbers. Create a new array in which to enter the values of the resulting areas. Display all areas on t... | It can be done using a single loop. I think if you reviewed my solution, then you can do it using nested loop.
double ans[10];
for(int i=0, j=0;i<15;i+=3, j++){
double s=(double)(numbers[i]+numbers[i+1]+numbers[i+2])/2;
double area = sqrt(s*(s-numbers[i])*(s-numbers[i+1])*(s-numbers[i+2]));
ans[j]=area;
}
f... |
63,214,662 | 63,214,792 | Can I create Custom Java Array that can be created as type array[size]? | In Cpp++ we can create array as
int arr[10];
I want to do the same in java without this longer
int arr[] = new int[100];
Can Create a custom class that allows this ? or Some other way around?
| Simply the answer is No !
Java is purely object oriented so what your trying to achieve is not possible in java .
|
63,215,062 | 63,229,244 | Floor Value of an element in a Binary Search Tree | So I was reading the book - Data Structures and Algorithms Made Easy by Narasimha Karumanchi and in that the floor Value of a bst snippet is given - Problem 61 in BST Chapter.
The snippet confused me very much and now I just want to know how it is working :
The snippet as Follows :
node* floorValue(node* root, node* p... | It's classic Binary Search algorithm. I always recommend you to understand the problem you posted. If you clear with algorithm you will know how Binary Search actualy works, as well as how Backtrack works using StackTrace of your system/computer memory.
Let's dive into that. :)
if(!root){
return NULL;
}
the above ... |
63,215,160 | 63,215,558 | c++ compile time reference to field in struct | Hi i have an struct like this:
struct float2 {
float a;
float b;
};
now i can access members like this:
float2 f;
f.a = 1;
f.b = 2;
i want to access a and b with other alias as well:
float2 f;
f.a = 1;
f.b = 2;
f.x = 3;
f.y = 4;
f.w = 5;
f.h = 6;
f.width = 7;
f.height = 8;
x, w, width must refer too same memo... | I suggest you that use like this way.
#include <stdio.h>
struct float2 {
union {
float a;
float x;
float w;
float width;
};
union {
float b;
float y;
float h;
float height;
};
};
int main()
{
float2 var1;
var1.x = 10.0;
var1.... |
63,215,205 | 63,215,302 | C++ condition variables vs new threads for vectorization | I have a block of code that goes through a loop. A section of the code operates on a vector of data and I would like to vectorize this operation. The idea is to split the elaboration of the array on multiple threads that will work on subsections of the array. I have to decide between two possibilities. The first one is... | The biggest disadvantage of creating new threads is that thread creation and shutdown is usually quite expensive. Just think of all the things an operating system has to do to get a thread off the ground, compared to what it takes to notify a condition variable.
Note that synchronization is always required, also with t... |
63,215,398 | 63,215,425 | C++ split string function gives unexpected output | std::vector<char*> Split(std::string input) {
std::vector<char*> ret;
std::istringstream f(input);
std::string s;
while (getline(f, s, ' ')) {
ret.push_back((char*)s.c_str());
}
return ret;
}
This function is meant to take a string and put each word into a vector. But say I put ls -l as the string. It ... | Copying pointers do not mean copying what is pointed.
It seems you have to copy the strings.
#include <cstring> // for strlen() and strcpy()
std::vector<char*> Split(std::string input) {
std::vector<char*> ret;
std::istringstream f(input);
std::string s;
while (getline(f, s, ' ')) {
char* buf = new char[st... |
63,215,402 | 63,216,453 | c++ parameter as const T vs const T& | suppose SomeDataStruct is "huge", will a modern compiler produce equivalent and therefore equally efficient code in the following two cases?
1) void fooByValue(const SomeDataStruct data);
2) void fooByReference(const SomeDataStruct& data);
if equivalent, which idiom is "preferable", why?
please note that this ques... |
suppose SomeDataStruct is "huge", will a modern compiler produce equivalent and therefore equally efficient code in the following two cases?
It depends on the compiler, how you defined the object, what is happening to the object in the function. Lets find out what gcc does on x86-64 Linux. Take a look at the followin... |
63,215,796 | 63,215,839 | How do you do bounds checking with std span? | std::vector and pretty much all other containers have a very convenient way of bounds checking: at(). std::span doesn't have that apparently.
Why?
Is there a replacement? Other than rolling out your own at()?
| Pretty clunky but something like this:
using position
template<class Container>
auto& at(Container&& c, std::size_t pos){
if(pos >= c.size())
throw std::out_of_range("out of bounds");
return c[pos];
}
using iterators:
template<class Iterator, class Container>
auto& at(Container&& c, Iterator&& it){... |
63,216,108 | 63,216,791 | A basic example with "constexpr" doesn't compile | I'am learning C++ so I'am currently reading the book "C++ Primer".
I was reading some examples about the "constexpr variables" and I just want to try a basic code that I just wrote but it doesn't compile I don't know why.
This is the code :
#include <iostream>
using namespace std;
int j = 8;
const int *p = &j;
int m... | It seems the fundamental misunderstanding you have is the difference between an object being const vs constexpr. A variable being const means that it's logically const, i.e. the value cannot be changed once it's initialized. That does not mean that the value is known at compile time, which is what constexpr signifies.
... |
63,216,493 | 63,217,236 | How to speed up parsing C++ code using libclang? | I have a project that must be parsed before original compilation. It's needed for reflection purposes. In short I want to check edited .h files for some attributes in the code and gather info about it to generate specific include files.
For example reflectable classes/fields/methods will be marked as META(parameters...... | C++, as a language, is not very amenable to speculative parsing due to type-dependent parsing. For example, the < token might have different meanings depending upon whether it is preceded by a template or not.
However, libclang supports precompiled headers, which let you cache the standard library headers.
|
63,216,947 | 63,217,224 | Hexadecimal in [] operator | I found some article and I saw this:
// Capture vendor string
char vendor[0x20];
memset(vendor, 0, sizeof(vendor));
*reinterpret_cast<int*>(vendor) = data_[0][1];
*reinterpret_cast<int*>(vendor + 4) = data_[0][3];
*reinterpret_cast<int*>(vendor + 8) = data_[0][2];
This line: char vendor[0x20];.
Why threre are hexadec... |
Why threre are hexadecimal
Because the author chose to use hexadecimal. As you can see, 0x20 is quite "round" in hexadecimal, as it has only one non-zero digit.
may I use octal value?
Yes. Where-ever you can use an integer literal, you can use any of the available base representations. Binary, decimal, octal and he... |
63,217,129 | 63,217,497 | The result of an operator that takes an lvalue operand is an lvalue denoting that lvalue operand? | Reading through the Bjarne's CPP book I've encountered such a statement: "Where logically feasible, the result of an operator that takes an lvalue operand is an lvalue denoting that lvalue operand", and I really can't wrap my head around it. These are the examples included with this statement:
void f(int x, int y)
{
... |
x = y returns lvalue referring to left-hand operand.
int* j = x = y, this is erroneous because of invalid types of the operands.
But,
int* j = &(x = y) :
works, as x = y returns l-value so this boils down to int *j = &x (value of x is y)
and similarly, this int& j = x = y also works
Additional links:
For condition... |
63,217,432 | 63,217,576 | Is the Break keyword the most efficent way to exit a for loop? C/C++ | Is break the most efficient way to exit a loop? In the code snippet below, would line A or line B be the more efficient way to exit the loop? Any links to material on how the break instruction works under the hood would be appreciated.
for (int i = 0; i < 10; i++) {
cout << i << endl;
if (i == 3) {
... | Let's compile the following code and look at the assembly:
#include <stdio.h>
int loop_with_break() {
for (int i = 0; i < 10; i ++) {
puts("Hello, world!");
if (i == 3) {
break;
}
}
}
int loop_with_assignment() {
for (int i = 0; i < 10; i ++) {
puts("Hello, worl... |
63,217,482 | 63,217,581 | Pointer typecasting c++ | #include <iostream>
#define print(x) std::cout << x;
#define println(x) std::cout << x << std::endl;
int main() {
int ex[5];
int* ptr = ex;
for (int i = 0; i < 5; i++) {
ex[i] = 2;
}
ex[2] = 3;
*(int*)((char*)ptr + 8) = 4;
println(ex[2]);
}
on line 13 i'm using (char*) and when i ... | It depends on the architecture you use. By definition char is the type that has the size of 1, so sizeof(char) evaluates as 1, but it does not automatically mean that it is 8 bits.
To access the next value, you must add sizeof(int) to the pointer to make your code work independent of the architecture it is used on.
Whe... |
63,217,611 | 63,217,674 | std::set_intersection and iterators | Is it possible to have the output of std::set_intersection or other std::set_* algorithmic functions be added directly to a type std::set?
So far, I can only think of a way to add directly to something that allows std::back_inserter.
#include <set>
#include <algorithm>
#include <vector>
#include <iterator>
#include <io... | Yes, You can use std::inserter, instead of the std::back_inserter like this.
#include <iterator> // std::inserter
std::set<int> s3;
std::set_intersection(s.begin(), s.end(), s2.begin(), s2.end(),
std::inserter(s3, s3.end()));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
63,217,776 | 63,217,865 | Windows Visual C++ 2019 trying to pass preprocessor varible (-D in linux ) error C2143: syntax error: missing ';' before 'constant' | im doing simple port from Linux to windows, now in Linux I pass simple
-DVERSION=1 to be able to get the value in preprocessor macro :
for example :
#define APP_NAME "MyApp " VERSION
in windows when i set the VERSION value in :
Configuration Properties, C/C++, Preprocessor -> Preprocessor Definitions
as :
VERSION=1
... | With
VERSION=1
then VERSION expands to the integer literal 1, which means your statement is as this:
char *message = "MyApp " 1 "\0";
This is not valid, as you can't concatenate string literals with integer literals. For this to work you need to define VERSION as a string literal:
VERSION="1"
As for the APP_NAME ma... |
63,218,170 | 63,218,324 | why am i getting an Erorr here | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
class shape
{
public:
int width;
int height;
data(int w,int h){width=w;height=h;}
};
class Rectangle: public Shape
{
public:
int area ()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int ... | There are several errors:
The C++ is case-sensitive, shape isn't equivalent to Shape identifier. One of them must be the same as the other.
The class variables must be private, protected when the base class is to be derived. Otherwise, it violates the rule of OOP.
The datatype of data() defaults to int but nothing's... |
63,218,303 | 63,218,460 | C++: Implementing a numeric approximation for ln(a) | I want to implement the formula:
#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
int main(){
double a, eps = numeric_limits<double>::epsilon();
cout << "a=";
cin >> a;
double w = sqrt(a), prod = 1 + w;
int n = 1;
do {
w = sqrt(w);
prod *= 1 + w;
... | Initial conditions for the loop are off. Start with
double w = a, prod = 1;
and the program would produce expected results
|
63,218,326 | 63,220,987 | c++ compiling error for interface implementation with template | I am trying to implement interface with template for some class. I have code like this:
file.h
#pragma once;
class MySpecificClass {
std::string data;
unsigned int x;
unsigned int y;
unsigned int z;
public:
MySpecificClass(): data(""), x(0), y(0), z(0) {
}
MySpecificClass(std::string s, un... | The template is not the problem here. Virtual function without a definition is.
The C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined. In your base class you declare a virtual function save. If it were not virtual then it would be OK to leave it without a definition (i... |
63,218,383 | 63,219,220 | Why does my code give me different answers when I initialize a variable compared to when I add a simple value like 0? | Below you have two different codes. The difference between the two is simply for the variable sum, sum was initialized compared to giving sum the value 0 sum =0;
#include <iostream>
using namespace std;
int main(){
//This code will display first ten numbers and get the sum of it
cout << "The natural numbe... | Actually in the first set of code the compiler took a random value of variable sum. In your case I think the compiler took value of of sum as 32766. This value 32766 is "garbage value".
So see in second case you gave sum a initial value hence compiler knows that user has given a value. So accordingly it will perform yo... |
63,218,481 | 63,218,614 | Validity of iterator after insert for std::list and std::vector | Suppose, there are two iterator pointing at different places at different places.
For a list, are they still valid if an item is inserted between them?
If I understood correctly, a std::list object is usually implemented as a doubly-linked list, hence upon an insertion (or a deletion) the the iterators are still valid.... | iterators shows location on memory. Iterator behavior depends on representation of container in memory. As you said, std::list is implemented using linked list. nodes can be anywhere in memory. They are connected with next pointer of previous node. so if you insert an item in between two items, their location on memory... |
63,218,485 | 63,218,679 | What's the deal with overloading virtual functions in C++? | The GCC manual contains the following explanation of the warning option -Woverloaded-virtual:
Warn when a function declaration hides virtual functions from a base class. For example, in:
struct A {
virtual void f();
};
struct B: public A {
void f(int);
};
The A class version of f is hidden in B, and code lik... | Introducing a name that is inherited from an ancestor type causes that name to be hidden in the derived type. This is why b->f(); does not compile.
The warning comes from the declaration of B::f. The compiler is telling you that this new declaration does not overload or override the function inherited from A. It hid... |
63,218,698 | 63,218,818 | Whats this way of implementing a method in c++? | I want to create a game class using C++ SFML library.
I try to use OOP style of coding and I was confused about a code I found on my learning book which is like this:
#include <SFML/Graphics.hpp>
class Game
{
public:
Game();
void run();
private:
void proccessEvent();
void update();
void render();... | It is called member initialiser list. See : https://en.cppreference.com/w/cpp/language/constructor
By default, data members of classes are initialized before object itself. The same constructor implementation can be defined like this :
Game::Game()
{
mWindow = RenderWindow(sf::VideoMode(640, 480), "SFML Application... |
63,219,060 | 63,219,135 | Is there a way to use an overload operator as part of a comparison |
Here is my class
#include <fstream>
#include <cstdlib>
#include <math.h>
#include <iomanip>
#include <iostream>
using namespace std;
class Point {
protected:
int x, y;
Here is the overload operater I want to use it compares the difrence between two points.
double operator-(const Point &def){
re... | Yes, you can directly use operator- that is inherited from Point like this:
bool doIBumpIntoAnotherCircle(Circle anotherCircle){
if (anotherCircle.radius + radius >= *this - anotherCircle)
return true;
return false;
}
Or more simply:
bool doIBumpIntoAnotherCircle(Circle anotherCircle){
return anoth... |
63,219,069 | 63,219,113 | C++ know if a member function is called | How can I know if a method is called, but very early?
For example, I have a struct Foo that has some configurable members:
struct Foo {
int a;
int b;
Foo& setA(int a) {
this->a = a;
return *this;
}
Foo& setB(int b) {
this->b = b;
return *this;
}
};
Now I have a function that returns a Foo... | What you're proposing in your question is physically not possible; it would break causality: You cannot call useFoo if no member functions have been called before returning it and possibly using it, because after you return it you could use some member function.
What you can do is call useFoo from the destructor of Fo... |
63,219,070 | 63,219,444 | Making an object reference null from JNI code | Here is an abstraction of my problem. I want to set an object reference from the java code to null in a JNI function. For example:
// -- java code --
String s="this is a new string";
func(s); //passing the object to the JNI function.
System.out.println(s);
This should print null
Firstly, I am pa... | Java is pass by value. The call func(s) copies the reference s and gives it to func, which cannot change the original. null is not an object; it's a special reference. That means func can't set s to null, because it can't change s, only the object behind it. Just being a native method does not give func magical powers ... |
63,219,156 | 63,219,174 | Why starting for loop at i=1 giving me segmentation fault in this vector problem? | I am trying to create a variable sized array which will help me store values and will allow me to retrieve and print the value as query asks. I actually completed this problem but as I am new to coding part, I just wanted to ask why using for loop starting from i=1 to i<=n gives me segmentation fault?
#include<iostream... | When you declare a vector like this:
vector< vector<int> > a(n);
it has size n. Indexing in c++ (and in fact, most programming languages), starts from 0 and goes to n-1.
If you index into a vector of size n with the index n (as you are doing in your for loop), this is an out of bounds index, and invokes undefined beha... |
63,219,292 | 63,220,984 | Why does &vector_char[0] print all characters? | I have been analyzing code and I came across this:
...
vector <char> buffer (size + 1);
vsnprintf (& buffer [0], buffer.size (), format, args);
printf (& buffer [0]);
...
So I was wondering why it prints all the characters and in the vnsprinft function, the reference to the first element of the vector is passed
| So, as others have mentioned, this is due to the fact that you are not actually passing by reference, you're actually passing the address. This is because the & has different meanings in different contexts.
In a function declaration context, it means passing by reference:
void myFunc(int& i) { // << pass by reference
... |
63,219,353 | 63,219,387 | Generic function that receives different STL containers [C++] | I have a question regarding a C++ code. My task is to create a generic function that receives different STL containers (vector, list, set) and counts the odd numbers in them.
My first try is:
template <typename T>
void countOdd(T x)
{
int count = 0;
for (int i = x.begin(); i < x.size(); i++)
if (x % 2 =... | You have a number of issues. This loop:
for (int i = x.begin(); i < x.size(); i++)
is incorrect. begin() returns an iterator, not an index.
Also this condition:
if (x % 2 == 1)
is incorrect, since x is the range being passed in, not the individual elements.
The simplest way to do this is:
template<typename T>
void co... |
63,219,394 | 63,219,827 | Going from one instance of string.find to the next | Well, this is another classic puzzle... My goal is to take the first letter of each word in a string and put it at the end of that word adding -ay (Pig Latin). I managed to transform the first word. But how do I move on to the next? I consulted different sources, forums but I am still stuck... Any tips? :) Maybe someth... | It's pretty simple:
Just tokenize the string, take each token, save the first char of token in some var, remove the first char and build what you need.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
// build istringstream object from provided text
auto input = istringst... |
63,219,491 | 63,220,464 | Copy constructor + Shallow & deep copy | I wanted to ask that when I don't write any copy constructor explicitly so the compiler automatically generates the copy constructor which performs shallow copy by default right?
So in the main() program when I changed the values of integers a, b and pointer p only the value of p changed and values of a and b remain un... | You've totally got it wrong - The idea of shallow copy. Actually, c++ does not have anything called deep copy built into itself. So, calling something shallow copy is a bit wrong. And just the use of these words shallow copy creates a lot of confusion too.
Now, let me explain, what happens when cpp performs initializat... |
63,219,668 | 63,219,736 | problem with 'std::for_each', does not map function over vector as expected | I'm starting to play with c++ recently, and I'm coming from functional land so you can imagine my relief when I discovered the for_each function and then my frustration when I discovered I can't make it do what I want. What I want to achieve can be done with a simple for loop, but I seem to have developed an allergy. A... | std::for_each applies a function returning void to each of the elements of the collection--since std::stof is a pure function, you're silently performing a no-op. In particular, you are not converting the elements of the vector in place. The correct way to do this is to use std::transform:
std::vector<std::string> numb... |
63,219,820 | 63,220,030 | What should i do to optimize this C++ code? I don't have any idea which statement is taking more execution time | I was to solve one question on hackerrank related to lower bound in C++. My code was able to pass all the test cases which had no time limit but failed in all time bound test cases. You can find the hackerrank question from this link:
https://www.hackerrank.com/challenges/cpp-lower-bound/problem?utm_campaign=social-but... | You have over complicated the solution with unnecessary find() + lower_bound.
Just use lower_bound() to find the element
If found, print yes
If not, print no
auto elementPosition = lower_bound(v.begin(), v.end(), tempElement);
size_t pos = std::distance(v.begin(), elementPosition);
if (v[pos] == tempEleme... |
63,220,233 | 63,231,375 | Strange behaviour of openmp collapse directive | I have the following problem:
In the code below I wait the same amount of iterations, but this is not true. Often I have 45 iterations(expected amount), some times I have 67, some times 23 iterations. How does #pragma omp parallel for collapse(2) works, or maybe I wrongly used #pragma omp critical?
#include <iostream>
... | Your code is not compliant to the OpenMP standard.
Indeed, the initializer int j = i + 1 of the inner loop shall not be dependent of the iterator value of the outer loop. You should collapse the loop yourself (or you can use OpenMP tasks which have a higher overhead).
PS: #pragma omp critical is not needed anymore if y... |
63,220,998 | 63,221,053 | Shifting a vector in C++20 | I'd like to use this new feature from C++20 of shifting a vector to the right std::shift_right.
Something that I'm not sure about is how can I get the last element to the beginning of the vector after shifting?
Like in the example above... Where I'm saving the last element in a temp variable and then after shifting I s... | While you can probably achieve what you want with std::shift_right, the appropriate algorithm to do what you've described is std::rotate, which you can use without c++20 as well:
std::rotate(seq.begin(), seq.end() - 1, seq.end());
Here's a demo.
The reason the shift_right version doesn't work is that you have an i... |
63,221,074 | 63,221,154 | My member function designed to change a particular member data in a class doesn't actually change it | I have started to write a program that makes a drink and calculates the price of it based on the different variables (toppings, size). However, when trying to write a function called setSize, designed to change the size of a particular drink, the bool value which keeps track of the size of the drink stays the same.
Her... | This function is really strange.
void Boba::setSize(bool isLarge) {
isLarge = true; // you set the function parameter to true here, not the class member variable isLarge
updatePrice();
}
use this-> to explicitly tell the compiler which variable to work with:
void Boba::setSize(bool isLarge) {
this->isLarge... |
63,221,209 | 63,221,552 | How do I load values directly into myCircleArry |
Here is my class
#include <fstream>
#include <cstdlib>
#include <math.h>
#include <iomanip>
#include <iostream>
using namespace std;
class Point {
protected:
int x, y;
double operator-(const Point& def)
{
return sqrt(pow((x - def.x), 2.0) + pow((y - def.y), 2.0));
}
};
class Circle : public ... | First off, you should create a constructor that takes arguments.
It should look something like this:
Circle(const Point& pt, int radius)
{
x = pt.x;
y = pt.y;
this->radius = radius;
}
or
Circle(int x, int y, int radius)
{
this->x = x;
this->y = y;
this->radius = radius;
}
Make sure you still h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.