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 |
|---|---|---|---|---|
62,803,727 | 62,803,865 | How do you write and read an abstract class pointer to a file in c++? | I have several classes that all inherit the same interface. These classes are instantiated and saved in interface pointers. For example:
struct Class {
private:
Function* function;
};
I need to save the function to a file, and am wondering if saving the function as (*function), I will need to add an enum or do ins... | The only thing you can do: Make a list of all the function pointers that you would want to store, assign an unchangeable unique number to each, write that number to the file, and upon reading, replace it with the function pointer.
|
62,803,823 | 62,804,431 | Extract the century of a date from a string | My task is to output the current century of a given date. The date can be represented as a string; for example, 19.03.2022.
How can I retrieve the year and century of such strings?
| string date = "19.03.2022";
int century = (date[6] - '0') * 10 + (date[7] - '0');
if(date[8] != '0' || date[9] != '0') century++;
cout<<century<<endl;
Output: 21
Complexity: O(1)
|
62,803,996 | 62,804,352 | C++ Primer 5 ed.1.23 Reading from a file stream | I'm teaching myself C++ by working through C++ Primer 5th edition and I've come up to exercise 1.23 which states: Write a program that reads several transactions and counts how many transactions occur for each ISBN.
I thought about using variables to store the transaction information but in a real scenario this wouldn'... | Something like this using fstream is just a basic idea:
#include <iostream>
#include <fstream>
#include <stdexcept>
std::ifstream file("file_name.txt");
std::string ISBN("99959");
if (!file)
throw std::runtime_error("Open file error");
std::string line; // Or whatever the data is in the file
int count = 0;
while ... |
62,803,998 | 62,804,101 | Make archive file (.a file) on macos from object file (.o) | I want to create my own static library. I've watched tutorials on youtube for Linux (I couldn't find any mac tutorials). The tutorials used the command line tool ar to turn .o files into .a files. I tried doing this: ar rs library.o on mac but it didn't work. How can I do this on a Mac? Thanks.
This is the output:
ar: ... | This should do it:
ar rcs mylibrary.a myobjfile.o [...]
|
62,804,213 | 62,804,295 | How can I return an object using std::min with std::less | I have the following code where I need to return the object having a specific smallest element. I need to use std::greater and std::less. The code is working but this is not what I want. I want to have x3 to have both x and y of the structures having the smallest x.
#include <iostream>
using namespace std;
struct X ... | You can write the function like this:
template<typename T>
static X getValue(const X&x1,const X&x2) {
return T{}(x1.x, x2.x) ? x1 : x2;
}
Here's a demo.
Alternatively, you could pass the comparison object as an argument:
template<typename T>
static X getValue(const X&x1,const X&x2, T comp) {
return comp(x1.x, x... |
62,804,616 | 62,806,587 | Cross Compiling from Linux-Windows, stdio has undefined references (to __imp___acrt_iob_func) | As the title says, I've been trying to cross compile a fairly large project with quite a few dependencies (both static and dynamic libraries). I've cross compiled every dependency successfully using MinGW-w64, set the include & library search paths to their MinGW counterparts (/usr/x86_64-w64-mingw32/lib & include), an... | So, I apt-get purge'd mingw-w64 and mingw-w64-common, reinstalled just mingw-w64, and now it's working...
This might have something to do with the fact that I followed the issue that Richard Critten commented with (thanks!), which led me to try downloading and manually copy/pasting headers and CRT (mingw-w64-x86_64-hea... |
62,804,621 | 62,809,534 | How to Close Console Window with code in Visual studios C++ | I've built a small Menu system. and I'm looking to add an option to Close the console window that pops up when code runs but I haven't found anything to do so yet. Can anyone help?
This is the code I have so far following what Paddy said in the comments bellow
void Menu::Output() {
HWND WINAPI GetConsoleWindow(void... | I suggest that you could use SendMessage() to close window.
HWND hwnd= GetConsoleWindow();
int number;
cin >> number;
switch (number)
{
//....
case 5:
SendMessage(hwnd, WM_CLOSE, 0, 0);
//FreeConsole();
break;
}
Also, you could refer to this link.
|
62,805,047 | 62,805,164 | to understanding this line of C++ pointers code | I am reading an example code about pointers but I can't understand why the developer write this:
If DD is the class we defined, why is this working?
DD *g = 0,h(ARGUMENTS_HERE);
but this isn't working (without zero ,)?
DD *g = h(ARGUMENTS_HERE);
| Given the minimal information provided, if I had to guess, I'd say the first line works because g is being defined as a pointer to DD and initialized to be 0, or null. The comma afterwords means that h(with arguments) is defined as a function (with arguments) that returns a DD object (not a pointer to the object, the a... |
62,805,479 | 62,805,503 | muQueue.front() gives const instance even though I didn't mark it const | I'm having a problem in this program:
#include <iostream>
#include <string>
#include <queue>
#include <functional>
int main()
{
class Buffer{
public:
void consumed(size_t s) {
//alter something inside Buffer
}
};
std::queue<Buffer> bufferFifo;
typedef std::function<v... | By default, any variables captured by value in a lambda are const.
If you mark the lambda as mutable then the captured b is no longer const:
tasks.emplace( [b] () mutable {
b.consumed(0);
});
Here's a demo.
Also, variables captured by reference are non-const, so you can just capture b by reference:
tasks.emplac... |
62,806,157 | 62,806,232 | How can overloaded 'operator new' cause infinite loops? | I was reading a book named
"Hands-On System Programming with C++". It says on page 320 that overloading the new operator can cause infinite loops, so it should be avoided.
These overloads affect all allocations, including those used by the C++ library, so care should be taken when leveraging these overloads as infinit... | Simply telling a std::vector to allocate some memory in operator new should do it:
void *operator new(std::size_t size) {
// std::vector<int>::reserve calls std::allocator<int>::allocate calls (this) operator new calls ...
std::vector<int>().reserve(999);
return std::malloc(size);
}
int main() {
int *p... |
62,806,192 | 62,807,048 | What is an event table (wxWidgets)? | What exactly is an event table and what does it do? I am asking regarding wxWidgets but maybe its a general GUI programming concept, so please correct me on that.
| To keep it simple, the evend table tells which function to call when which event occurrs.
However, it is an old way of mapping events to functions.
It is no longer recommanded because isn't very flexible, and use macro tricks to do its job.
Macros themselves are generally not very recommanded in C++.
Unless you must st... |
62,806,341 | 62,806,410 | Using SFINAE to ensure the Variadic Parameter Pack Arguments are Derived of a Specific Type | I currently have a class hierachy with the following structure:
#include <list>
#include <memory>
class Base {
protected:
std::list<std::shared_ptr<Base>> items_;
Base(){}
public:
addItem(Base* derived) {
// adds derived to items_
// and checks for duplicates
}
};
class DerivedA : pub... | It'd really be a lot easier to just add an overload that takes an initializer_list:
addItem(std::initializer_list<Base*> items)
{
for(auto item: items)
addItem(item);
}
And you'd just call it with a braced-init-list: a1.addItem({&a2, &a3, &b1, &b2, &b3});.
|
62,807,113 | 62,808,051 | Non-class type Errors | It appears that the main problem is in the variable type. Can anyone suggest some of the essential functions I should be using to correct the errors?
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
char input[99];
char get[99];
int numOfchars = 0;
cout<<"Plea... | The operator . is generally used to access the member functions of the class. The char is a pure built-in datatype and not a class unlike std::string. You can't create an object of it, but a variable. And it's commonly known that a variable is a variable, not an instance of an object that it could refer to some member ... |
62,807,315 | 62,807,316 | Pass an empty unordered_map by default to function in C++ | An empty vector is passed by default by setting it to {} in the function definition. How is an empty unordered_map passed by default?
int exist(vector<int> a = {}, int x = -1, int y = 10, unordered_map<int,bool> x = ?) {
...
}
| An empty unordered map and an empty vector are initialized in the same way.
int exist(vector<int> a = {}, int x = -1, int y = 10, unordered_map<int,bool> x = {}) {
...
}
|
62,807,353 | 62,807,563 | Multiset declaration with comparator using function pointers | This is an extension of the question asked and answered here: How to define a multiset using a function pointer?
Unfortunately I do not have enough reputation to ask the user with the accepted answer my question as a comment (9 more to go ...), so here I am. Hopefully this was OK to do.
As in that question, I am also w... | The line std::multiset<A, decltype(compareA)*> m1(compareA) defines an object named m1 of type std::multiset<A, decltype(compareA)*> and passes compareA as a parameter to its constructor.
std::multiset's second template paramter is the type of comparator to use. In this case, that's decltype(compareA)*: A pointer to t... |
62,807,703 | 62,807,759 | VLA in C++ with std=c++11 extension | How is VLA working in C++ despite giving -std=c++11 compile option. As per GCC:
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++.
#include<iostream>
using namespace std;
int fun()
{
int j;
cin>>j;
return j;
}
int main()
{
const int... | As Jonathan mentions in a comment, gcc has the pedantic option that also disallows extensions:
-Wpedantic
-pedantic
Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other
programs that do not follow ISO C and ISO C++. For ISO C, follows the
versi... |
62,807,743 | 62,807,914 | Why use `std::bind_front` over lambdas in C++20? | As mentioned in a similarly worded question (Why use bind over lambdas in c++14?) The answer was - no reason (and also mentioned why it would be better to use lambdas).
My question is - if in C++14 there was no longer a reason to use bind, why did the standards committee found it necessary to add std::bind_front in C++... | bind_front binds the first X parameters, but if the callable calls for more parameters, they get tacked onto the end. This makes bind_front very readable when you're only binding the first few parameters of a function.
The obvious example would be creating a callable for a member function that is bound to a specific in... |
62,808,127 | 62,808,628 | Configure VS Code code runner extension to display CPP warnings | I am wondering how I could configure the code runner extension on VS Code (MacOS 10.15) to display warnings (i.e. -Wall?)
Would there be a simple, almost permanent method so code runner will always display warnings no matter which CPP file I build?
| Yes! This is possible.
Go to the Workspace Settings, search for code runner and click on Executor Map:
You may then use the following JSON code:
{
"code-runner.executorMap": {
// ...
"c": "cd $dir && gcc $fileName -Wall -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
} // used -Wall here
}... |
62,808,180 | 62,808,348 | Qt and C++: Overwrite or Expand Class | I want to add some properties (like an ID) to a QPushButton. Therefore, I need to expand or overwrite the class Q_WIDGETS_EXPORT QPushButton : public QAbstractButton
How do I do that?
Thanks for the help.
| It really depends on the use case. There is no problem (and often the intended way) in inheriting from Qt-(Widget) Classes (correct me, if I am wrong).
So you could do:
class MyQPushButton : public QPushButton
{
Q_OBJECT
public:
MyQPushButton() : QPushButton(...) {}
private:
int ID = -1;
}
Qt has a very ... |
62,808,478 | 62,827,183 | spdlog header-only with external fmt. spdlog error: 'internal': is not a member of 'fmt' | I am using header-only spdlog as cmake's external project.
find_program(GIT_EXECUTABLE git)
ExternalProject_Add(
spdlog
PREFIX ${CMAKE_BINARY_DIR}/vendor/spdlog
GIT_REPOSITORY "https://github.com/gabime/spdlog.git"
GIT_TAG "v1.6.1"
TIMEOUT 10
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTAL... | This has been fixed in spdlog version 1.7: https://github.com/gabime/spdlog/releases/tag/v1.7.0:
Support for using external fmt version 7.x
|
62,808,525 | 62,809,021 | How does the << operator works in the following line | I have come across a line of code.
int m_iCorners = 30 , m_iTesselation2 = 10;
int iNeededSize = (4 + (m_iCorners + 1) * (m_iTesselation2 << 1));
what is the role of << operator in the code above and how does it affect the m_iTesselation2 value?
| << and >> are the shift operators. They shift the value of their first operand to the left/right with the number of bits specified by their second operand.
<<
Let's see how it works for 13 << 3.
The binary representation of 13 is 1101. In computer the value is stored on a fixed number of bits, depending on its type. Le... |
62,808,715 | 62,808,881 | c++ insert empty vector can not use braces | Codes below doesnt' works properly, when I reference to it, it causes Member call on null pointer error, if it's not supported, why it allow the use of insert(end, {})(No compile error).
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<vector<pair<int, int>>> vv;
auto it = vv.inse... | The line auto it = vv.insert(vv.end(), {}); is using the form iterator insert( const_iterator pos, std::initializer_list<T> ilist );.
As int the line auto it = vv.insert(vv.end(), {});, the initlizer list have no element so no element is inserted in the vector vv.
As there is no element is inserted so it is same as vv.... |
62,809,121 | 62,809,469 | can anyone help me to understand this c++ code? | I explain you the working of this program.
step 1: enter the no. of time you want to run the loop.
step 2: enter two strings s1 and s2.
output : it will give you a string s3 that does not contain any character from string s2.
problem: I am unable to understand the working of for loop, and why the value of hash is 257, ... | This program figures out which characters in the first string are not contained in the second string.
Example input for the program:
1
abcdefghijklmnopqrstuvwxyz
helloworld
Example output (thanks to @mch for correction)
abcfgijkmnpqstuvxyz
Edit: Note that this is of course case sensitive as characters a and A produce... |
62,809,172 | 62,809,211 | Pass reference to external function in class constructor | There are other questions regarding how to pass an external function as an argument to a function in C++, but I am struggling to apply those answers to the case where the target function is the constructor function for a novel class.
Here is what I am trying to do:
#include <iostream>
double external_function(double x... | Like this
class foo {
public:
// Initialize a function pointer as a method of class foo
double (*func)(double, double);
// Construct an instance of the class by supplying a pointer to an external function
foo(double(*func_in)(double, double)) {
func = func_in;
}
// When calling this me... |
62,809,600 | 62,809,707 | cvSaveImage was not declared in this scope OpenCV3.4 | My teacher provide me source code of a project which is maybe based on OpenCV 2 or 3.
I tried to run it, but I get an error: ‘cvSaveImage’ was not declared in this scope. Like this:
root@qrh-pc:/home/qrh/文档/TrafficSignQtProgram/build# make
Scanning dependencies of target TREFFIC_SIGN_QT_PROJECT
[ 3%] Building CXX obj... | cvSaveImage is supported by openCV2. The supported alternative method in openCV3 and openCV4 is imwrite method. For further info check this link
C++:
bool cv::imwrite ( const String & filename,
InputArray img,
const std::vector< int > & params = std::vector< int >()
)
Python:
retval = cv.imwrite( fil... |
62,809,651 | 62,809,929 | What is the type of an 'auto' return type when returning *this in an anonymous class? | In this code:
struct
{
auto operator[](const char*)
{
return *this;
}
} m_some_class;
What is type of auto in here?
|
What is type of auto in here ?
The type is decltype(m_some_class) - I.e., the return value is of the same type as the variable m_some_class.
Note that the function will return a copy of *this.
If a reference to *this is wanted instead, you can use
auto& or, since C++14, the more generic decltype(auto).
|
62,809,820 | 62,810,461 | How to add namespaces to Lua? | I'm using Lua in a game engine that I'm working on. I'd like to give Lua a way to get and set the position of the entity that the script is sitting on. The script is a component that contains a pointer to the entity that contains it. From Lua, I'd like to be able to type:
print(transform.position.x)
transform.position.... | Short answer: it may be done with userdata and metatables.
More details:
Register metatable that will be a "class" for the position object and register "__index" and "__newindex" metamethods for it:
luaL_newmetatable(L, "position_metatable");
lua_pushcfunction(L, &position__index);
lua_setfield(L, -2, "__index");
... |
62,809,967 | 62,810,093 | Trouble in sorting vector strings using std::sort() using custom compare function | I am trying to sort strings according to a rule. The c++ code works in most cases but in some cases gives an error:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
I have seen this error before, it happens when we try to initialize a string as nu... | The only problem I can see with the code (actually I tried in an online compiler and it gave me this warning) is that you don't return anything from greater if the two strings are equal:
bool greater(string a, string b) {
int i = 0;
a = a;
b = b;
while(i<a.size() && i<b.size()) {
if(a[i] != b[i]) {
if... |
62,810,498 | 62,811,133 | Why does std::copyable subsume std::movable? | According to cppreference, std::copyable is defined as follows:
template <class T>
concept copyable =
std::copy_constructible<T> &&
std::movable<T> && // <-- !!
std::assignable_from<T&, T&> &&
std::assignable_from<T&, const T&> &&
std::assignable_from<T&, const T>;
I'm wondering why a copyable object should ... | This comes from two facts. Firstly, even if you don't define move constructor + move assignment you can still construct/assign object from r-value reference if you define copying functions. Just take a look at the example:
#include <utility>
struct foo {
foo() = default;
foo(const foo&) = default;
foo& ope... |
62,810,503 | 62,811,346 | Keeping reference to member function from other another class | I have an instance of a class A which should register a member callback in another instance of class B. I'm trying to keep the reference to the function of class A inside class B but I get a Segfault.
classA.h:
std::shared_ptr<classB> mB;
void toBeRegisteredCallback(const uint8_t val);
classA.cpp:
classA::classA(std:... | Consider your classA constructor...
classA::classA(std::shared_ptr<classB> b)
: mB(std::move(b))
{
b->registerCallback(std::bind(&classB::toBeRegisteredCallback, this,
std::placeholders::_1));
}
The initialization of mB will invoke (from here(item 10))...
share... |
62,810,792 | 62,810,869 | Unit-tests for preprocessor macros for cross-compilation and CMake | Our project builds with CMake on several platforms, including Windows, Linux and cross-compilation on some embedded OSes, described with custom CMake toolchain files.
In case of cross-compilation, we have to maintain sets of preprocessor macros.
It is reflected in CMakeLists.txt in the following fashion.
File embedded_... | I'd do it with #warning macro and check the compilation output with bash of whatever. Then you can set Werror for these files and get compile-time check. Or simply use #error (thanks to KamilCuk)
Another way is to dig into check binaries that help to see if the toolchain has threading or something else.
|
62,811,132 | 62,811,925 | Build variadic tuple from array to return | I want to have a method to build a tuple with variable number or entries based on how many entries an object has in a member variable container (e.g. vector).
This is what I've got as my best result. Not working, however. I'm obviously missing something in return value construction. Let's say m_values is a container wi... | If you know size of array at compile time, it can be done in way like this:
#include <array>
#include <tuple>
#include <utility>
struct MyType {};
constexpr auto my_type_to_any_other_type(const MyType&) {
// use if constexpr to return desired types
return 0;
}
template<std::size_t N, std::size_t... Idx>
con... |
62,811,820 | 62,811,843 | Error : Too many initializers for character array | Compile Errors :
prog.cpp: In function ‘int main()’:
prog.cpp:7:38: error: too many initializers for ‘char []’
char even[] ={"E", "V", "E", "N" }; // this is a character array.
Hey, should i use const char* here even though i just included characters? I don't understand why this error is given.
Thanks for your time! ... | char even[] ={'E', 'V', 'E', 'N'};
You are trying to initialise a char-array with strings.
|
62,811,878 | 62,812,010 | Does the header would be included explicitly when use find_package in CMake? | When I use PyTorch for C++, it's pretty easy to just use find_package to set up the dependency. And here is the CMakeLists.txt:
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(dcgan)
set(CMAKE_PREFIX_PATH /User/root/libtorch) # I added this line, does it effect?
find_package(Torch REQUIRED)
add_executable(dcg... | The include path can be set as propagated setting in the dependency:
target_link_libraries
Specify libraries or flags to use when linking a given target and/or
its dependents. Usage requirements from linked library targets will be
propagated. Usage requirements of a target’s dependencies affect
compilation of its own ... |
62,812,358 | 62,812,425 | Dynamic Object vs Non dynamic object in C++ | When do you want to use a dynamically allocated object such as, https://leetcode.com/problems/design-twitter/,
Your Twitter object will be instantiated and called as such:
Twitter* obj = new Twitter();
obj->postTweet(userId,tweetId);
vector param_2 = obj->getNewsFeed(userId);
obj->follow(followerId,followeeId);
obj->u... | You usually dynamically allocate objects if you do not know upfront how many of those you will need or if objects instances need to be shared between users.
As a side note, never use new use the std::unique_ptr or std::shared_ptr instead.
|
62,813,176 | 62,813,425 | Set QTabWidget Order by text of tabs | I am trying to set tab order by tab text or tab name
ui.tabWidget->setTabOrder(//set order here by tab name like "helloTab","hiTab");
//I have tried this(I know it's dumb just trying)
ui.tabWidget->setTabOrder(ui.tabWidget->tabBar->findChild<QTab *>("tab_1"), ui.tabWidget->tabBar->findChild<QTab *>("tab_2")... | QTab is not defined in Qt. Use QWidget:
ui.tabWidget->setTabOrder(ui.tabWidget->tabBar->findChild<QWidget *>("tab_1"), ui.tabWidget->tabBar->findChild<QWidget *>("tab_2"));
|
62,813,330 | 62,813,331 | QSocketNotifier opened on a FIFO keeps firing even if I read everything | In my code I open a FIFO (created with mkfifo) and then I proceed to use a QSocketNotifier to receive notifications of incoming data, to read it while it arrives.
// create the FIFO
if(!mkfifo(SERIAL_FIFO, 0600)) {
// nonblocking open (even open itself would block until a first write)
in_fifo = ::open(SERIAL_FI... | Ultimately, this is just a variation over the problem described here, as Qt under the hood uses select/epoll machinery to implement QSocketNotifier. Opening the FIFO as O_RDWR fixes the problem.
|
62,813,578 | 62,828,694 | OBJ file in surface3d | I have new problem couldnt find any solution in Google ...
im using a qml file and it contain a surface3d , when i show it with a obj file that was in qt examples (oilrig) it could show correct without any problems!
but when i used my own obj file (boat) it couldnt show correct in surface3d application (showing with gr... | ok i found a Temporary solution that was usefull for me.
1- convert that model in blender to ".dae"
2- upload it in scene editor online
3-convert it to Model (from NULL)
4-export as .obj file and use it in QT ^_^
|
62,813,667 | 62,821,507 | C++. I want to save a specific line of characters, that change, in a string | I run a command in CMD through my C++ app which saves the output from that command. In that output, there is a port number and a remote API token, that changes upon each restart of the application im targeting.
This is the output I'm getting through my CMD command, which I store in a string:
"C:/Riot Games/League of Le... | It depends on what you mean by "save". Save to file or just assign to a variable? My guess is that you are confused about how iterators work and are wondering how you can fetch the remote-auth-token and the port number to from the words_begin variable. If the number of "words" in the cmd output is always the same you c... |
62,813,712 | 62,814,278 | Why std::function works as an argument to std::not2? | std::not2 is implemented in the following way:
template <class Predicate>
binary_negate<Predicate> not2 (const Predicate& pred)
{
return binary_negate<Predicate>(pred);
}
It uses std::binary_negate in its implementation and binary_negate which is inherited from std::binary_function requires _Predicate::first_argum... | There is also a (from cppreference):
template< class Predicate > (since C++11)
struct binary_negate; (deprecated in C++17)
(removed in C++20)
Further, std::function does have the following typdefs:
first_argument_type (deprecated in C++17)(removed i... |
62,814,873 | 62,814,924 | Is it possible to make variable truly read-only in C++? | By using the const qualifier a variable is supposed to be made read-only. As an example, an int marked const cannot be assigned to:
const int number = 5; //fine to initialize
number = 3; //error, number is const
At first glance it looks like this makes it impossible to modify the contents of number. Unfortunately, act... | No, this is not the concern of a programming language. Any "access" protection is only superficial and only exists at compile-time.
Memory of a computer can always be modified at runtime if you have the corresponding rights. Your OS might provide you with facilities to secure pages of memory though, e.g VirtualProtect(... |
62,814,892 | 62,816,364 | Does object have to be destroyed when a new object is assigned to its address? | Consider following code.
#include <stdio.h>
using namespace std;
constexpr size_t TOTAL = 2;
class thing
{
private:
inline static size_t NEXT_ID = 0;
size_t id;
public:
thing() : id(NEXT_ID++)
{
printf("Thing %zd created.\n", this->id);
}
~thing()
{
printf("Thing %zd destr... | There is no double call to a destructor for the same object. The problem is only in your output. You are printing the id but the copy assignment in c.at(0) = thing(); copies the id from the temporary object to the one in the container. That is the reason that you see two "Thing 2 destroyed." and no "Thing 0 destroyed."... |
62,815,089 | 62,815,510 | Could std::vector::iterator legally be a pointer | I already heard that std::vector<T>::iterator can simply be T* instead of an iterator class.
But is it really legal?
Pointer arithmetic only applies to array and std::vector doesn't create array object (T[]) but contiguous objects (via placement new).
Moreover I think that std::launder would even be required (C++17) to... | std::vector::iterator is part of the Standard Library, and therefore part of the implementation. That means it may depend on implementation-specific details. In particular, the implementation may use pointer arithmetic in a non-portable way. If the implementation knows a T[] is indistinguishable from contiguously alloc... |
62,815,514 | 62,822,924 | Embedding Julia in C++ using Visual Studio | I try to embed Julia v1.4.2 in a simple C++ console application built using Visual Studio 2017 v15.0.
I follow the official docs at https://docs.julialang.org/en/v1/manual/embedding/#High-Level-Embedding-on-Windows-with-Visual-Studio-1.
However, when typing
#include <julia.h>
VS explodes in a series of 25+ errors, such... | Answering my own question here as I found a solution.
Turns out <uv.h> - which is a part of Julia - must be included before <windows.h>.
This is so because uv.h includes uv/win.h which includes winsock2.h. And winsock2.h guards against including winsock.h which is included by windows.h. But if windows.h and thereby win... |
62,815,594 | 62,815,665 | How to define constructor in class with struct as data member in c++? | I made a struct as a data member in class. Now, I want to make a constructor to which I will pass my data members. How can I pass struct in constructor.
I wrote this code but it's not working.
#include <iostream>
#include <cmath>
using namespace std;
class circle
{
private:
struct center
{
... | You can initialize the cordinate member like this:
circle(int x, int y, float r) : cordinate{x, y}, radius{r} {}
Also, your default constructor can be simplified to:
circle() : circle(0, 0, 0) {}
which delegates to the 3-argument constructor. Even better, just use in class member initializers for all the fields:
stru... |
62,815,652 | 62,815,747 | about : Scope of exception object in C++ : why don't I get the copy? | In question about scope of exception it is stated by Aj. that throw and catch clauses will create copies of the exception (unless reference is used I guess)
I tried myself a small toy code and I don't understand the result. here :
//g++ 7.4.0
#include <iostream>
using namespace std;
struct Some_error {
Some_error(... |
I would expect 2 copies to happen.
Why? Only one copy is made by the catch block. Where would the second copy happen?
set err_code to 1.1, but the display is still 1.
Because get_code returns an int, so the floating point value gets truncated.
|
62,816,071 | 62,816,970 | What is the best way to insulate new C++ code from an older (binary) component using a different CRT? | I work on a large codebase for a Windows desktop application written in C++.
Many years ago, my company paid license fee to a much bigger company for use of a component which is incorporated into our software and provides a critical service. The component is a binary blob with some header files and was compiled using t... | COM is not actively developed mostly because it's finished. It is actively supported, though. For instance, when Windows went 64 bit, COM was also ported to 64 bits. It gets security updates when necessary.
DCOM is the distributed variant of COM. I wouldn't bother; you just design everything to run on one PC using a si... |
62,816,188 | 62,816,312 | Endianness when order of bits (rather than bytes) is crucial | All of the questions and answers on endianness seem to centre on the order of bytes but suppose I've got a series of bits where the order of the bits is crucial. Let's say I save them to a memory stick file as an array of bytes. I may use the memory stick on a little endian machine one day and on a big endian machine t... | Endianess only applies to integer (and float) variables of 2 bytes or larger. It does not apply to raw data, uint8_t (byte) variables or arrays of uint8_t.
|
62,817,307 | 62,817,639 | Why is std::isnan not constexpr? | As of C++20 std::isnan is not constexpr.
Is there a technical reason for this?
All I can think of is that it is in "C header" so nobody bothered to fix it (<limits> functions dealing with floats are constexpr, but unfortunately numeric_limits does not contain isnan check).
| The answer is basically "Because the proposal hasn't been merged into the standard yet"
P0533 Proposes what you are asking, and it did not make it into C++20.
One of the holdups is that perhaps this proposal is a little big... some of the functions in <cmath> or <cstdlib> are allowed to set global error codes, which co... |
62,817,316 | 62,817,392 | How do i create multiple class objects that doesn't delete itself after a loop | I've been trying to create multiple object in a loop and store in it in a map, however it tends to get destroyed after the loop, which i understand but i want to store those objects in a map for future use.
After some debugging i found the map is only saving 1 object instead of 5 why is that and how can i improve on it... | Unless EnemySprite or tmp is defined as macro, EnemySprite tmp(x,y,40,40); is an local variable, which will be destroyed at the end of scope (end of one iteration in this case).
To avoid deletion, you should dynamically allocate memory.
EnemySprite* tmp = new EnemySprite(x,y,40,40);
SDL_Texture* tmpTex = tmp->set_image... |
62,817,374 | 62,863,174 | GlobalAlloc instead of other allocation method | While going through code on MSDN for finding the owner of the given file object, the program uses GlobalAlloc() to allocate the memory to AcctName. Since I'm new to using the Win32 API, my curiosity made me enquired why we are using GlobalAlloc() instead of other allocation methods. If other better allocation methods e... | Thanks for everyone.
I have just modified my code by using malloc.
AccountBuff = (LPSTR)malloc(AccountBufflength * sizeof(LPSTR));
DomainBuff = (LPSTR)malloc(DomainBufflength * sizeof(LPSTR));
|
62,817,740 | 62,916,727 | TSP recursive solution to its iterative form | I have a function which returns the shortest distance possible between n cities. AKA Travelling salesman problem.
int tsp(int mask, int pos, int n)
{
if (mask == VISITED_ALL)
{
return dist[pos][0];
}
int result = 2147483647;
for (int i = 0; i < n; i++)
{
if ((mask & (1... | Okay, so I have figured it out. Here's my solution if anyone's interested.
int tspIterative(int mask, int pos, int n)
{
struct MyStructure
{
int mask;
int pos;
int n;
int new_result;
int result;
int nextPos;
int stage;
};
int retVal = 0;
i... |
62,818,317 | 62,818,784 | How do you write your class's data to wostringstream in C++? | Say I have a class B which includes an array of class A, I want to use std::wostringstream to output the data in class B. I have overloaded the operator << for Class B, but I just get 'E0349' and 'C2679' error.
Definition of class A
class A
{
public:
A();
~A();
inline A(float _x, float _y, float _z) :
... | Keep in mind that std::wostringstream << char (or wchar_t) returns a std::wostream and not a std::wostringstream. So, effectively,
out << '<' << source.ArrayOfA[i];
Would be looking for the function
std::wostream &operator<<( std::wostream &out, const A & );
What you really want, is to take in, and return an std::wos... |
62,818,516 | 62,818,652 | Implicit type conversion for bitwise operation | I have this operation:
uint32_t DIM = // ...
int32_t x = // ...
// Operation:
x & (DIM-1u)
How does implicit type conversion work in the statement x & (DIM-1u)?
Does it convert x to uint32_t?
Or (DIM-1u) to int32_t?
Also, what would be the result type? Is it uint32_t or int32_t
| Two scenarios, noting that 1u is a literal of type unsigned:
unsigned is in the inclusive range of 16 bits to 31 bits. The type of DIM - 1u is uint32_t, and the whole expression is uint32_t. This is because the signed type in a binary expression where the other argument is an unsigned type is converted implicitly to u... |
62,818,683 | 62,819,398 | C++ lambda capturing by copy of parent lambda's captured value | Trying to compile the following code:
#include <functional>
void test() {
int a = 5;
std::function<void()> f = [a](){
[a]()mutable{ // isn't it capture 'a' by copy???
a = 13; // error: assignment of read-only variable 'a'
}();
};
}
gives the error: assignment of read-only va... |
[C++11: 5.1.2/14]: An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &. For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these membe... |
62,818,850 | 62,819,019 | Handling division by zero with <csignal> results in unexpected behaviour | I was trying to handle the integer division by zero (please don't judge, I was told I had to use <csignal> lib and I couldn't just use an if statement), but I needed to make sure the program would keep running (even though it's a very bad practice), instead of crashing or closing. The weird part is that the program sho... | It's defined as:
The SIGFPE signal reports a fatal arithmetic error. Although the name is derived from “floating-point exception”, this signal actually covers all arithmetic errors, including division by zero and overflow. If a program stores integer data in a location which is then used in a floating-point operation,... |
62,819,066 | 62,819,119 | Initializing Dynamic 2d array in c++ | I have created the class and first constructor, but I don't know how to initialize 2d array to ref as asked in 2, need to do this using dynamic memory allocation.
Create a class named matrix having followed private members:
• int **p;
• int rows;
• int cols;
The class should have the following member functions:
... | It seems p[i][j] = **ref; should be p[i][j] = ref[i][j];.
Also you should follow The Rule of Three. In other words, you should declare copy constructor and assignment operator to handle object (including pointers) copying properly.
|
62,819,325 | 62,819,860 | Can a constant be optimized away | If we have a static const class member the address of which is never used, can the member be optimized away and allocated no storage ?
| Yes, but only link-time optimisation is capable of doing this, because only the link stage can prove that the address is never taken throughout the whole program. And, if you're producing a shared library, that's just off the table. Speaking generally, you're best off assuming that the object probably will take up spac... |
62,820,255 | 62,820,639 | How to access the position of an object within a vector when using an iterator? | I'm currently doing this:
for (std::vector<myClass>::const_iterator i = myVec.begin(); i != myVec.end(); ++i) {
std::cout << *i << ", ";
}
As it is the recommended way to output all the members of a vector. The problem is that this means that all of my members of this vector get output on a singular line. I want t... | As always, there are a lot of possibilities to achieve this. But to answer your initial question:
for (std::vector<myClass>::const_iterator i = myVec.begin(); i != myVec.end(); ++i) {
std::cout << *i << ", ";
size_t index = i - myVec.begin();
if (index % 5 == 0) {
std::cout << "\n";
}
}
This p... |
62,820,355 | 62,820,527 | std::ranges::elements_view for custom tuple-like data | I have an use case that can be reduced to:
#include <vector>
#include <ranges>
#include <tuple>
struct TDat
{
double x, y;
template <std::size_t I>
friend double &get(TDat &Dat)
{ if constexpr (I == 0) return Dat.x; else return Dat.y; }
template <std::size_t I>
friend double const &get(TDat const &Dat)... |
I believe that, since the call to get is qualified, the compiler cannot find my get functions. Is that conclusion correct?
Yes.
If so, is that the intended behaviour?
That's the specified behavior at least. [range.elements.view] defines the concept as:
template<class T, size_t N>
concept has-tuple-element = ... |
62,820,446 | 62,821,136 | For loop variants comparison | There is a for loop like this:
uint32_t WORD_COUNT = // ... a constant number
using Word = uint64_t;
Word mWords[WORD_COUNT];
uint32_t n = WORD_COUNT;
for (Word* w = mWords; n--; ++w) *w = Word(0); // <= Original loop
Can the original loop be written like this?
for (uint32_t i = 0; i < n; ++i) mWords[i] = Word(0); /... | If the loop is used to initialize that array, you could just write
uint32_t WORD_COUNT = // ... a constant number
using Word = uint64_t;
Word mWords[WORD_COUNT] {};
// ^^
// See e.g. https://en.cppreference.com/w/cpp/language/aggregate_initialization
Otherwise, as john mentioned
You could also u... |
62,820,628 | 62,823,532 | On windows is it possible to get dll's to look for dependencies in another folder without using the PATH environment variable? | On linux I am able to set theRPATH of a shared library to $ORIGIN:$ORIGIN../lib. This tells the DLL to look in the same directory as the shared library as well as in the ../lib folder. I've read that on windows you just add the absolute path to ../lib (for example) to the PATH. Is there an alternative to this method? I... | If the main DLL dynamic/delay-loads the dependent DLLs, it can call SetDllDirectory() (or better, AddDllDirectory()) before loading them.
If the main DLL static-links to the dependent DLLs, but the EXE dynamic/delay-loads the main DLL, then the EXE can call (Add|Set)DllDirectory() before loading the main DLL.
Otherwise... |
62,820,653 | 62,820,788 | Random numbers on if array | I'm trying to find the highest item in an array that holds age-numbers.
The thing is it would return random numbers at the if line. I want to undestand the logic behind it.
The language is C++ and I'm pretty sure this is very easy to solve.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
... | Your program has undefined behavior since you are using i and suma without initializing them.
Also, make sure that you check that the extraction of numbers is successful before using them.
Use
int edad[100] = {}; // Initialize the elements to zero.
int n = 0; // It's a good practice to initialize all variables... |
62,821,340 | 62,821,656 | Using .find function to find size between character and another character in c++ | I am looking for some help with a find function in C++. I have searched and searched but nothing I try works correctly.
The question is:
The function has to convert this date to the international format. For example: If the string "December 29, 1953" is received, the string that the function should return must be "29 ... |
I have searched and searched but nothing I try works correctly.
Well, if you're looking for a solution to the problem, and willing to use something you haven't tried, then usage of std::istringstream makes the code trivial:
#include <sstream>
#include <string>
#include <iostream>
std::string convertDate(std::string ... |
62,821,641 | 62,824,668 | Working with Node::Buffers in C++ Node Addons | I'm working on a Node addon that encrypts data using Windows DPAPI. I'm passing two Javascript Uint8Array to the C++ code using NAN.
This is what the typescript interface looks like:
export interface DpapiBindings{
protectData(dataToEncrypt: Uint8Array, optionalEntropy: Uint8Array, scope: string): Uint8Array
}
I'd... | No, you don't need to worry about overflow. The dataIn and dataOut structures are pointers with a length.
BufferCopy is not what you want to use though. You want to use: Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size).
https://github.com/nodejs/nan/blob/master/doc/buffers.md#api_nan_new_buffer
and... |
62,821,795 | 62,916,482 | Undefined symbols for architecture arm64 after linking a static library in iOS app | I am creating a sample static library to be used in my iOS app, however, when calling the static library's methods, I ran into a linker error:
Undefined symbols for architecture arm64:
"_doMath", referenced from:
_doMathInterface in libTestMain.a(Test.o)
(maybe you meant: _doMathInterface)
ld: symbol(s) not found fo... | The problem is that your doMath function gets compiled as C++ code, which means that the function name gets mangled by the C++ compiler. Your Test.m file however gets consumed by the (Objective-)C compiler and C doesn't use name mangling.
This means that the linker will end up looking for the wrong symbol. You can fix ... |
62,822,043 | 62,822,139 | How to read a string from a binary file? | I am trying to read a string(ver) from a binary file. the number of characters(numc) in the string is also read from the file.This is how I read the file:
uint32_t numc;
inFile.read((char*)&numc, sizeof(numc));
char* ver = new char[numc];
inFile.read(ver, numc);
cout << "the version is: " << ver << endl;
what I g... | A char* string is a nul terminated sequence of characters. Your code ignores the nul termination part. Here's how it should look
uint32_t numc;
inFile.read((char*)&numc, sizeof(numc));
char* ver = new char[numc + 1]; // allocate one extra character for the nul terminator
inFile.read(ver, numc);
ver[numc] = '\0'; // add... |
62,822,342 | 62,822,493 | how to return multiple values of struct from get function in c++? | I have made a struct data member in my class. Now, I want to return values of that struct using a get function, but it is generating errors. I am not sure what the datatype of the getcenter() function should be, and what the body should be.
#include <iostream>
using namespace std;
class circle
{
private:
s... | Here is the corrected code which compiles. You had many errors coming from your << operator which was not implemented for the circle class.
You can either write a toString() method (which could print in a nice way what a circle is) or override the << operator for the circle class.
#include <iostream>
using namespace s... |
62,822,473 | 62,822,568 | Can I reassign/overwrite a std::string? | Can I do the following in C++?
std::string a = "";
a = "hello";
a += ", good sir";
//use a in the program
a = "";
a = "bye";
a += " to you";
//use it for something else
If this is not a legitimate operation, may I incur into memory issues down the line? This last point is important to me because I have some of those a... | Yes, you can reuse the same variable for multiple purposes one-by-one. But actually I won't recommend you, the program will be a bit messy if you use only a single variable for multiple usage.
The class std::string automatically allocates the required bytes memory to store the string literal and reallocates when the st... |
62,822,481 | 62,823,369 | C++ Hazelcast with Protobuf serialization: String is not UTF-8 formatted | I want to be able to send serialized Protobuf data using HazelCast. I understand why it gives me the error but is there a way around it?
Here is the sample code I am using:
main.cpp
#include <iostream>
#include <vector>
#include <hazelcast/client/HazelcastClient.h>
#include "testProto.pb.h"
using namespace std;
int m... | From protobuf doc:
SerializeToString(string* output) const;
serializes the message and stores the bytes in the given string. Note that the bytes are binary, not text; we only use the string class as a convenient container.
So it's not safe to store them as string in IMap, as it is prone to fail in case of non UTF-8 f... |
62,822,550 | 62,822,650 | Trouble with nested for loops C++ (beginner) | So I'm starting out practicing some code and wanted to create a Z shape using "X" in a 7x7 like grid.
Can someone help me figure out what I'm doing wrong or missing?? Thanks!!
#include <iostream>
using namespace std;
int main(){
string x = "X";
for(int i = 0; i <= 6; i++){
for(int j = 0; j <... | You've mistaken in the conditions.
You've used = (assignment operator) rather than comparison operator ==.
Replace all the = in if - else if with ==. Something like:
if((i == 0) || (i == 6))
cout << x;
else if((i == 1) && (j == 5))
cout << x;
else if((i == 2) && (j == 4))
cout << x;
else if((i == 3) && (j ... |
62,822,595 | 62,822,867 | Getting the maximum Pair Wise product C++ and the output is not always right with my code | Problem to solve:
given an array or sequence of numbers the goal is to find the Max number obtained by the multiplication of some 2 numbers in that sequence.
example of inputs and outputs
Input:
2
100000 90000
Correct output:
9000000000
Input:
3
1 2 3
Correct output:
6
My Solution: get the 2 Maximum numbers in the ... | There are several mistakes in the code:
cout << ... << ' ' syntax tries to print three whitespace characters letters using a single-quote which accepts a single letter not multiple. Use " " instead.
The result produced can't be held by an integer, you need to define size_t (which expands into unsigned long long i... |
62,822,725 | 62,822,790 | gcc and clang disagree on whether expression is constant evaluated | For the following program:
struct S { int i; };
constexpr S f() {
return std::is_constant_evaluated() ? S{1} : S{0};
}
int main() {
S s = f();
return s.i;
}
gcc returns 0, and clang returns 1. demo
I don't think the evaluation of f is being done in a context that requires constant evaluation, so I think clan... | The requirement we're looking for is if an expression is manifestly constant-evaluated, which is defined in [expr.const]/14, which is:
a constant-expression, or
the condition of a constexpr if statement ([stmt.if]), or
an immediate invocation, or
the result of substitution into an atomic constraint expression to dete... |
62,822,778 | 62,822,825 | C++ Inheritance change member | Currently learning more c++ and I have this question: Why do I have to use a function to change a member of a parent class instead of just changing it without the function?
class Shape{
private:
int a;
protected:
int b;
public:
int c;
};
class Rectangle: public Shape{
public:
c = 123;
void change_c(){c = 32... | Assigning a value to a variable, like in the statement c = 123;, is illegal outside of a variable declaration or an assignment performed within a function. Which means you can't perform it from within the class scope of a derived class:
class Rectangle: public Shape{
public:
c = 123; // <-- illegal
int d = 123; //... |
62,822,893 | 62,834,743 | Project Structure for unit testing (qtest) when using target_sources() command in sub directory | First of all, I know there are very similar questions in this forum. However, none really answer my specific case.
I have the following project structure:
|---Project_Root
|---CMakeLists.txt
|---build
|---src
| |---CMakeLists.txt
| |---many .cpp and .h files in multiple subfolders with a differe... | As you described, you can make a new static library target Project_Lib. Take advantage of the fact that you parameterized the target name by using the project name (${PROJECT_NAME}), so you actually don't have to change all of the CMakeLists.txt files in the subfolders. Just change the project name.
As I commented, sim... |
62,823,360 | 62,823,475 | C++ 20 Concepts: Require operator overloading | I am trying to understand how to declare a concept that requires a particular operator is overloaded for a given type. Lets say I have the following function that takes a vector of an arbitrary type and prints it to std::cout:
template<typename printable>
void print_vector(const std::vector<printable>& vec)
{
std::c... | template <class T>
concept Printable = requires(std::ostream& os, T a)
{
os << a;
};
template<Printable T>
void print_vector(const std::vector<T>& vec) {
std::cout << '{';
for (const auto &item : vec) {
std::cout << item << ',';
}
std::cout << '}';
}
If you wish you could also make it more generic to... |
62,823,798 | 62,844,326 | UE4 Casting OtherActor on OnComponentBeginOverlap | Am new at UE4. Now i am colliding two classes. a pawn and a character class. My OnComponentBeginOverlap dynamic is in pawn class. That means i am trying to get OtherActor from my pawn class. OtherActor should be a ACharacter class. Now let's see the parameter signature:
void Adenn_pawn::OnOverlapBegin(UPrimitiveCompone... | You can try casting OtherActor to a variable of type ACharacter* using the Cast function. Luckily the function will check if the actor overlapped is of type ACharacter, so this is helpful when you're not sure if OtherActor is of type ACharacter. You can call the Cast function and do what you wish with the casted actor ... |
62,824,376 | 62,842,038 | Make an external project available for find_package CMake | In my project I have a dependency "A" that has another library dependency "B", I'm trying to download and install the dependency B before A in order to clear the conflict. I'm using Externalproject_add, FetchContent_Declare and install, but it fails.
for an example
I got a CMakeList.txt like:
FetchContent_Declare( lib... | well technically you can "modify" the png project by applying a patch.
Unfortunately FetchContent/add_subdirectory() i.e. incorporating third party as subproject, can't work with find_package().
You should replace by something like this
if(NOT TARGET ZLIB::ZLIB)
find_package(ZLIB)
endif()
i.e. create a patch an appl... |
62,824,403 | 62,824,697 | What are some good scenarios to use a cstring over a string? | I've made quite a few projects (small) now with C++ and was wondering, what would be some good scenarios in which it is better to use a cstring instead of a string?
Just to clarify, I'm not calling cstrings bad. I'm just genuinely interested if they are as important as regular strings in C++
| std::string allocates dynamic memory at runtime for its character data (unless the std::string implementation employs "Short String Optimization" and the data is short enough to fit in the SSO buffer).
So, one scenario you may want to use C-style strings for is when you want to pass around string literals without alloc... |
62,824,407 | 62,824,951 | Template function to convert std::string in std::wstring and vice_versa with compile time checking | I have the following functions:
std::string convert(const std::wstring &str);
std::wstring convert(const std::string &str);
Which I would like to do something like this:
template<class T, class U> T convert(const U& u);
I created some verification:
template<class T> struct is_string : public std::false_type {};
templ... | Not particularly elegant... but I suppose you can write something as follows
#include <type_traits>
#include <string>
template <typename T,
typename U = typename std::conditional<std::is_same<T, std::string>::value,
std::wstring,
... |
62,824,685 | 62,867,918 | How to change the width of a QDialog box with the help of Qpushbutton | i have a QDialog box named "Validate dialog" and a QPushbutton on that dialog named "Refresh Width" , when i click this button the width of the QDialog box must be changed from 1000 to 500,
by reading some documentation , i got to know that i can probably use setFixedWidth(int w) function , and tried using it but facin... | @Mr_Workalot
It's quite basic so in the first time I think it's not necessary to show the source. But to avoid the confusion or misunderstanding, below is the code for your reference.
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setu... |
62,825,026 | 62,825,122 | How to know the number of digits in an integer | I'm new to programming, and I'm wondering, how can I know the number of digits in an integer that the user enters? For example: the user enters a number like 123456, how can I know that the user enters 6 digits? I don't want to use a for loop to get user input because I don't want the user to enter each digit after a ... | Yes, you can read in the user's input as a std::string instead of as an int, and then you can use std::string::size() (or std::string::length()) to get the number of characters in the string, eg:
#include <iostream>
#include <string>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
for (... |
62,825,053 | 62,825,089 | Constructing with a reference to an const array of const structs | So I have an array of structures and a class that uses the array. The constructor needs to reference the array of structures which are a constant. What I am struggling with is passing the array of structures as a reference so that the class constructor can use it. Since the array of structures doesn't change there i... | You need to specify the size of the array using a template parameter:
template<size_t N>
class Converter
{
protected:
size_t _length;
const c_cs_pair_t(& _pairs)[N];
public:
Converter ( const c_cs_pair_t(& pairs)[N] ) : _pairs(pairs) {
_length = N;
}
};
Note that you don't really need the _le... |
62,825,770 | 62,825,792 | Given two even numbers, find the sum of the squares of all even numbers between them | My task is to create a program that will prompt the user for two even ints, finput and sinput. After that, it should output the sum of the squares of all even numbers from finput to sinput, inclusive.
Here is my code which attempts to accomplish this:
#include <iostream>
#include <cmath>
using namespace std;
int main... | You can use a for-loop to loop through all numbers from finput to sinput. Make sure to increment by 2 each time to get all the even numbers from finput to sinput.
int sum = 0;
for(int i = finput; i <= sinput; i += 2){
sum += i*i;
}
There is also a O(1) way to get the sum of all even squares between finput and sinp... |
62,825,843 | 62,826,028 | Why does a member of ostringstream type in class cause "call to implicity deleted copy-constructor" error? | I have isolated a problem with "call to implicitly deleted copy-constructor" compilation errors to the use of an ostringstream type in declaring members of a class. In the example below, a STL list of objects of the example's Reading class is defined. At the point where push_back is called, the compiler searches for th... | Each class has an implicitly-declared copy constructor if you don't declare one, but only if each data member and inherited type can be copy-constructed. std::ostringstream has no copy constructor, therefore the compiler cannot generate a copy constructor for Reading.
You can define a copy constructor yourself, if you... |
62,825,984 | 62,858,839 | Masking Structure Name | I'm trying to mask a structure name like so:
#define cat_val(l, r) l##r
#define name_mask cat_val(exception_, __COUNTER__)
using i_dont_show_in_rtti = struct name_mask
{
// ...
};
void test()
{
throw i_dont_show_in_rtti{};
}
This works, but only individually in files. If I include a file that has done this, I'll... | It is possible to do this in completely standard C++14.
#include <cstdlib>
template <std::size_t N>
constexpr std::size_t ct_hash(const char (&str)[N])
{
std::size_t hash = 0;
for (std::size_t i = 0; i < N; ++i)
hash = (hash << 7) + (str[i] * str[i]); // just an example
return hash;... |
62,826,076 | 62,833,924 | no matching function for call in rcpp | When using Rcpp,I create a function named rpois_rcpp and l try to call it below in genDataList function, an error occurs and said :
"no matching function for call to 'cpprbinom',
candidate function not viable: no known conversion from 'arma::vec' (aka 'Col') to 'Rcpp::NumericVector' (aka 'Vector<14>') for 3rd argument
... | Thanks for adding your code. When I tried to compile, I got the same error as you, but also an error for the line calling rpois_rcpp()
invalid initialization of reference to type 'Rcpp::NumericVector&'
Pretty much everything seems to be in arma, except the R bindings and calls to the R:: namespace, which takes double... |
62,826,144 | 62,826,186 | Virtual function of derived class calls that of base class | #include <iostream>
using namespace std;
class Widget {
public:
int width;
virtual void resize() { width = 10; }
};
class SpeWidget :public Widget {
public:
int height;
void resize() override {
//Widget::resize();
Widget* th = static_cast<Widget*>(this);
th->resize();
hei... | The commented out code is right.
Widget::resize();
Your substitute code is wrong.
Widget* th = static_cast<Widget*>(this);
th->resize();
Think about it: You are calling a virtual function through a pointer to the base class. What happens when you do that with any virtual function? It calls the most derived version... |
62,826,230 | 62,826,522 | Is there a difference between std::string's front() and [0]? | In my program I need to check the first character of a std::string, and use something like this:
if(string.front() == '-')
I wonder, does using the code below instead make any difference?
if(string[0] == '-')
| From the reference for string::front:
Effects: Equivalent to: return operator[](0);
So there is no difference between the 2 snippets of code you've shown.
|
62,826,246 | 62,826,334 | C++ Curiously Recurring Template Pattern "uses undefined struct" compile error | I have two classes using the Curiously Reoccurring Template Pattern with a parent class.
When I compile on VS2013 I get two errors, one for each subclass, stating:
'Parent<Child1>::_child' uses undefined struct 'Child1'
'Parent<Child2>::_child' uses undefined struct 'Child2'
Am I including the files incorrectly, or do... | When using the recurring template pattern, the child is an incomplete type in the scope of the parent.
template<class CHILD>
struct Parent
{
CHILD _child; // <- there, incomplete
};
You cannot instantiate an incomplete type as its definition is not there yet.
So... why is that?
A type become complete when the comp... |
62,826,300 | 62,826,313 | Why can I use more memory than allocated? | I was messing around with the memset function and did this:
int* p = malloc(sizeof(int);
memset(p, 0, 10000);
I was wondering why this is valid. I've only allocated 5 bytes of memory yet I can take up 10000 with memset. Why should I even malloc the memory if I can take up more than allocated? Could someone explain?
| It's undefined behaviour, as in you can do it but the results are not defined, as in unpredictable, as in the program might crash.
In this case you can only write to the allocated region, or sizeof(int) * 5.
Why doesn't C prevent you from doing this? It's because the language design philosophy is that the programmer kn... |
62,826,437 | 62,826,481 | I can't figure out what's going wrong when I try to add 2 big strings | I tried this question by using big integer library in c++ and it works completely fine and when I try to do this using one integer at a time from both the strings
I get a run time error and I did try to debug it by including cout statements in the code but everything seems fine.
string addStrings(string num1, string n... | You declare a std::string called res in your program, which you want to return from your function. Everything works fine until this line:
res += u;
In this line, you attempt to add an int to a string, which will return unexpected results. To fix this, you can use res.push_back(u + '0') instead (this converts u to a cha... |
62,826,712 | 62,826,741 | inquiry in designing my Arm simulator function representing format 1 | The following function represents format 1 in ARM Thumb. I don't understand the part of using AND(&) after shifting in each declaration of the fields of the formats and why did we use these numbers after AND?
format 1 representation in ARM architecture
int simulate(unsigned short instr)
{
unsigned char fmt, op, of... | For something like op, it is supposed to be 2 bits long, but it's at some offset into your instruction. So you need to get the op bits shifted all the way to the least significant position, then remove any remaining bits.
The shift moves the bits to the least significant bit position in your op unsigned char, and ANDin... |
62,827,030 | 62,827,075 | Problem with a function similar to strcat() | I tried to write a function similar to strcat() in c++.
Here is the code of this function:
char *mystrcat(char *str1, char *str2){
int i = 0;
char *buffer = str1;
while(*str1){
str1++; i++;
}
i++;
while(*str2){
str1[i] = *str2;
str2++; i++;
}
str1[++i] = '\0';
... | For a start, since you're incrementing both str1 and i in the first loop, you're going to move twice as fast through that array as you think. Thats because you're increasing both:
the base of the array; and
the offset from that base.
You're actually lucky to have chosen an even number of characters, otherwise you'd p... |
62,828,177 | 62,828,818 | Would sign be lost: zeroing out the low-order bits | I have a Coord class like this:
class Coord
{
public:
Coord(int32_t x, int32_t y, int32_t z): mVec{{x, y, z}} {}
int32_t operator[](size_t i) const { assert(i < 3); return mVec[i]; }
private:
std::array<int32_t, 3> mVec
}
Now I use my class:
Coord origin(-1, 2, -4);
uint32_t DIM = 1 << 12; // 2 ^ 12... | In hexadecimal DIM is 00001000, DIM-1 is 00000FFF, and ~(DIM-1) is FFFFF000. Then the & operation preserves all bits that are set in ~(DIM-1) and zeroes all bits that are clear in ~(DIM-1). So the lower 12 bits are zeroed and the upper 20 bits are preserved. Since the sign bit is the highest bit it is preserved.
Techni... |
62,828,526 | 62,828,988 | Why is UINT32_MAX + 1 = 0? | Consider the following code snippet:
#include <cstdint>
#include <limits>
#include <iostream>
int main(void)
{
uint64_t a = UINT32_MAX;
std::cout << "a: " << a << std::endl;
++a;
std::cout << "a: " << a << std::endl;
uint64_t b = (UINT32_MAX) + 1;
std::cout << "b: " << b << std::endl;
uin... | This behaviour is referred to as an overflow. uint32_t takes up 4 bytes or 32 bits of memory. When you use UINT32_MAX you are setting each of the 32 bits to 1 which is the maximum value 4 bytes of memory can represent. 1 is an integer literal which typically takes up 4 bytes of memory too. So you're basically adding 1 ... |
62,828,757 | 62,828,869 | How to find the occurrence count of sequence's largest element in C++? | C++ beginner here. I'm trying to write a program without the usage of arrays that would take a N number and allow the user to write a sequence of elements consisting of the N number (e.g. the N is 5, then the sequence of elements should be consisted of 5 integers (e.g. 8,21,7,21,10)). Then the program should count how ... | You need to increase the count when n_seq == max and when you encounter a new maximum number you need to reset the counter:
if(n_seq > max)
{
counter = 1;
max = n_seq;
} else if (n_seq == max) {
++count;
}
|
62,828,959 | 62,832,365 | Why is mpfr_printf different than printf for hex float (%a conversion specifier)? | I'm comparing values from regular floating point arithmetic and using a high-precision MPFR number as a baseline. When printing, I'm confused why the following code is output different.
The MPFR documentation says the output specifiers are
‘a’ ‘A’ hex float, C99 style"
So I would assume it prints the same as printf... | There is no canonical form. The C standard does not regulate the first digit except that it must be non-zero for normal numbers. C 2018 7.21.6.1 8 says, of the a and A conversion specifiers:
A double argument representing a floating-point number is converted in the style [-]0xh.hhhhp±d, where there is one hexadecimal ... |
62,828,960 | 62,843,476 | Register and unregister a handler while iterating throught the vector of handlers | I have got a very small program which starts a thread and dispatches events to the registered set of handlers. Handlers class look as follows.
class Handler
{
public:
/* OnEvent must return void. This is part of the user interface agreement */
virtual void OnEvent(struct Event*) = 0;
virtual ~Handler();
};
... | If you are fine with handler changes only taking effect after event processing, you can just copy the handler array:
std::vector<Handler*> handlers;
void thread_function(){
struct Event* e = getEvent();
std::vector<Handler*> handlersCopy = handlers;
for(Handler* h : handlersCopy) {
h->OnEvent();
}
}
If yo... |
62,829,299 | 62,967,516 | C++ DllInjection / Run dll in sandobxed enviroment (Hooking system/WinAPI calls) | So I have a native Windows dll witch is heavily obfuscated, so disassembling is not an option.
If I call a specific function in the dll, the dll does some stuff in my registry, reads a few files and finally returns something.
I want to hook up the registry and filesystem WinAPI calls. So that I can change the return of... | It seems the only solution is to inject a dll (via AppInit_DLL) and hook the windows functions (setwindowshookex).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.