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 |
|---|---|---|---|---|
68,783,081 | 68,783,100 | Why does shared_ptr not delete its memory? | int main(){
int* iptr;
{
std::shared_ptr<int> sptr = std::make_shared<int>(12);
iptr = sptr.get();
}
std::cout << *iptr;
return 0;
}
Output
12
I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces. But output shows 12. Do I miss... |
Why does shared_ptr not delete its memory?
shared_ptr does delete the memory that it owns when it is the last owner.
I was expecting that the content to which iptr points, would have been deleted, at the end of inner curly braces.
You were expecting correctly.
But output shows 12. Do I miss something?
You're miss... |
68,783,210 | 68,783,296 | Intel VTune Profiler error for Mac: Cannot communicate with the target | I'm using Intel VTune on my personal MAC, to profile a remote application on a Linux server. I followed the instructions on https://software.intel.com/content/www/us/en/develop/documentation/get-started-with-vtune/top/macos.html.
When configuring analysis, in the WHERE pane, I selected Remote Linux (SSH) and specified ... | I have tried this without any problem, so I suggest to see possible issues section and follow them, it may help,
https://software.intel.com/content/www/us/en/develop/documentation/vtune-help/top/set-up-analysis-target/linux-targets/remote-linux-target-setup/configuring-ssh-access-for-remote-collection.html
I usually us... |
68,783,323 | 68,783,458 | How to use typedef in header file cpp | I have created a new type using typedef and a struct. I want to export that type as a module.
I have the following cpp header file:
//header.h
#ifndef VECTOR_H
#define VECTOR_H
typedef struct {
float x;
float y;
float z;
} Vector;
#endif
#ifndef PLANE_H
#define PLANE_H
class Plane {
public:
//... | You seem to be copying the Plane class's declaration, while an include is enough, so change your module.cpp file into something like:
#include "header.h"
Plane::Plane(Vector P1, Vector P2, Vector P3)
{
}
Note that above does define what the header does declare, in C and C++, we can separate the declaration from defi... |
68,784,459 | 68,784,571 | how to make a table with different types | i need to put some data of different types(int,string)in the same table (knowing that the structure of the table is variable(rows, columns, the type of the data in the column is variable)) ,how can i do this in C++
| Either use std::variant or a union. The former is type-safe, but only available in C++17 and later.
|
68,784,746 | 68,786,959 | Why do I have to move the pointer by 2 using 'seekg' when it points at a new line symbol? | Trying to parse the file:
1
2
3
It basically represents something like this: 1\n\n2\n\n3. I want to skip a number of symbols and if a particual one is presented during this action, I should to return the pointer back. Further the first implementation is put forward:
void DoSomething(std::fstream &file, std::size_t n... | On Windows, historically text files store 2 symbols for a line break - \r\n. When you open a file with std::(i|o)fstream in text mode, read operations replace \r\n with \n, and vice versa on write operations. std::istream::seekg() moves the read pointer in bytes, ignoring that translation. So std::istream::peek() give... |
68,784,829 | 68,784,846 | How print out the OpenGl version of a GPU and put it in a string in Opengl and C++? | I need to print out the OpenGL Version of my GPU in an application and then put it in a string.
| You can use the following code as an example:
std::cout << "" << std::endl;
std::cout << "" << "OpenGL Vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "" << "OpenGL Renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "" << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;
std::co... |
68,784,961 | 68,788,433 | Cast an element in Eigen Vector/Matrix to a primitive double type | Basically how do i do this
Eigen::RowVectorXd param(2);
param << 1.0, 2.0;
double last_element = param.tail(1); // error: no suitable conversion...
I know i can use .coeff() however in my code some vectors are being resized, thus the size is unknown a priori
| Would something like this work:
Eigen::RowVectorXd param(2);
param << 1.0, 2.0;
double last_element = param(param.size() - 1);
or even better, using the Eigen provided last value:
double last_element = param(Eigen::last);
|
68,785,213 | 68,785,689 | Using iterator to read input | I have the following code, which has sin_start(cin) function. I am not sure if there is any such function defined in C++ or if I need to define it myself. But somehow this code compiles and runs too.
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
cout << "Enter integers: ";
istream_i... | The code compiles because it is valid code. It just doesn't do anything meaningful.
sin_start is not a function, it is a variable of type istream_iterator<int>, where istream_iterator is a template class defined in the <iterator> header file. It is being passed std::cin as a parameter to its constructor, so it knows wh... |
68,786,348 | 68,786,618 | Problems understanding the min and max declarations syntax in std::chrono::duration_values | I'm having a look at the piece of code below, from std::chrono, and I don't understand the _Rep(min)() syntax.
I know _Rep is the return type, and min has to be the method name, but then:
What's the difference between writing it like _Rep(min)() and _Rep min()?
And, why isn't the same done for zero?
template <class _... | Its to defeat macro expansion; the Windows headers used to define macros named min and max.
|
68,786,394 | 68,788,413 | Return a pointer on multidimensional array c++ | I want to make a function who return a pointer on a mutidimensional array (cause we can't return an array in cpp) but I don't know how to do this.
I have this error
./source/code/metier/Jeu.cpp: In member function ‘Tuile** Jeu::getPlateau()’:
./source/code/metier/Jeu.cpp:21:10: error: cannot convert ‘Tuile* (*)[6][9]’ ... | I think I was able to get it compiling by creating typedefs:
class Jeu {
...
using TuilePtr = Tuile*;
using TuilePtrArray = TuilePtr[LARGEUR][LONGUEUR];
TuilePtrArray plateauTuile;
...
TuilePtrArray* getPlateau() { return &plateauTuile; }
}
I may have mixed up the types though, so if it's still failing let... |
68,786,397 | 68,786,556 | C++: Get and list all the files from directory that user writes | I am new here. I am working on a small program for binary packing files but I don't know how to make a function that would read and list all the files, with different names and extensions, inside a folder that user writtes.
string folder;
cout << "Input folder name: ";
getline (cin, folder);
So after that command, fun... | I would use std::filesystem::directory_iterator to go through all files in a given directory.
#include <iostream>
#include <filesystem>
int main()
{
const std::filesystem::path path{ "C:\\temp" };
for (auto const& dir_entry : std::filesystem::directory_iterator{ path })
std::cout << dir_entry << '\n';
... |
68,786,402 | 68,786,475 | add to std::map with a non-default-constructible mapped value | I have a std::map<Key, T> with a non-default-constructible T. T operloads operator + so that I know how to add objects of T. I am frequently in the situation that I need to add a particular value at at a given Key k. If T were default constructible I would do something like
std::map<Key, T> map;
Key k;
T t;
map[k] += ... | To look-up only once, you might do something like:
if (auto [it, inserted] = map.insert(k, t); !inserted) {
*it += t;
}
|
68,786,569 | 68,786,679 | using constexpr to return pointer | Since C++20 we can allocate memory during compile time and we have to free that during compile time. Therefore this raised some questions for me:
first why does this work?
constexpr int* return_ptr() {
return new int{ 1 };
}
void call_return_ptr(){
int* int_ptr = return_ptr();
}
int main() {
call_return_p... | There is no such thing as "compile-time". Not really.
What there is is "constant expression evaluation". These are a certain category of expressions whose evaluation happens in a certain way, such that the results of their evaluation are available to the source code.
A constexpr function is a function which may be eval... |
68,786,593 | 68,786,602 | How do I fix error "C++ requires a type specifier for all declarations?" | I am on macOS right now, XCode Version 12.5.1.
I've encountered an error I haven't ever seen before, and I've searched all over for solutions however none have made sense.
Here's my code:
#include <iostream>
#include <cstdint>
#include <dlfcn.h>
std::uintptr_t rebase(const std::uintptr_t address, const std::uintptr_t ... | You cannot call functions outside of a method, unless you're initializing globals. You need to put your function call inside a method.
I.e.
int main() {
r_print("hi", nullptr);
}
|
68,786,754 | 68,787,615 | Finding key corresponding to max value in c++ map | Given a number say 'KEY' and map <int, int> myMap. I am trying to find a smallest key k (condition: k < KEY) in the map myMap such that it's value is maximum.
Example:
map <int, int> myMap = {{3,1}, {4,3}, {5,2}, {6,3}, {7,2}, {8,5}};
// ^^^
int KEY = 7;
Answer is 4, since for all the keys... | How about this. You maintain a secondary map, a subset of your primary one. Specifically, this secondary map would contain {k, v} if and only if all smaller keys in the primary map correspond to smaller values.
For your example of {3,1}, {4,3}, {5,2}, {6,3}, {7,2}, {8,5}, this secondary map would be {3,1}, {4,3}, {8,5}... |
68,787,012 | 68,788,430 | MFC modeless dialog freezes when using cURL | I have a MFC application where it tries to get a page using cURL. When running the app, the dialog becomes unresponsive for a moment. Is there any way to fix this?
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
... | As noted earlier, you have to run the function in a separate worker thread.
CreateThread + WaitForSingleObject may behave like a blocking function, depending on how it is implemented...
One alternative is to run the worker thread and continue in GUI thread. Once the worker thread is finished, use synchronization object... |
68,787,080 | 68,787,143 | Mapping a structure to uint64_t | What is the right way to convert the structure below to uint64_t?
struct Data
{
uint64_t sign : 1;
uint64_t exp : 4;
uint64_t man : 8;
};
static_assert(sizeof(Data) == sizeof(uint64_t));
the obvious one is
Data data;
uint64_t n = *(reinterpret_cast<const uint64_t*>(&data));
but it does not compile as con... | You std::memcpy the structure to an uint64_t. std::memcpy is a legal way to perform type punning, it is allowed since your structure is trivially-copyable.
In C++20 there is also std::bit_cast.
Unlike std::memcpy it's constexpr, but to make it work at compile-time I had to add uint64_t : 51; at the end of the struct.
... |
68,787,490 | 68,787,523 | C++ string variables not accepting enter and tab whitespace? | Why does the following work:
string input = "a long string of text pasted from a .txt file";
But this version does not?
string input =
"
some
large
string ";
I thought C++ doesn't care about whitespace.
| You can do something like this. It's called a raw string literal:
string input =
R"(
some
large
string )";
This will include the endline characters as well. The format is R"(string-literal)"
|
68,788,127 | 68,788,155 | emplace_back an object containing a mutex | I'm trying to create a vector of threads that perform a search. This is the important stuff from my SearchThread class.
class SearchThread {
explicit SearchThread(int t_id) {
id = t_id;
run = true;
thread = std::jthread([&]{
while(run){
{... | std::mutex is not copyable. Its copy constructor is deleted. "Copying a mutex" makes no logical sense. If the mutex is locked, what does that mean? Is the copy-constructed mutex is also locked? If so, who locked it? Who gets to unlock it?
This makes the SearchThread class also uncopyable, and have a deleted copy constr... |
68,788,475 | 68,788,546 | Will if-else statements nest without brackets? | I want to write something utterly ridiculous that calls for a great depth of conditional nesting. The least disorienting way to write this is to forgo brackets entirely, but I have not been able to find any info on if nesting single-statement if-else guards is legal; the non-nested version causes people enough problem... | From cppreference.com:
in nested if-statements, the else is associated with the closest if that doesn't have an else
So as long as every if has an else, nesting without brackets works fine. The problem occurs when an else should not be associated with the closest if. For example:
if ( condition1 ) {
if ( ... |
68,788,543 | 68,788,776 | C++ - how to read file save by ofstream::binanry | Hope you are doing well, I wrote the code to save my txt with number for each line into the binary file named "csdl.bin". Now i would like to read the content from that binary file and show it on the console screen.
saving binary file from txt file
void saveinbinary()
{
ifstream in("csdl.txt", ifstream::in);
of... | Your method of writing integers to a binary file is wrong, use this:
void saveinbinary() {
std::ifstream in("csdl.txt", std::ifstream::in);
std::ofstream out("csdl.bin", std::ofstream::binary);
int number;
while (in >> number) // Read a number from the text file and put it inside 'number', ignoring all... |
68,788,617 | 68,788,636 | What's does the use of "object={number}" in the following code? | class circle
{
private:
double a = 0;
public:
circle(void){}
circle(double);
};
circle::circle(double a){
this->a=a;
}
int main(void)
{
circle c1{ 1 };
c1 = { 8 }; //what does it mean? Anonymous Object?
return(0);
}
What's the difference between the code "c1={8}" and "c1=circle{8}"? Are ... |
What's the difference between the code "c1={8}" and "c1=circle{8}"?
They have the same effect here; both construct a temporary circle which is move-assigned to c1 later.
Both perform list initialization (since C++11), in c1={8} the temporary is copy-list-initialized, in c1=circle{8} the temporary is direct-list-initi... |
68,789,265 | 68,789,413 | std::optional<boost::asio::ip::tcp::socket> initializing using socket.emplace() | I have the following example code, that implements a asynchronous server using boost::asio
I am trying to understand the code. The questions I have regarding the code are as follows
In function async_accept() in class server, the first statement is
socket.emplace(io_context)
From what I understand, this line call the s... | Your understanding of optional is correct.
acceptor.async_accept(*socket, [&] (boost::system::error_code error)
{
std::make_shared<session>(std::move(*socket))->start();
async_accept();
});
Waits for connections and if a connection is made the code inside the bracers is execute... |
68,789,346 | 68,789,376 | Why doesn't this deduce array size? | I'm wondering why this doesn't work when in a struct or class but does ordinarily when declared outside of a struct or class.
enum options { OPTION1, OPTION2};
int main()
{
options opts[] = { OPTION1, OPTION2}; // WORKS
struct DOGG
{
//options opts[] = { OPTION1, OPTION2}; // DOESN'T WORK
... | Data members might be initialized in different ways. Suppose we have:
struct DOGG
{
options opts[] = { OPTION1, OPTION2 }; // default member initializer
DOGG() {} // default member initializer applied
DOGG(int) : opts { OPTION1 } {} // mem... |
68,789,594 | 68,789,626 | C++ can I make a pointer to an array? | Silly question but how do I make a pointer to an array in C++? My understanding is we have a pointer to the first element of an array, but what if we wanted a pointer to that pointer.
int arr[3] = { 1, 2, 3 };
auto arrp = &arr;
cout << arr << " " << arrp << endl;
cout << typeid(arr).name() << " " << typeid(arrp).name(... | Pointers to arrays and function pointers have weird syntax.
int (* arrp2)[3] = &arr;
|
68,789,790 | 68,790,911 | Squared Euclidean distance with Row Major Matrix Eigen C++ | Due to the fact that i plan to pass numpy arrays into my C++ code with pybind11, naturally i would like to compute with Row Major matrices. I found a (one liner) implementation of the squared euclidean distance on stack
typedef Eigen::MatrixXd Matrix;
void squared_dist(const Matrix& X1, const Matrix& X2, Matrix& D) {
... | You can use a templated version of that one-liner function so that it can accept RowMajor as well as ColMajor Eigen::Matrix arguments:
template<class T>
void squared_dist(const T& X1, const T& X2, T& D) {
D = ((-2 * X1.transpose() * X2).colwise() + X1.colwise().squaredNorm().transpose()).rowwise() + X2.colwise().sq... |
68,789,862 | 68,790,118 | How to "reassign" a shared_ptr<base> to a new derived object | I'm writing an interpretive language using C++. Now the problem is I want to implement features like reassignment:
VAR a = [1,"2",[3,4]]
VAR a[0] = 100
In my language, a List is a vector of shared_ptr<Data>, so that you can store different types of data in one list. If someone wants to change an element, I can get the... |
But what I want is to let the shared_ptr "repoint" to a new object. Is it possible?
Yes. Simply assign one shared_ptr<Data> to another, no casting needed:
shared_ptr<Data> &elem = ...;
shared_ptr<Data> value = ...;
elem = value;
Online Demo
|
68,789,984 | 68,790,298 | Immediate function as default function argument initializer in Clang++ | If one uses an immediate function (declared with consteval) for default initialization of a global function argument like here
consteval int foo() { return 0; }
int bar(int a = foo()) { return a; }
int main() { return bar(); }
then Clang compiler issues the error:
error: cannot take address of consteval function 'foo'... | Yes, this is a Clang bug; consider that std::source_location::current is consteval and is meant for exactly this usage.
|
68,790,128 | 68,792,667 | Understanding Linux perf FP counters and computation of FLOPS in a C++ program | I am trying to measure the # of computations performed in a C++ program (FLOPS). I am using a Broadwell-based CPU and not using GPU. I have tried the following command, which I included all the FP-related events I found.
perf stat -e fp_arith_inst_retired.128b_packed_double,fp_arith_inst_retired.128b_packed_single,fp_a... | The normal way for C++ compilers to do FP math on x86-64 is with scalar versions of SSE instructions, e.g. addsd xmm0, [rdi] (https://www.felixcloutier.com/x86/addsd). Only legacy 32-bit builds default to using the x87 FPU for scalar math.
If your compiler didn't manage to auto-vectorize anything (e.g. you didn't use ... |
68,790,700 | 68,790,716 | Is there a better way to check for opposite signs when comparing floats? | So I have this piece of code which checks if two floats are opposite in their signs e.g. one is negative and other is positive vise versa. I feel there must be an easier way to do it than this.
// Checking if force applied is in opposite direction to movement of ball to apply greater force
if (BallVelocityComponent... | std::signbit, this is what you are looking for.
|
68,790,988 | 68,792,267 | Grid nearest neighbour BFS slow | Im trying to upsample my image. I fill the upsampled version with corresponding pixels in this way.
pseudocode:
upsampled.getPixel(((int)(x * factorX), (int)(y * factorY))) = old.getPixel(x, y)
as a result i end up with the bitmap that is not completely filled and I try to fill each not filled pixel with it's nearest ... |
the filled pixel should be no further than 2 pixels from unfilled one, so well implemented BFS wouldn't take long.
Sure, doing it once won’t take long. But you need to do this for almost every pixel in the output image, and doing lots of times something that doesn’t take long will still take long.
Instead of searchin... |
68,791,126 | 68,791,183 | a function that can declare global variables | I am working on a project in c++ that requires me to build a memory model of a variable size. I need to represent each memory cell as a global variable.
for example a memory of size 10000 should be a vector of 10000 global variables of type memory cell named as m0-m9999. (memory cell is a struct I defined).
normally in... | You could use something like this.
Also see : How to implement multithread safe singleton in C++11 without using <mutex>
header file memorycells.h
#include
struct memory_cell
{
};
static std::vector<memory_cell>& cells()
{
static std::vector<memory_cell> cells(100000);
return cells;
}
source file
#include "m... |
68,791,216 | 68,791,494 | Reducing the overlapping count number of buses running from a city to different stopage in straight line, and can my current approach be optimised? | Given pair of distance of start distance and end distance, reduces the number of buses if there is an overlapping in two stopage.
for e.g:
input n=4
{2,8},{6,10},{12,14},{12,20}
output:2
explanation:route {2,8} and {6,10} overlap so it can be reduced to 1 route as {2,10}
similarly route {12,14} and {12,20} overlap it c... | Your error is at if(y.second >= st.top().first). What if st is empty here?
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
bool compare(pair<int,int>p1,pair<int,int>p2){
return p1.first>p2.first;
}
int main(){
int n;cin>>n;
vector<pair<int,int>>v;
for(int i=0... |
68,791,319 | 68,794,755 | Unix domain socket bind failed in windows | I'm running the following code in order to create listener to unix domain socket.
Under macOS this code is working fine, but in Windows it produces the following error from the tcp_acceptor command : WSAEOPNOTSUPP
Here's a minimal reproducible example :
#include <iostream>
#include <boost/asio/local/stream_protocol.hpp... | The issue seems to be the SO_REUSEADDR socket option, which ASIO by default sets. Setting this option itself succeeds, but causes the subsequent bind to fail.
Construct the acceptor with reuse_addr = false, then the binding should succeed:
local::stream_protocol::acceptor acceptor(my_io_context, server, false);
|
68,791,729 | 68,793,983 | gtkmm : Drawing text with cairo | I want to draw a simple text with Cairo in an app using Gtkmm. I want to give the font style (it can be Pango::FontDescription or Pango::Context and so on ...) directly to draw text with Cairo when the Gtk::FontButton is clicked (in other words when the signal_font_set signal is issued). In the example below, I have a ... | Here is a way that works: instead of using a Pango::Context, you can get the font name from Gtk::FontButton::get_font_name and then create a Pango::FontDescription from it. Here is a minimal example to show this:
#include <iostream>
#include <gtkmm.h>
class MyDrawing : public Gtk::Layout
{
public:
MyDrawing();
... |
68,791,769 | 68,791,814 | C++: Create function that returns array size | I want to make a function in C++ that returns size of any array using pointers:
*(&array + 1) - array.
like this:
#include <iostream>
using namespace std;
void arrayLength(string array[]) {
int arraySize = *(&array + 1) - array;
cout << "Size of the array: " << arraySize << endl;
}
int main ()
{
stri... | Nice demonstration why are ordinary raw arrays dangerous.
The issue is with pointer arithmetic and +1. For T* ptr;, ptr+1 advanced the pointer by sizeof(T) bytes, or one T.
In main, &array is of type string(*)[4], so the pointer is incremented by sizeof(string)*4. This leads to the correct size.
On contrary, string arr... |
68,791,964 | 68,793,278 | Can you create a string based dictionary in C++? | I'm trying to make a python-like dictionary in C++, and using was suggested many times but in my case i want to label my lists with words instead of "1, 2, 3, 4...", is that possible?
Example dict:
"Cookie": "sugar", "chocolate", "flour"
"Pie": "milk", "apples", "flour"
etc etc
| You can do something really beautiful like this using the data structure proposed by @Retired Ninja. You can use unordered_map instead of map for better performance, since the order of the indexes doesn't matter:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main()
{
uno... |
68,792,023 | 68,792,883 | How does the compiler copy member data that are arrays? | AFAIK, an array cannot be copied nor assigned so:
int a[5] = {1, 2};// 1 2 0 0 0
int b = a;// error
b = a; // error
But how does the compiler copies arrays that are member data of a class/struct type through the trivial copy-ctor and copy-assignment operator?
// trivial struct
struc Arr{
int arr_[7];
};
Arr a = {... |
So does the compiler does something like: this->arr_ = rhs.arr_?
No. As you said, this wouldn't compile.
Or it iterates over all elements of rhs.arr_ and copy-assign them to their coresponding elements in lhs?
For the copy assignment operator - yes.
For the copy constructor - no. There, each element is copy-constru... |
68,792,093 | 68,792,138 | I don't know why I can't reach answer. (c/c++) | I am a student just learned c&c++ a little. I want to print arData[3][4]. Also, I want to solve this question with only one 'for' phrase. (not to print, to make array) What could I have been wrong? Thanks for letting me know.
I want to print like this.
1 2 3 4
5 6 7 8
9 10 11 12
But print now
9 10 11 12
0 0 0 0
... | 0 < nData <= 4 is not a correct comparison in c++, you should do 0 < nData && nData <= 4, where && denotes logical AND operator. Here is the fixed code:
#include <iostream>
int main () {
int arData[3][4]{};
int nData{};
int nIndex1{};
int nIndex2{};
nData = 1;
for (int i = 0; i < 12; i++)
... |
68,792,104 | 68,792,208 | Accessing a class variable in another class shows a different behavior in C++ | I am a newbie in C++. Here in my case I have created two classes, class One and class Two. _x is declared as a private member variable of class One. So here I am trying to learn different methods to access this private variable(_x) from any other class(Here in this case it is class Two). This is my scenario basically. ... | The problem in your code is that you pass to Two an instance of class One by value. This means that Two stores a copy of the instance of One you pass to it. When you change the value of _x in one it does not affect the value of _x in _a (inside two).
In order for your code to work you need to pass a reference to One in... |
68,792,210 | 68,792,347 | Using "unsigned short" data type breaks loops | I was making a simple C++ code that takes multiple lines of input, the first line defines how many numbers the user will enter, then he enters them all, the code will reverse every number of them and print the reversed version of every number space-separated, the surprise I faced is that, for some reason, using unsigne... | An unsigned type can never be less than zero. The language standard supports underflow/overflow to wrap to the opposite end of the domain in both scenarios. Eg:
#include <iostream>
int main()
{
unsigned short i = 0;
--i;
std::cout << i << '\n';
}
Output
65535
Therefore, you can put any legal value you wa... |
68,792,317 | 68,792,499 | Vector of square root no printing in C++ | I am having trouble making a vector that would return the original elements of a vector squared.
This is the error I am getting.
no operator "<<" matches these operands -- operand types are: std::ostream << std::vector<int, std::allocator<int>>
#include <iostream>
#include <vector>
#include <cmath>
void squareRoot(std... | You can define the << operator for vector<int> (or as a template for vector<T>). Insert the following code before squareRoot:
std::ostream& operator<<(std::ostream& os, const std::vector<int>& v) {
os << "[";
bool first = true;
for (const auto& x : v) {
if (first) {
first = false;
... |
68,792,804 | 68,792,984 | Using accumulate to calculate alternate sum | If I use the accumulate function in C++ like the below
std::vector<int> v2{1, 2, 3, 4, 5};
int sum = 0;
std::cout << std::accumulate(v2.begin(), v2.end())
It will simply sum all the numbers. But I wanted to calculate 1-2+3-4+5
I was thinking of some way to accumulate 1,3,5 and 2,4 separately and then do it
But no... | This is my quick solution :
int sign = -1; // start with minus first (e.g. 1-2)
std::vector<int> values{ 1, 2, 3, 4, 5 };
auto value = std::accumulate(values.begin(), values.end(), 0, [&sign](int total, int value)
{
sign = -sign;
return total + (sign)*value;
});
|
68,792,971 | 68,793,120 | Reading paragraph in file line by line using getline() function and using while loop with codition fin.eof() but result is infinte loop | ben_stokes.txt
The great Irish sports writer Con Houlihan used to say that every team should have a redhead.
And it's true that Ben Stokes' combative nature, allied to his powerful frame and outrageous talent,
lifted England to another level. Never was that more true than when he secured his place in English
cricket... | Calling clear will reset the eof flag, so the condition of the while-loop will always evaluate to true. Call clear before getline and the code will work.
|
68,793,079 | 68,793,249 | Pointer always shows the same value C++ | This ain't any problem but, I have a C++ program and I want to print the memory address of a variable (the pointer) but it always shows the same values.
Here's a snippet of my code
#include <iostream>
int main() {
int a = 90; // any random value returns the exact same pointer
int* b = &a;
std::... | This is dependent on the kernel. The exact thing is Address space layout randomisation (ASLR), and is used to stop a buffer overflow attack. I do not know the specifics of Win10, but linux generally has ASLR enabled by default
In a very basic overview, what happens is that when the program is loaded it will have severa... |
68,793,177 | 68,793,848 | C++ function returning different types | I was trying to make a function where based on the parameter the function returns the value, like this:
type getValue(string input) return <OUTPUT>
OUTPUT's type would be changed to int, string, bool, etc., on what the input is given. I got that sorted but the problem that I've been having is the return type. I've tri... | As the comments point out, you'll need to use a std::variant or std::any as a return type.
std::any getValue(string input) {
if (input == ...) {
return "string return type";
}
if (input == ...) {
return 100;
}
if (input == ...) {
return 123.456;
}
return false;
}
Ho... |
68,793,323 | 68,793,396 | c++ new without storing object | I've taken over some legacy C++ code (written in C++03) which is for an application that runs on an RTOS. While browsing the codebase, I came across a construct like this:
...
new UserDebug(); ///<User debug commands.
...
Where the allocation done using new isn't stored anywhere so I looked a bit deeper and found this... | If you look into the constructors of those classes you’ll see that they have interesting side effects, either registering themselves with some manager class or storing themselves in static/global pointer variables á la singletons.
I don’t like that they’ve chosen to do things that way - it violates the Principle of Lea... |
68,793,587 | 68,793,649 | C++ exception thrown | I am learning C++ and have lost quite some time trying to solve to understand the reason of the error i am getting.
When i run the code below i am getting an Exception thrown. It happens when the program ends, so i believe it's related to the Edge pointer:
#include <iostream>
#include <vector>
#include <map>
using nam... | Edge *edge = new Edge[E * sizeof(Edge)];
Unless E is initialized, this multiplies an uninitalized variable by sizeof(Edge) (which is also wrong on its face value as well, but we'll get to it later). This is undefined behavior.
Graph::Graph(int Ver, int Edg) {
V = Ver;
E = Edg;
}
This isn't good enough. The d... |
68,794,418 | 68,795,706 | Empty String when sending a String value using WM_COPYDATA in JNA | I am trying to send a String from Java (First app) to c++ (the Second app with a message-only window).
So firstly, what I tried is this:
I adapted this example into my code and got this on the java side
STRMSG msg = new STRMSG();
msg.message = "test";
//msg.write(); // Idk exactly why because i thought JNA ... | Ok, basically, after the help of Remy Lebeau (as always), I managed to include the NativeString Class in my project, which allows me to get the Pointer of the NativeString and use it directly in my COPYDATASTRUCT.
I had to inline some method contents in my own NativeString Class because some of them were also not visib... |
68,794,583 | 68,794,611 | Strange output of __cplusplus when enabled c++17 | I am doing some experiments here with metaprogramming and initially the idea was to find out if we can make sorted integer sequence unique at compile time. (This is unrelated to the question though)
I have enabled c++17 in my properties (I use VS2019) and this program gives me strange output when I want to find out the... | In Visual Studio, you must enable /Zc:__cplusplus in order to get the appropriate values.
This has something to do with backwards compatibility.
|
68,794,809 | 68,794,943 | Libcurl and user-defined functions for receiving/sending | I have my own functions for receiving and sending data to the network, based on WinSock, but I really don't want to implement text protocols myself, such as HTTP/HTTPS. I would like some good library to do it for me, for example Libcurl.
However, for example, if I make a GET request using libcurl, libcurl uses its own ... |
Does libcurl allow, somehow, to replace its functions for receiving and sending to use other user-defined functions?
No, it does not.
|
68,795,626 | 68,795,978 | vscode doesn't recognize extension .cpp.in | I've been recently learning cmake and I want to use the command configure_file to generate .cpp file because I need dynamic values created from cmake variables in my source files. However, it seems that VSCode doesn't recognize the extension .cpp.in, therefore the editor doesn't show any autosuggestion or highlight. Bu... | You have to associate the extension with the language.
In Settings, search for Files:Associations. Select the Add Item Button and specify *.in as key and cpp as value. From now on all files with the extension .in are associated with c++. I don't know if *.cpp.in will work, you have to test that on your own.
More Info:... |
68,795,849 | 68,795,970 | Not able to insert different values of struct into Map | I use Node to hold (x, y) of coordinator and try to insert 4 nodes into map. The following code only print 2 nodes, why?
{0,0}, 0
{1,2}, 3
If i change the code of overload operator '<' with
bool operator<(const Node &ob) const
{
return x < ob.x or y < ob.y;
}
It prints all 4 nodes. My understanding the opera... | std::map considers two element to be equal if for two keys a and b, the comparator (in your case, the default, std::less) fulfils
!comp(a, b) && !comp(b, a)
Let's check your case:
First you insert the key Node<int, int>(0, 0), then the key Node<int, int>(0, 1). For these elements (and your operator<) the following hol... |
68,796,369 | 68,796,955 | Why the 'declaration of a single variable' in the 'condition' part of the 'for loop' syntax from cpp reference doesn't end up with a semicolon? | https://en.cppreference.com/w/cpp/language/for
a declaration of a single variable with a brace-or-equals initializer. the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.
I do noticed that only the concept of simple declaration is clearly... | I encounter this question when reading Cpp primer, it states:
The syntactic form of the *for statement* is:
for (*init-statement condition;expression*)
statement
And I mistakenly thought it missed a semicolon after init-statement. By reading other materials I make out it but came the question above.
In t... |
68,796,371 | 72,324,686 | Is there a Catch2 variable that provides the name of the current test? | I'm using Catch2 for unit tests and I would like to know the name of a C++ or environment variable that reveals the name of the current test that is executing.
Is there a way to do this, or is it bad form to have the test debugging code print the name of the test in which it is running? Ideally I'd like to print it usi... | I think your scaffolding idea is the way to go. I have not found any macros that would return the name without having to define an extra variable.
When it comes to the class that is being instantiated for a test case:
struct AutoReg : Detail::NonCopyable {
AutoReg( Detail::unique_ptr<ITestInvoker> invoker, SourceLi... |
68,796,540 | 68,796,610 | providing a reference-type argument for pass-by-reference c++ function | I have a very boring question.
I thought, when you do pass-by-reference for a C++ function, you literally have to pass a reference-type argument (or parameter?). But I saw in the resource that I am learning from, and all over the web basically, that I was wrong.
So, what is the real difference between these two and why... | C++ has a lengthy, and occasionally confusing list of rules by which objects of one type are automatically converted to objects of some other, related type.
For example, you might have a function that takes a const char * as a parameter, such as:
size_t strlen(const char *);
Despite that its parameter is a const char ... |
68,796,901 | 68,797,823 | "SERVICE_CONTROL_SESSIONCHANGE" notification is never received in C++ service application in Windows 10 | I have been trying to develop a service application to hook into the login/logout event of windows. My development environment is Windows 10. As it is a service application, based on suggestion from some of the existing posts in Stackoverflow and other dev platform, I have registered the service to get notified in diff... | To receive SERVICE_CONTROL_SESSIONCHANGE notifications in your HandlerEx callback, you need to call SetServiceStatus() with the SERVICE_ACCEPT_SESSIONCHANGE flag enabled in the SERVICE_STATUS::dwControlsAccepted field.
Control code
Meaning
SERVICE_ACCEPT_SESSIONCHANGE 0x00000080
The service is notified when t... |
68,796,903 | 68,797,607 | Generate specific random number | I am trying to create a method that generates a random number from a specific selection of numbers, it must be either 0, 90, 180 or 270.
This is the method I have so far to generate a random number between a certain range, but I am not sure how to generate a random number from a specific selection.
int randomNum(int mi... | Umm, So as I think you're trying to choose a specific number in a array or so called a list of options, I've a quick example for you here. You can just create a array with all your options and make this method to return a value from the given array.
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main ()... |
68,797,454 | 68,797,486 | create a queue with multiple data types | I want to be able to have a queue class that can accept "any" preferred data type wether that is a CURL type or just a std::string type. Queue of strings or queue of curl handles if you will.
#pragma once
#include <iostream>
#include <queue>
#include <string>
#include <mutex>
#include <condition_variable>
#include <ch... | If you want to have a single object corresponding to a single type. You must use Template Classes:
template <typename T>
class SafeQueue {
public:
std::condition_variable ready;
std::mutex queue_lock;
std::queue<T> safe_queue;
uint8_t empty();
void initialize();
void put(T& element);
T get(... |
68,797,467 | 68,797,854 | Why the count in my main is not updated when i entered new patient info? | Why the count in my main is not updated when I entered new patient info? I don't know why for case 2 in my add function, the count in main will never increase. It remains at 20 only(same with my input text) even after I type in new patient info.
Here is my code:
struct PATIENT
{
string id;
string name;
stri... | This is c++ operator precedence. See e.g. https://en.cppreference.com/w/cpp/language/operator_precedence
Change *count++ to (*count)++. If you don't do this, your code is equivalent to *(count++), which is valid c++, but it just does nothing...
But I would rather pass an int reference to the functions, and not a pointe... |
68,797,630 | 68,797,671 | hold reference object inside std::optional | I am having issue when trying to pass a reference object inside std::optional as a function argument.Does it not support storing reference objects ?
Example -
void fun(std::optional<ClassA& obj>)
What exatly does this error mean -
static_assert failed due to requirement '!is_reference
static_assert(!is_reference_v<_Tp... | The cpp reference states quite clearly:
There are no optional references; a program is ill-formed if it
instantiates an optional with a reference type. Alternatively, an
optional of a std::reference_wrapper of type T may be used to hold a
reference.
So use std:reference_wrapper as suggested.
Footnote: there are movem... |
68,800,577 | 68,801,477 | How to properly use concepts? | Currently, I am learning C++ and decided just start with C++20. However, these codes are driving me crazy, since I don't think the result makes any sense.
The following code will have the sentence Valid array. printed. What I meant above is that this is not right. It shouldn't print the sentence at all, since the type... | So, two things.
You are using simple requirements (the extra {} make those compound requirements technically, but since you don't use any optional feature of those, it's equivalent to a simple requirement). Those mostly verify that an expression is syntactically valid. Its value is immaterial to them. What you want is... |
68,800,748 | 68,800,922 | Add const to pointer type | Say I have a class template:
template <class T>
struct A
{
T value;
void foo(auto fun) {
fun(value);
// ^^^^^^^ Pass value as a const object
}
};
I want to add const to the value, when calling fun so that only functions that accept T, T const&, T const* are callable. My initial approach was to make foo... | You can
fun(static_cast<std::conditional_t<
std::is_pointer_v<T>,
std::add_pointer_t<std::add_const_t<std::remove_pointer_t<T>>>,
std::add_const_t<T>
>
>(value));
Then when T is MyData*, the converted type would be MyData const*... |
68,801,286 | 68,820,373 | Call static function of specialize template with base class of type T | I need to write Stream class with a template Write function to accept any type and write it to stream.
I write a Stream class and a StreamWriter to partially specialize Write function, but compiler can't find static function of StreamWriter with base class of AInt class.
template<typename T>
class AType {
public:
T ... | I solve the problem with c++ concept.
IsAType is a concept that accepts all subclasses of AType.
template<typename T>
class AType {
public:
using RawType = T;
T rawValue;
void Add(T v) { rawValue += v; }
void Sub(T v) { rawValue += v; }
void Mul(T v) { rawValue *= v; }
void Mod(T v) { rawVal... |
68,801,644 | 68,802,168 | Callback function in a templated function accepting variable argument type using `switch` statement | I am trying to call a callback function from within a templated function. But the arguments for the callback function depend on switch statement.
Here's the working code which explains what I intend to do using a toy example.
#include <vector>
struct A {};
struct B {};
struct C {};
struct D {};
enum class StructType
... | As your errors say, there are no matches for callback functors you haven't created.
I suggest removing the runtime argument to process and using the information you have in the function template parameters only.
Example:
#include <vector>
#include <type_traits>
struct A {};
struct B {};
struct C {};
struct D {};
// e... |
68,802,030 | 68,802,165 | Porting python code to C++ / (Printing out arrays in c++) | I am currently learning C++ and being quite proficient in python, I decided to try porting some of my python code to C++. Specifically I tried porting this generator I wrote that gives the fibonacci sequence up to a certain given stop value.
def yieldFib(stop):
a = 0
b = 1
yield i
for i in range(2):... | An integer array of size 10000000 is generally too large to be allocated on the stack, which causes the crash. Instead, use a std::vector<int>. In addition to that:
The variable b is unused.
fibN is not initialized. Its value will be indeterminate.
Returning a pointer to stack memory will not work, as that pointer is ... |
68,802,244 | 68,802,720 | C++ how to convert string characters to exact hex bytes | To start off: I have an app that takes a byte array and loads assembly from it.
My idea, to prevent (easy)piracy, was to have an encrypted string on server, download it on client, decrypt it to get for example:
std::string decrypted = "0x4D, 0x5A, 0x90, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4";
Then to convert from string to bina... | Use std::stoul to interpret a string as an unsigned integer. The unsigned integer can then be cast to a uint8_t type.
One method of parsing the entire string is by using a stringstream.
Code example:
#include <cstdint>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
// Input... |
68,802,505 | 68,802,699 | why is_standard_layout gives true here? | my understanding is that not having any virtual method is one of requirements for standard layout. however, following code prints out true while there is a virtual method in struct Cancel.
if I remove the virtual method. is_stand_layout returns false which makes sense, as Cancel has members with different access contro... |
is this a bug?
No.
is there something I am missing
You're outputting std::is_standard_layout_v<std::variant<NewOrder, Cancel>> which determines whether std::variant<NewOrder, Cancel> is standard layout rather than whether Cancel is standard layout.
why is_standard_layout gives true here?
Whether std::variant<NewO... |
68,802,905 | 68,803,007 | Reading numbers from a text file to an array prints unexpected values | I'm writing a program that print an array to a text file, then read that array from that text file to another array, this is my program:
#include <iostream>
#include <fstream>
using namespace std;
void PrintToFile(int arr[], ofstream& PrintFile)
{
for (int i = 0; i < 10; i++)
{
arr[i] = i;
Pri... | You can only open a file once, so all your reads fail and the array is left with indeterminate values.
While you can open for both reading and writing at once, it's more common (and has fewer surprises) to close after writing and only then open for reading.
This should work:
ofstream PrintFile("output.txt");
PrintToFil... |
68,802,968 | 68,803,104 | Why do I get the same data with a different seed? | For some reason, seed=0 and seed=1 give the same result, while I expect it to be different.
For different results everything works as expected, the problem arises only with 0 and 1 seeds.
Is it a bug or I don't understand something?
Code for reproduce. I tried it on gcc and g++ compilers.
#include <vector>
#include <ra... | This "oddity" can likely be explained simply by noting that the PRNG you use, std::default_random_engine, is not very good.
Here is your code again, except now it compiles (was missing #include <iostream>) and using std::mt19937 instead:
#include <vector>
#include <random>
#include <cstdint>
#include <iostream>
int ma... |
68,803,048 | 68,804,346 | Qt Grid Layout doesn't fit into Scroll Area | I am trying to put a grid view that will contain some buttons into a scroll area but I don't know why the grid layout only fits into the initial size of the scroll area (it doesn't go downside so I could use the scroll bar to see all elements).
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
QGridLay... | I fixed it by this way:
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
QGridLayout *lay = new QGridLayout(ui->centralwidget);
lay->addWidget(ui->scrollArea, 0, 0, 1, 1);
auto gridLayout = new QGridLayout(ui->scrollAreaWidgetContents);
gridLayout->setObjectName(QString::fromUtf8(... |
68,803,517 | 68,805,624 | How to create a button when another button is pressed and hide the other one | (Questions are at the bottom)
I am trying to write a program, which has one button. If this button is pressed, it should create a new button, and delete the other one, you will see here:
constexpr unsigned int button1=111;
constexpr unsigned int button2=112;
bool buttonIsPressed = false;
LRESULT CALLBACK WndProc(HWND ... | You are close. You already know to create individual buttons (CreateWindowEx()). In the code you have shown, you just need to move the 2nd CreateWindowEx() from the WM_CREATE handler into the WM_COMMAND handler, being sure to check the reported ID/HWND to make sure it is the 1st button you are interested in, and then... |
68,804,939 | 68,804,992 | In C++ programming, is the main() function static like in java or non-static like in C? | In C++ programming, is the main() function static like in java or non-static like in C?
| From https://timsong-cpp.github.io/cppwp/n3337/basic.start.main#1
A program shall contain a global function called main, which is the designated start of the program.
It cannot be a static function.
|
68,805,010 | 69,148,827 | How to check if a cognito access token has expired? | The access token is valid for 1 hour.
I know how to use a refresh token to update an access token.
However, I don't know how to check if the cognito access token has expired.
Pattern1: Measure the time since token authentication by timer thread.
-> Waste of CPU resources...
Pattern2: Record the authentication time & Co... | I choose retrying by try-catch.
Because, If I use the timestamp, I should to use retrying for fail safe in the end.
thanks.
|
68,805,558 | 68,805,905 | std::enable_if to choose a class specialitzation | I'm tyring to understand std::enable_if and the benefits of using it over a static_assert / regular template specialitzation.
After reading around I found:
This is useful to hide signatures on compile time when a particular condition is not met, since in this case, the member enable_if::type will not be defined and at... | You cannot overload class templates like you can function templates, buy you can partially specialize them (which you cannot do with function templates):
#include <ios>
#include <iostream>
#include <type_traits>
class Interface
{};
class Foo : public Interface
{};
template <class T, typename = void>
struct C
{
//... |
68,805,639 | 68,805,699 | Undefined reference GCC compilation | I am new to Linux and I am trying to learn how to run and debug my programs using GCC and GDB. I set my Visual Studio Code to run and debug C/C++ programs and I wrote a simple code that implements a list. When I hit Run>Start Debugging in VSC everything works fine and the output is as expected.
However I want to compil... | Use g++ to compile C++ code. gcc is for C code. The undefined references are the result of gcc not linking to the C++ standard library.
|
68,805,722 | 68,805,807 | C++: How can I forward-declare derived classes that appear in a static method of a base class? | Just doing a simple exercise where I'm translating ideas I learned from another language to C++.
I have an abstract class Number, which has two derived classes, PositiveNumber and NegativeNumber. Number has a static method that should create a new instance of either PositiveNumber or Negative number, depending on the s... | The definition of fromInt() needs to know what constructors PositiveNumber and NegativeNumber have, so forward declarations are not enough. You need to break up the declaration and definition of Number::fromInt(), and then you can move the definition underneath the declarations of PositiveNumber and NegativeNumber.
Al... |
68,806,059 | 68,806,120 | Multi-inheritance with interfaces type casting on pointers for using with std::list | I come from Java (OOP) background. I made a simple class to illustrate my problem:
#include <list>
#include <string>
#include <iostream>
// classes
class InterfaceA
{
public:
virtual std::string functionA();
};
class InterfaceB
{
public:
virtual std::string functionB();
};
class DerivedAB : public InterfaceA... | C++ is far different from Java!
I have obviously a type casting error.
You are right about this (aka. type mismatch)! The std::list is a standard template container which gives you a concrete type, when you instantiate with a template argument.
That means, the std::list<InterfaceA*> is different from std::list<Deriv... |
68,806,359 | 68,820,482 | Why does storing an 32-bit unsigned int value of -1 in SQLite DB and reading it back result in the value getting changed to half? | In its simplest form, below is a pseudo code of the problem:
enum E { VALUE = -1; }
uint32_t value = VALUE; // signed to unsigned conversion without typecasting
SQLiteDB.INSERT(<table containing `value`>);
SQLiteDB.SELECT(<same table as above>);
In the DB, I see that the value is stored as 4294967295 (i.e. 0xFFFFFFFF... | Found the issue.
I am using a library code to read the DB tables. Which gets the values in form of string properly. Further std::stoi() is used for converting to the desired uint32_t.
Now 4294967295 is too big of an integer for an std::stoi(). In fact in Ubuntu 64-bit machine, it throws an exception. However in Windows... |
68,806,376 | 68,806,542 | Use the default constructor of T for the default initial value |
Write a function template that takes a single type parameter (T) and accepts four function arguments: an array of T, a start index, a stop index (inclusive), and an optional initial value. The function returns the sum of all the array elements in the specified range and the initial value. Use the default constructor o... | It means something like the following
template <typename T>
T sum( const T a[], size_t start, size_t stop, const T &init = T() );
where the default value of the fourth parameter is created using the default constructor of the type T.
|
68,806,614 | 68,807,006 | Do we really need to implicitly convert ranges adaptors to bool? | Since ranges::view_interface has an explicit operator bool() function, this makes most C++20 ranges adaptors have the ability to convert to bool:
https://godbolt.org/z/ccbPrG51c
static_assert(views::iota(0));
static_assert("hello"sv | views::split(' '));
static_assert(views::single(0) | std::views::transform([](auto) {... | From this blog post by Eric Niebler, whose range-V3 library heavily influenced C++20 ranges
... custom view types can inher[i]t from view_interface to get a host of useful member functions, like .front(), .back(), .empty(), .size(), .operator[], and even an explicit conversion to bool so that view types can be used in... |
68,806,670 | 68,807,533 | Trouble Playing Youtube Videos with libwebkitgtk-4 | Whenever I try to browse to a youtube video using the libwebkit2gtk library in Ubuntu 18 LTS, I'm met with a "Your browser can't play this video". I see that other browsers that use this library can play youtube content just fine (org.gnome.Epiphany).
Can someone point me in the right direction as to what I'm missing?
... | It turns out that I needed the gstreamer1.0-libav package installed. After I install this through apt, my program started playing youtube videos with no issue.
sudo apt install -y gstreamer1.0-libav
|
68,806,759 | 68,808,119 | Is there a way to update a pair in a vector of pairs in C++ | This function tries to find a way for plan a journey given two vectors A and B, A[i] being the source of a trip and B[i] being the destination of a trip.
Here is the code but it seeming to get on an infinite loop since the value in pair doesn't get updated.
vector<string> solve(vector<string> A, vector<string> B) {
... | Your code is making a lot of copies of all of the objects involved, so it makes sense that trying to make modifications of those objects is not having the effect you want. You need to make use of references/pointers to avoid those copies.
Try something more like this instead:
vector<string> solve(const vector<string> ... |
68,806,802 | 68,806,946 | Duplicating wide-character string | I am trying to create an application in which I have a function where I am trying to duplicate a wide character string. I am currently using _wcsdup(), since it is a Windows application and everything is working fine for me. But I need to create a multi-platform function, so _wcsdup() (which is a Windows function) will... | The standard cross-platform equivalent would be to allocate/free a wchar_t[] buffer using new[]/delete[] (or, if absolutely needed, malloc()/free() to mirror the behavior of _wcsdup()), using std::copy() or std::memcpy() to copy characters from wstring into that buffer, eg:
std::wstring w = wstring.str();
wchar_t* out ... |
68,806,890 | 68,919,912 | How to link Google Test with premake5 | I want to link Google Test (https://github.com/google/googletest) with my project. I added gtest as submodule in following directory:
%{wks.location}/sengine/vendor/gtest
I have following premake5 script in gtest directory:
project "gtest"
kind "StaticLib"
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}... | googletest expects that the directory googletest/include dir is a root include directory. You can infer this because <> are used (compared to "" for relative paths in the project) and the path is given relative to this directory in gtest-all.cc.
I work more with CMake an have no experience with premake5 but usually you... |
68,807,436 | 68,807,904 | Why do I keep getting undefined reference using SFML in VSCode? | I'm tried compiling this program copied from the sfml tutorial
#include <SFML/Graphics.hpp>
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's ... | Turns out I got the wrong version of SFML. It works perfectly now, thanks!
|
68,807,622 | 68,807,835 | Minimum syntax to guarantee no dynamic memory with std::function | Quite often I want to write higher order functional code like
void f(int value, const std::function<void(int)>& callback);
int x, y=5;
f(y, [&](int result) { x = result; });
In cases like these, I would like to be able to guarantee that the std::function constructor does not allocate any memory. The guarantees in th... | There are no guarantees of allocations (or lack of thereof) specified in the standard for std::function constructors. Most you can hope for is a recommendation, from 20.14.17.3.2:
Recommended practice: Implementations should avoid the use of
dynamically allocated memory for small callable objects, for example,
where f... |
68,807,973 | 68,809,176 | Segmentation fault DPDK | I've written a sender application using dpdk libraries.
struct my_message{
struct rte_ether_hdr eth_hdr; // the ethernet header
char payload[10];
};
*/ Sender Application */
void my_send(struct rte_mempool *mbuf_pool, uint16_t port, uint64_t max_packets)
{
int retval;
struct rte_mbuf *bufs[BURST_SIZE];... | As per the provided source code and debug printouts, every time rte_eth_tx_burst() fails to send the whole batch of 256 mbufs, your program leaks unsent packets. The loop reiterates thus overwriting mbufs. The leak subsequently grows, and the mempool runs out of available objects. At some point rte_pktmbuf_alloc() retu... |
68,808,164 | 68,836,057 | Not able to get some autosuggestions for inner class members in std::map in visual studio code (Intellisense) | I am currently making a reverse map class bidir_map. The code can be compiled using GCC in the terminal so the types and members should be in scope but Intellisense is not giving autosuggestion for specific parts of the code e.g. std::pair<K,V> members (but it does give suggestions to std::map members). What is the rea... | IntelliSense is unable to give names of members which are dependent on template parameter types. Example: A certain member function might exist for most template parameter types but for certain types the class might have a specialization that has no such function defined. Since we haven't provided any concrete types ye... |
68,808,195 | 68,808,318 | Overload of variadic template function with another template | I am trying to figure out how to "overload" a variadic function template with a "more specialized" variadic function template. For example:
#include <iostream>
template <typename... ARGS_>
void foo(void(*fn)(ARGS_...)) {
std::cout << "Generic function pointer foo" << std::endl;
}
struct Test {
};
template ... | SFINAE'd overloads based on the last parameter pack argument
You can add mutually exclusive overloads based on whether the last type in the variadiac parameter pack is Test* or not:
#include <type_traits>
template <typename... Ts>
using last_t = typename decltype((std::type_identity<Ts>{}, ...))::type;
struct Test {}... |
68,808,248 | 68,814,852 | Not able to debug my c++ code in visual studio code | I don't what happened to my vscode all of a sudden I am not able to debug files although I am to run my CPP program but not able to debug please help me I spend 2-3 hours continuously trying to fix my debugger
my program is running fine and compiler is creating a exe file as shown below
when I hit the debug button thi... | Deleting the
%USERPROFILE%.vscode\extensions\ms-vscode.cpptools-1.6.0-insiders\install.lock
%USERPROFILE%.vscode\extensions\ms-vscode.cpptools-1.6.0-insiders\debugAdapters
worked for me. Windows 10
for more information Please see: https://github.com/microsoft/vscode-cpptools/issues/7971
|
68,809,603 | 68,809,760 | Aggregate vs non-aggregate structs/classes | I am trying to understand what an aggregate class/struct/union is: Here is from the C++ standard:
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no b... | The rules for what is and what is not an aggregate has changed a lot over various standard versions. This answer briefly highlights the changes related with OP's three questions. For a more thorough passage, see e.g. The fickle aggregate, which walks through these different rules along with the correct standard (versio... |
68,810,670 | 68,810,697 | Problem returning unsigned char value from C++ dll to C# | In the following example, I try to concatenate two unsigned chars(which is the requirement) by passing the values to a C++ dll and return a single string. The output I'm getting is not right.
C#:
using System;
using System.Runtime.InteropServices;
using System.Text;
class HelloWorld
{
[DllImport("cpp_func.dll")... | The memory for c array is allocated in the concat_fun function and has a scope and lifetime of this function, so the memory is released when you leave the function body.
Try to allocate c array in the calling function Main or use dynamic memory allocation: new/delete or malloc/free in concat_fun.
|
68,810,718 | 68,810,750 | Deleting NULL pointer memory | I've encountered strange, unbelievable problem.
I wrote a program in which structure is reallocated several times.
The pointer is initially NULL, and before allocation it is checked whether NULL or it is deleted.
But, I've made a mistake here.
I wrote like this if (!pConfig) delete pConfig;, which means it is never del... | Yes, you got memory leaks here. Memory leaks are common problems, but they won't cause your program to be killed immediately, sometimes when the system memory is running out, the OS will kill other programs that are not leaking, they are victims.
Delete a NULL pointer is always safe, and it's duplicated. What you have ... |
68,811,149 | 68,960,327 | How to efficiently (without looping) get data from tensor predicted by a torchscript in C++? | I am calling a torchscript (neural network serialized from Python) from a C++ program:
// define inputs
int batch = 3; // batch size
int n_inp = 2; // number of inputs
double I[batch][n_inp] = {{1.0, 1.0}, {2.0, 3.0}, {4.0, 5.0}}; // some random input
std::cout << "inputs" "\n"; // print inputs
for (int i ... | It is necessary to make a deep copy as follows:
double outputs_data[batch];
std::memcpy(outputs_data, outputs.data_ptr<dfloat>(), sizeof(double)*batch);
|
68,811,586 | 68,811,624 | Does C++ guarantee the minimum number of std::placeholders::_N? | According to cppref:
The std::placeholders namespace contains the placeholder objects [_1, . . . _N] where N is an implementation defined maximum number.
I just wonder:
Does C++ guarantee the minimum number of std::placeholders::_N?
| No, there is no guaranteed minimum number of placeholders. [func.bind.place] explicitly calls out the number as an "implementation-defined number of placeholders."
However, it is likely that you will have access to 10 different placeholders, as [implimits] says:
The bracketed number following each quantity is recommen... |
68,811,604 | 68,811,626 | Segmentation fault (core dumped) - C++ Error | I am trying to write a simple code of vector addition and I am getting this error. I don't know what it is. I am using VS Code in Ubuntu 18.04.
int main(){
std::vector<int> vect1 = {1,2,3,4,5};
std::vector<int> vect2 = {6,7,8,9,10};
std::vector<int> vectsum;
for (int i = 0; i < vect1.size(); i++){
... | You haven't allocated any memory for vectsum (so you're hitting a NULL pointer when you assign a value to one of the elements)
std::vector<int> vectsum(5);
|
68,811,758 | 68,811,853 | How do I make a virtual variable? | I know there's virtual functions, but no virtual variables. It wasn't added probably because it wasn't needed most of the time, but I've ran into a problem lately:
class A
{
public:
int bar;
};
class B : public A
{
public:
float foo;
};
class C : public A
{
public:
double foo;
};
int main()
{
std::ve... | why dont you use virtual getter in both classes?
like : virtual int getA() and virtual int getB()
it will be easier for you to access those variables then :)
|
68,812,248 | 68,812,309 | C++: Calling a specific funtion within a class via the main function | I have 3 classes and each has a function within them, I want to call these functions specifically via a number-driven menu from within the main function. For example, if the user chooses New accounts I want to redirect him to the New accounts function. What I wanna know is how can you exactly call a specific function (... | Your approach is correct and widely used. For 3 functions/methods (and more) a switch would be a bit more convenient:
switch(menu_input)
{
case 1:
account.newAccount();
break;
case 2:
other.method();
break;
case 3:
yet_another.method();
break;
}
PS: account.newAccount() sounds and looks like a ... |
68,812,281 | 68,814,374 | Is the initializer of a constexpr variable at class scope allowed to reference the variable? | The following code:
struct S {
static constexpr int rolling_sum[4]{
0,
rolling_sum[0] + 1,
rolling_sum[1] + 2,
rolling_sum[2] + 3
};
};
is accepted by clang (tested with version 12), but rejected by gcc (tested with version 11) with the following errors:
test.cpp:4:9: error: ‘ro... | You aren't missing anything. This is GCC bug 99059, reported in GCC 11.
Your case applies too, since just like static inline, a constexpr variable must be initialized at the point of declaration. The same lookup related bug would affect C++14 code as well.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.