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 |
|---|---|---|---|---|
67,159,458 | 67,160,386 | I need to calculate the arctan(x) and the result is showing "nan", what is wrong with my code? | So the value that im getting is "nan" and i suspect something is wrong in my while statement.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{ int n=1,c=0;
float x;
double sum=0, old_sum, diff=1000000,eps;
cin>>x>>eps;
while(abs(diff)>=eps){
old_sum=sum;
sum=sum... | There are several issues in your code:
You don't take into account that the formula is only valid for abs(x) <= 1. This can be solved by a little mathematical trick
You don't check that the formula converges effectively. This can be done with a test of the value of n
You are repetidly using the pow(.) function. This i... |
67,159,497 | 67,159,536 | Parentheses inside template arguments e.g. std::function<int(int, float)> | I was reading about std::function in part 3 this (long) answer on callbacks in C++ https://stackoverflow.com/a/28689902/3832877 and it demonstrates the use template arguments which have additional types in parentheses. Examples of what I mean:
std::function<int(int, float)> foo; //for a function returning int with one ... | Those are types of functions. int(int,int) is the type of a function that takes two int parameters and returns an int.
For demonstration, consider this example:
#include <type_traits>
#include <iostream>
int foo(int,int){ return 42;}
int main(){
std::cout << std::is_same< decltype(foo), int(int,int)>::value;
}
I... |
67,159,945 | 67,159,946 | How to make OpenCV tracking classes derive from a base class? | OpenCV tracking API has implementations in 3 different places.
video/tracking.hpp
tracking.hpp
tracking/tracking_legacy.hpp
I would like to be able to use any implementation by providing the name of the algorithm as input.
cv::Ptr<cv::Tracker> get_tracker(std::string trackerType);
A similar approach with Python seem... | The solution lies in the example script of OpenCV. (tracking/samples/samples_utility.hpp)
We need to convert cv::legacy::Tracker to the preferred type cv::Tracker. Just like the different input problem for a function, we need to implement these member functions separately.
class LegacyTrackerWrapper : public cv::Tracke... |
67,160,419 | 67,160,584 | Log File class in .header to log events while running | I'm pretty new to c++ and I need your help, I think it's pretty easy questions but i cant get over the error
I have a .h file which includes methods to log error in txt file given but actually I dont really know how to use it could you please help me ? I try to test in the main by wrinting some error but i cant use the... | This operator
friend FileLogger &operator << (FileLogger &logger, const char *text)
is called like this:
test << "some text";
Your error message is a little obscure, because of the comma operator, which evaluates both operands and returns the right one, ie your call is the same as:
test << 'LOG_ERROR';
And 'LOG_ERRO... |
67,160,491 | 67,164,826 | Call template constructors of an inherited parameter pack | I'm having two probably related problems with the code below.
It just defines two types Type1 and Type2 respectively and an "aggregate" type Types that inherits from both of them.
My final goal is to make the commented constructor work to avoid having a temporary variable initialization. If I un-comment the code under ... | It seems like it's something with the copy constructor being automatically generated and used instead of the templated function. I added the copy constructor explicitly:
template <typename T>
Type1(T t) {}
Type1(const Type1& t) : init_{true} {}
to both types that seemed to work.
Another note would be to switch t... |
67,160,679 | 67,161,471 | Dependent project cannot see headers from a library in refferences in Visual Studio | I am learning how to make a static library. I started with windows and Visual Studio.
The directory structure looks like this:
- MyLibraryProject
- include
- MyLibraryProject
- MyLibraryHeader.h
- src
- MyLibrarySource.cpp
- build
- MyLibraryProject.vcxproj
- MyDependentProject
- mai... | Project references do not provide the dependent project with any information about headers. The most flexible way to do this instead (in Visual Studio) are property sheets. I created a file MyLibraryProject/build/MyLibraryProjectDependency.props:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns=... |
67,161,105 | 67,161,174 | How to initialize my struct describing RGBA color | I have a question about structures in c++. How should I declare
struct color_rgba
in this class? Just I get error:
no matching function for call to 'color_rgba::color_rgba()'
when I'm trying to do smth with this struct
Child_rectangle_dialog.cpp
#include "MainWindow.h"
#include "color.h"
class Child_rectangle_dialo... | The struct declares a constructor, so you have to call that constructor when constructing the property Child_rectangle_dialog::rectangle color.
Also, your constructor is weird and unnecesary - I will describe below. Consider this instead:
class Child_rectangle_dialog : public QDialog
{
private:
QLineEdit *cords_1, ... |
67,161,817 | 67,163,052 | How to get caret position without external libraries in C/C++ on linux? | I am trying to get the caret's (console cursor) position in ubuntu. I found a solution (here: https://thoughtsordiscoveries.wordpress.com/2017/04/26/set-and-read-cursor-position-in-terminal-windows-and-linux/ ) that makes use of ANSI codes, which looks like this:
printf("\033[6n");
scanf("\033[%d;%dR", &x, &y); // in x... | On my terminal disabling ECHO and disable canonical mode, but setting terminal to RAW is probably just better. Following code misses a lot of error handling:
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int x, y;
int t = STDOUT_FILENO;
struct termios sav;
... |
67,161,929 | 67,162,699 | convert nlohmann::basic_json<> to std::tuple c++ | I'm trying to call a function with parameters extracted from a JSON file using the nlohmann/json library.
I need to convert the JSON array retrieved from the JSON file to a tuple to call the function with.
The problem is that there's no build-up solution to convert nlohmann::basic_json<> to std::tuple in c++
the source... | Let's assume that you only pass non-overloaded functions, function pointers, or function objects with one operator(). Lets also assume that the json object is always an array of parameters.
First we need to make a tuple from the json and the target arguments
template<typename... Args, std::size_t... Is>
std::tuple<Args... |
67,162,214 | 67,162,283 | How do I output into a file in subdirectory? | This is not a duplicate. I'm trying to print some output to a file in a subdirectory (in this case to a file /stuff/output_1.txt) but it doesn't seem to create any new file. The code executes but no file is created, nor any subdirectory called /stuff. Here is my code:
#include <iostream>
#include <sstream>
#include <fs... |
no file is created, nor any subdirectory
You are using fstream which expects the path to exist. If you are referencing a directory and it doesn't exist, then it will fail, because either you have to create the directory before you run your program, or you have to use mkdir() to create it.
You can check with f.is_open... |
67,162,321 | 67,181,442 | Temporary disable console output for boost::log | I added sink to file via boost::log::add_file_log and console output via boost::log::add_console_log. I am calling a logger via BOOST_LOG_SEV and everything workds perfectely. But there is a place, where a want output only to the file.
How I can disable cosole output in certain place?
| You could achieve this with attributes and filters. For example, you could set up a filter in your console sink to suppress any log records that have (or don't have, depending on your preference) a particular attribute value attached.
boost::log::add_console_log
(
...
boost::log::keywords::filter = !boost::log:... |
67,162,470 | 67,162,517 | invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and class | I think I did all things clear. I used operator overloading concerned with "cout" and " cin" and "^" and "+" about Nat class.
I don't know why my compiler doesnt understand my code.
It must be a problem in making operator overloading but i dont know why...
enter code here
#include <iostream>
using namespace std;
cl... | The output operator is not modifying the object, hence the parameter should be const&.
To fix your code, change:
ostream& operator<<(ostream& out,const Nat& n) {
// ^^^-------------- !!!
return out << n.ival() << endl;
}
The complete error message s... |
67,162,884 | 67,162,995 | How to fix initialization errors? | I am trying to realize the work of the design template.
In lines 62 and 63 there are errors. I do not understand what might not be so, because I did everything in the book.
Points that are running in main():
The client declaring and initializing an instances of the classes.
The method gets called.
C2440 Initializa... | class Gender
{
public:
virtual string DetermineTheSex() = 0;
};
class Natasha : public Gender
Roma and Natasha inherit Gender, which is not a subclass of Human.
Therefore, you cannot use a Human* to point objects of this class. Change to Gender* and it will work:
Gender* Person1 = new Roma(mal);
Gender* Person2 =... |
67,163,139 | 67,163,185 | Why am I getting expression must have pointer to class type in c++? | Hey I am trying compare values of vector that store class objects to another vector of same class.
I have class in seperate .h file containing following
class Student{
std::string ID;
std::string Name;
std::vector<std::string> FriendsIDs
Student(std::string ID, std::string Name, std::vector<std::string> FriendsIDs)
~St... | List_Students is a vector of Student*, so iter "points at" Student*. Therefore you have to do "dereferencing" two times to access corresponding Student.
Therefore, you should use (*iter)->Name (or (**iter).Name) instead of iter->Name.
|
67,163,429 | 67,163,981 | I want to print the elements of the C++ vector in a listbox in the C# form application | I wrote a C ++ dll. One of the dll's functions returns the vector it takes as a parameter as follows
std::vector<std::string> foo(std::vector<std::string> strVec) {return strVec;}
I want to write the elements of the vector, which is the return value of the above function, into the listbox named lstData on the C# side... | a std::vector<std::string> is a c++ object. P/Invoke calls c-style functions and have no understanding of c++ objects. Your alternatives are more or less
Add a method to you c++ dll that accepts/returns pointers or c-style arrays.
Write a c++/cli adapter that converts between the vector and a C# list/array.
|
67,163,649 | 67,164,020 | Count amount of 3s in a series of numbers | (This isn't homework)
I'm working on a practice question (https://train.nzoi.org.nz/problems/1207) - "count the number of 3's when printing the numbers from 1 to N". I haven't found any solution online and I was wondering what a more efficient way to answer this question is.
my solution is:
#include <bits/stdc++.h>
usi... | Looks like a good use-case for recursion. Call your function f(n) (short name because I'm going to use math notation below). Then calculate f(n) by something like f(a) + f(b) + ... when all of the numbers a, b, ... are much smaller than n.
I am only going to give ideas by examples, not code. I hope this will be complet... |
67,163,712 | 67,163,792 | Why is compiler converting char to int in printf? | I am using https://cppinsights.io/ . Following is the code (default example)
#include <cstdio>
int main()
{
const char arr[10]{2,4,6,8};
for(const char& c : arr)
{
printf("c=%c\n", c);
}
}
About cppinsights
C++ Insights is a clang-based tool which does a source to source transformation. Its goa... | In C, any argument narrower than an int is automatically promoted to an int when passed to printf, or generally when passed to any function for an argument corresponding to ... in the declaration or to any function without parameter prototypes (declared with ()). C++ Insights is explicitly showing you this promotion.
A... |
67,163,775 | 67,164,128 | Connectionless named pipes on windows | What I want to do is create a named pipe server that routes messages between connected peers. On Windows it seems that you first have to create a pipe and then connect it to a client and then you read from the connected client pipe to get the message you want and then that handle is bound to that client and you have to... | "you first have to create a pipe and then connect it to a client"
Not exactly. The server process creates the pipe, but the client connects itself. Also, the client can try to connect and block if the server hasn't yet created the pipe.
"you read from the connected client pipe to get the message you want and then that ... |
67,164,156 | 67,164,193 | Reversing a linked list using recursion | I don't know where I'm going wrong. Output shows 1 upon inputting 1 2 3 -1 (-1 to terminate insertion of nodes). Help is appreciated!
I can't seem to find the error in my code that is resulting in wrong output upon different test cases.
Other approaches to the same problem are also welcome.
Any tips so that i won't com... | You have to assign the return value of rev_LL to head instead of just ignoring that.
int main()
{
Node *head = insert();
print(head);
cout << endl;
cout << "After reversing the Linked list : " << endl;
//rev_LL(head);
head = rev_LL(head); // assign the result
print(head);
cout << endl;
... |
67,164,630 | 67,164,690 | How to decompress gzip containing multiple files? | Is there an option, using zlib or boost, to unpack a gzip archive containing several files?
All options which I figured out were for 1 single file in archive.
I know about minizip, quazip and other useful libs, but I need to try to find an option without additional libraries.
| gzip doesn't compress multiple files. It only compresses one file. The reason you can't find a way to extract gzip archives is that they don't exist.
|
67,164,674 | 67,164,707 | "undefined reference to `CreateStreamOnHGlobal@12'" error faced on executing gdiplus c++ code | i found a code on github which takes a screenshot and saves it as a jpeg file. I copied and pasted it in notepad++, saved it, and compiled it with the following command:
g++ -mwindows screenshot.cpp -lgdiplus
and faced the following error:
C:\Users\USER\AppData\Local\Temp\ccTLI53G.o:screenshot.cpp:(.text+0x158): undef... | According to this site:
CreateStreamOnHGlobal function (combaseapi.h) - Win32 apps | Microsoft Docs
The library that contains CreateStreamOnHGlobal function is Ole32.lib, so -lole32 should be added to the command line.
|
67,165,024 | 67,169,668 | Cannot find library using Conan | I am requesting all your help and/or advise on a strange issue I am encountering trying to understand Conan.
First thing first, the error :
A well-known : /bin/ld: cannot find -lnlohmann_json_schema_validator
What I am trying to do :
Trying to build the main example of the json-schema-validator, based on nlohmann_json,... | I don't know where you found a tutorial, example or explanation, but you should read the official cmake-conan README, which contains a functional example.
Said that, your case can be fixed by the following example:
cmake_minimum_required(VERSION 3.5)
project(validator CXX)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_BINARY_... |
67,165,201 | 67,166,646 | C++ call to LAPACKE run on a single thread while NumPy uses all threads | I wrote a C++ code whose bottleneck is the diagonalization of a possibly large symmetric matrix. The code uses OpenMP, CBLAS and LAPACKE C-interfaces.
However, the call on dsyev runs on a single thread both on my local machine and on a HPC cluster (as seen by htop or equivalent tools). It takes about 800 seconds to dia... | From the provided informations, it seems your C++ code is linked with OpenBLAS while your Python implementation use the Intel MKL.
OpenBLAS is a free open-souce library that implement basic linear algebra functions (called BLAS, like the matrix multiplication, the dot products, etc.), but it barely supports advanced li... |
67,165,339 | 67,168,605 | clang-tidy readability-identifier-naming IgnoredRegexp | I want to exclude certain regex patterns from linting for readability-identifier-naming.
Part of .clang-tidy I'm using:
Checks: 'readability-*'
CheckOptions:
- key: readability-identifier-naming.TypeAliasCase
value: CamelCase
- key: readability-identifier-naming.TypeAliasIgnore... | Looking at the changeset that introduced the IgnoredRegexp it seems you have to use a proper regex - not a glob-match in the value-string
%check_clang_tidy %s readability-identifier-naming %t --
-config='{CheckOptions: [
{key: readability-identifier-naming.ParameterCase, value: CamelCase},
{key: readabilit... |
67,165,504 | 67,165,595 | failed to recognize concept type as bool in SFINAE | consider this example:
#include <iostream>
#include <utility>
template<typename T>
concept Printable = requires(const T a) {
a.print();
};
template<typename T>
constexpr auto is_printable() {
return Printable<T>;
}
template<class T, std::enable_if_t<is_printable<T>()>* = nullptr>
constexpr void do_print(T dat... | This is an MSVC bug. Your code is correct. I highly recommend reporting the issue. Your code works correctly on GCC and Clang.
In the meantime, I would simply drop the SFINAE. It is not really needed when you got concepts that replaces enable ifs:
#include <iostream>
#include <utility>
template<typename T>
concept Pr... |
67,166,800 | 67,167,192 | Is there a way to require all fields be entered in order to avoid vector subscript out of range error? | I have a database simulator coded in C++, and the way it works essentially is that the user says "insert 'item' 'quantity' 'price'" with item being a string and quantity/price being an int.
The issue I am running into is that whenever the user enters "insert" and doesn't put the other fields, a "vector subscript out of... | Something like this:
//insert command
if (cmdInput[0] == "insert")
{
if( (int)cmdInput.size() < 4 ) {
std:cout << "Not enough input params\n";
}
else {
string name = cmdInput[1];
int quantity = stoi(cmdInput[2]);
double price = stod(cmdInput[3]);
itemsDB.append(name, quantity, price);
}... |
67,166,825 | 67,174,086 | Template argument deduction of custom allocator | There is a custom allocator class:
template<typename T>
class pool_allocator {
public:
using value_type = T;
using pointer = value_type *;
/* Default constructor */
constexpr pool_allocator( void ) noexcept = default;
/* Converting constructor used for rebinding */
template<typename U>
con... | The solution is quite simple (only important parts are listed):
template<typename T>
class pool_allocator {
public:
[[nodiscard]] pointer allocate( size_t n, [[maybe_unused]] const pointer hint = nullptr ) const noexcept {
return get_pool().allocate( n );
}
void deallocate( pointer ptr, size_t n )... |
67,167,001 | 67,167,101 | Strange output when trying to display an array of characters C++ | Context
I'm trying to create a Rotor struct that holds arrays of characters in a specific sequence.
Code
Rotor
struct Rotor
{
public:
char assignedRotor[26];
void setRotor(int rotor) {
switch(rotor) {
case(1):
assignedRotor = rotor1;
break;
case(2)... | In c++ if you are declaring any variable you have to initialize its value otherwise it will be a garbage value. In your case, you are just declaring int i in the loop and variable i will point to some garbage value. Which you can fix by initializing i = 0 in the loop.
int main()
{
Machine enig;
for(int i = 0; ... |
67,167,379 | 67,167,530 | if constexpr not-taken branch doesn't need to be valid, sure? | I'm testing the code below:
#define TO_STRING(X) #X
#define TEST(X, Y) namespace Y { constexpr std::string_view name{#X}, raw_value{TO_STRING(X)};\
constexpr bool defined {name!=raw_value}; constexpr bool has_value{raw_value!=""}; }
#define A
#define B 1
TEST(A, a);
TEST(B, b);
TEST(C, c);
int main()
{
if const... |
[stmt.if]/2
If the value of the ... condition is false, the first substatement [aka the first branch] is a discarded statement, otherwise the second substatement, if present, is a discarded statement.
During the instantiation of an enclosing templated entity ..., if the condition is not value-dependent after its insta... |
67,167,420 | 67,407,194 | Strange output from debugger on data from ifstream | I open a file in read only mode, I read a line, and I cannot understand the meaning of the line contents as shown by the debugger:
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::string fidMapPath = "./file.txt";
std::ifstream ifsFidMap(fidMapPath);
if(ifsFidM... | With the version of GCC I used, 4.8.2, we must explicitly specify if what being compiled is C++11 code with the -std=c++11 compiler option. Otherwise it defaults to C++98.
This applies to GCC versions up to 5.x.
|
67,167,591 | 67,167,641 | Is this a semicolon between a method declaration and the method body? | I programmed for many years in C and C++ (I now use C#), and I ran into the following C++ code:
std::vector<BYTE> authTag(authTagLengths.dwMinLength);
{
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo;
BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
authInfo.pbNonce = (PUCHAR)&origNonce[0];
authInfo.cbNonce = orig... | This is all inside a function, right?
The first line defines a variable authTag of type std::vector<BYTE> and initialises it with a length.
The following code block is unrelated to that variable definition. The only reason why the following code is inside a separate code block is to create a more constrained scope: the... |
67,167,685 | 67,168,316 | ld.exe: cannot find -lasan ld.exe: cannot find -lubsan | I am using Clion and I want to use ASAN address Sanitizer, when I compile the file with ASAN here I get the following errors:
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot find -lasan
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: cannot find -lubsan
Here is my CMa... | Sanitizers have not yet been enabled for MinGW: https://github.com/msys2/MINGW-packages/issues/3163
|
67,167,802 | 67,169,405 | Delete element with specified key and value from std::multimap | Suppose I know that a given std::multimap has exactly one element with a given key and value, and I want to delete this element.
I could explicitly write a std::multimap::find to find some element with that key, then walk backwards until I reach the first element with a different key, walk forward until I find the elem... | There is no built in way to do anything involving searching by key and value but as NathanOliver says in comments, you can write a helper function on top of multimap::equal_range, e.g.
#include <map>
#include <iostream>
template<typename K, typename V>
typename std::multimap<K, V>::const_iterator find_item_by_key_and_... |
67,168,016 | 67,168,097 | Can a function take an argument by const reference *without* accepting temporaries as an argument? | Motivating example:
Suppose we have a class Foo and a class ObservesFoo that has a non-owning pointer to an instance of a Foo. We could write that as follows:
class Foo {};
class ObservesFoo
{
Foo* p_foo = nullptr;
ObservesFoo(Foo* t_foo) : p_foo(t_foo) { }
};
But maybe I don't consider nullptr to be a valid... | Assuming const doesn't interfere with how you use the object, and you never need to rebind what object is being observed, and the observed Foo instance is guaranteed to outlive its observer(s), then a reference will work.
If you delete the constructor taking an rvalue-reference to a Foo, you will prevent the accidental... |
67,168,153 | 67,168,686 | Visual Studio 2010 project builds fine using 32 bit, but get LNK2028 and LNK2019 errors when trying 64-bit. What could fix this? | I have a Microsoft Visual 2010 project that runs fine in the Win-32 compilation setting. I am running on Windows 10. I am trying to use the x64 to build for 64-bit but that is when I encounter the LNK errors (examples below):
error LNK2028: unresolved token (0A00015D) "extern "C" unsigned char __cdecl
UcanDeinitCan(un... | You're probably linking UCAN static library from somewhere. You need to make sure that in 64bit configuration, you link to 64bit .lib file.
First thing to check is Additional dependencies config and check what libraries are linked into the project.
|
67,168,746 | 67,168,864 | C++ set iterator error: no match for ‘operator+=’ in set | auto str=lower_bound(s.begin(),s.end(),n);
cout<<std::distance(s.begin()+1,str)+1;
Why +1 not working after s.begin()? It shows that there is no match for operator+ (operand types are 'std::set::iterator'...)
| std::set iterators are bi-directional iterators, which are required only to implement the -- and ++ operators. Random-access iterators implement +/- and +=/-= operators.
You can use std::advance() or std::next() to move an iterator forward when it doesn't implement operator+, eg:
auto str = std::lower_bound(s.begin(), ... |
67,169,183 | 67,169,502 | How to send a pointer of an overriden virtual function to the base class? | An example:
class Base
{
protected:
virtual void function() { std::cout << "Base\n"; }
void callfunction(void (Base::* func)()) { (this->*func)(); }
};
class Derived1 : public Base
{
public:
void publicCall() { callfunction(&Derived1::function); }
private:
void function() ov... | You can cast the member function pointer to the base class member function pointer type: callfunction(static_cast<void (Base::*)()>(&Derived1::function));. Full example:
class Base
{
protected:
virtual void function() { std::cout << "Base\n"; }
void callfunction(void (Base::* func)()) { (this->*func... |
67,169,464 | 67,170,066 | Dynamically cast to function argument type (C++) | In f1(), I want to be able to dynamically cast its foo argument to the same type as the argument of f2() (Bar, Qux, etc). Is this possible?
struct Foo {
virtual ~Foo() = default;
};
struct Bar : public Foo {};
struct Qux : public Foo {};
template<class T>
void f1(T f2, Foo &foo) {
// dynamically cast foo to type o... | This is a job for a templated conversion operator:
template <typename T>
struct dynamic_caster
{
T *ptr;
dynamic_caster(T &ref) : ptr(&ref) {}
template <typename U>
operator U &() const
{
return *dynamic_cast<std::remove_reference_t<U> *>(ptr);
}
};
template<class T>
void f1(T f2, Foo &... |
67,170,637 | 67,170,968 | Issue with pointer array not grabbing data from pointer function | I'm coding a game for my class, and I'm having a segmentation fault when my map array tries to access the symbol of a piece of land to display on a map. I can't figure out how to word this, because I can't figure out where to start when fixing this issue. Any help is appreciated.
Map.h
public:
Map(Player &p... | I tried to made two examples. One with size known at compile time (constant), and when dynamic. This following code is using C++ best practice of using RAII to avoid memory leakage.
class Map
{
public:
// Ctor for constant map.
Map(Player& player);
// Ctor for dynamic map.
... |
67,171,004 | 67,171,057 | Passing a 2D Array to function in C++ | I tried passing a 2D array to a function in C++ and I didn`t understand something:
//My array declaration:
int array[5][5]={{....}}; //I declared and filled the array with values
//My different function tries:
void passArr(int **array) //ERROR
void passArr(int *array[5]) //ERROR
void passArr(int *(*array)) //ERROR
void... | They're just different things. Reading from right to left might be helpful.
int array[5][5] -> array of array of int, could decay to pointer to array of int
int (*array)[5] -> pointer to array of int, could be converted from the above
int **array -> pointer to pointer to int
int *(*array) -> same as above
in... |
67,171,248 | 67,171,586 | O(1) worst case append only array | I'm looking for a data structure that supports O(1) random access and worst case O(1) append.
In my case however, O(1) amortized time for append is not what I'm looking for.
The data structure also will not have any operations performed on it other than append and access. No deletions, no insertions, just an append-onl... | std::deque gets awfully close to what you want:
It's O(1) for random access (twice as expensive as std::vector, as it must perform two pointer dereferences, not just one, but a fixed multiple like that doesn't change big-O)
It's effectively O(1), not just amortized O(1), for append, if you consider intermittent fixed ... |
67,171,481 | 67,171,801 | How to create a vector of objects that share a concept? | I want to create a vector (or array) of objects of different types but all sharing the same concept.
similar to Vec<Box<dyn trait>> of Rust.
struct Dog {
void talk() {
std::cout << "guau guau" << std::endl;
}
};
struct Cat {
void talk() {
std::cout << "miau miau" << std::endl;
}
};
tem... | What you're looking for is typically called "type erasure." The C++20 concepts language feature does not (and cannot) support type erasure - that feature is limited entirely to constraining templates (class templates, function templates, member functions of class templates, etc.) and cannot really be used in any other ... |
67,171,568 | 67,171,603 | Linked List creating a new pointer to add value but not working | void List::add_item(double new_value)
{
if (list == nullptr)
{
list = new ValueList;
list->value = new_value;
list->next = nullptr;
}
else
{
ValueList* track = list;
while (track != nullptr)
{
track = track->next;
}
track = ... | Because you are passing by the last element. You should in reality check if next element is nullptr, not if the element you are on is nullptr.
while (track != nullptr)
{
track = track->next;
}
should be:
while (track->next != nullptr)
{
track = track->next;
}
track->next = new ValueList;
track->next->value = ne... |
67,172,072 | 67,172,120 | How is access to private data members stopped? | I've started learning OOP concepts recently and was wondering what exactly is stopping the program from accessing private data members of a class? Are they encrypted? Or is it just the compiler that wont compile.
What I mean is that unless the data is encrypted. what is stopping the program from accessing those bits fr... | C++’s use of private is designed to guard against accidental misuse (“oops! I didn’t mean to read that value”) rather than against active subversion (“I’ll get a pointer into the middle of your object and read the bytes back.”) You can absolutely subvert private access by directly reading the bytes of the object if you... |
67,172,316 | 67,172,603 | co_return vs. co_yield when the right hand side is a temporary | Background: This question arose when I was reading the source of cppcoro, specifically this line.
Question: Consider the following code:
#include <coroutine>
#include <stdexcept>
#include <cassert>
#include <iostream>
struct result_type {
result_type() {
std::cout << "result_type()\n";
}
result_typ... | You are breaking a cardinal rule of C++: you wrote a function that takes a potential prvalue and store a pointer that outlives the function call that gave them a prvalue. Indeed, any time you see a function that takes an rvalue-reference (or a const-lvalue-reference) and stores a pointer/reference to that object which ... |
67,172,528 | 67,172,541 | Issue with recursive function arguments | I'm writing a simple recursive function, but I'm having issues calling it because of the arguments types. I'm new to C++ and typed languages, so it may be a really simple fix I don't understand.
The error:
error: no matching function for call to 'find(char*&, char* [4], const unsigned int&)'
find(charset, word, len... | char * word[length]; is an array of char * aka:
[char* 1, char * 2, char* 3, ...]
Your function is expecting just a char*. Since it seems you are expecting a character set, you probably just want char charset[4], or better yet std::vector<char> or std::array<char>.
|
67,172,598 | 67,172,747 | SelectionSort Template function not working with arrays | I have a template function that performs an index-based selection sort on an indexable object. The IndexedContainer must support operator[] and size(), e.g. std::vector. Container elements must support operator< and operator=.
My function must take in any std::vector or array and sort it in ascending order.
Function wo... | c++17 introduces std::size, a free function that encapsulates size for things with the size member function and arrays. If you don't have c++17, conveniently that link includes an implementation. The crux of which is this specialisation:
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) ... |
67,173,086 | 67,173,550 | Wait for a multithreading program written in C++ in java | I written a program in C++ where multithreading is used. Call this program using a bash script or something like that is no problem, everything is working fine. Now I want to call this program in Java. This is the Java code sample I tried:
Process v2j = new ProcessBuilder("./src/main/cpp/vcd_converter",
... | Your program doesn't get all output from the C++ program because it doesn't read until the input streams are depleted. It jumps to waitFor if the C++ program has not produced any output when your program reaches is.available().
Here's an alternative approach doing reading until the input streams are closed. It uses an ... |
67,173,410 | 67,173,734 | How should I implement an array constructor that takes in an unknown amount of arguments in c++? | I am currently implementing a dynamic array which uses a template to identify the type that is stored. However, the problem I am currently having is that I don't know how to make a constructor that accepts as many arguments as the user puts in to initialize the array. Function overloading would not be of any help due t... | This is an highly simplified case (it doesn't resize), but (I hope) addresses your specific construction question. If you are doing this for exercise you should start with something simpler, like a stack and read all the interesting nuance of exceptions guarantee (there is a beautiful analysis by Sutter on it).
#includ... |
67,173,703 | 67,173,850 | How can i open multiple files in one run in C++? | Hey I have several Files that I want to read. The user would input what file they want to open on console. And if they want they can change and read another file, they would do so.
This is how i went by doing (this is just rough copy, the code i have is too big will take too long to understand)
#include <string>
#inclu... | First close the file that is already open:
File.close();
Then open the new one:
File.open(FileName2);
|
67,173,743 | 67,177,355 | How to construct a tree given its depth and postorder traversal, then print its preorder traversal | I need to construct a tree given its depth and postorder traversal, and then I need to generate the corresponding preorder traversal. Example:
Depth: 2 1 3 3 3 2 2 1 1 0
Postorder: 5 2 8 9 10 6 7 3 4 1
Preorder(output): 1 2 5 3 6 8 9 10 7 4
I've defined two arrays that contain the postorder sequence and depth. After t... | You can do this actually without constructing a tree.
First note that if you reverse the postorder sequence, you get a kind of preorder sequence, but with the children visited in opposite order. So we'll use this fact and iterate over the given arrays from back to front, and we will also store values in the output fro... |
67,173,977 | 67,174,617 | Initialize a map with regex | I'm using a very nice and simple std::vector<std::string> initializer which takes an input string and regex. It's similar to a basic split, just it works with regex Group1 matches:
static std::vector<std::string> match(const std::string& str, const std::regex& re) {
return { std::sregex_token_iterator(str.begin(), ... | I don't know what 'easily' does mean exactly, so here comes simple solution:
#include <iostream>
#include <regex>
#include <vector>
static std::map<std::string, std::string> match(const std::string& str, const std::regex& re) {
std::map<std::string, std::string> retVal;
auto token = std::sregex_token_iterator(... |
67,174,019 | 67,174,137 | Confusions with reference in c++ | In The C++ programming language, it said "a reference cannot be made to refer to a different object after its initialization." However, when I wrote the code below, it printed 20, which means that the reference refer to another object.
int a = 10;
int b = 20;
int& ref = a;
ref = b;
cout << ref << endl;
However, when I... | In the line
int& ref = a;
You set ref to be a reference to the variable a. You then set the value of this object to be the value of b in the next line:
ref = b;
Note that a will now have the value of b (which since you haven't initialised it yet will be zero).
Next, you set the value of a to be 10
a = 10;
At this po... |
67,174,057 | 67,176,117 | The contradiction on the return values of PostMessageA and WM_MOUSEMOVE | I want to post WM_MOUSEMOVE message using Windows api PostMessageA. In the microsoft document on WM_MOUSEMOVE, it says:
If an application processes this message, it should return zero.
And in the one on PostMessageA, it says:
If the function succeeds, the return value is nonzero. If the function fails, the return va... |
In the log file, I found this line:
[Error]: post message in Mouse move failed. Error: 0
What exactly the meaning of the returned "0" ?
Nothing. You have an erroneous ; on the end of your if statement, so it doesn't matter what value PostMessageA() returns, because LogError() will be called unconditionally and be pa... |
67,174,261 | 67,176,619 | Where program entry point is defined when building and runing C+/Juce project in Xcode? | I'm trying to build C++ project in XCode and JUCE: https://github.com/spiricom/LEAF it has prepared example project for JUCE which generates Xcode project.
It runs with no errors, and I can see the application is working.
Yet I cannot find where in my project settings is program entry point defined, also there is no ma... | int JUCEApplicationBase::main (int argc, const char* argv[]) is hidden in
/JUCE Modules/juce_events/messages/juce_ApplicationsBase.cpp
Main is hidden in
/JUCE Modules/juce_auido_plugin_client/juce_audio_plugin_standalone.cpp:
Answer how this hooks in to the external code (LEAF in my case) :
You should derive your own ... |
67,174,450 | 67,175,739 | Add struct in std::list | I have a following struct:
struct data {
std::string str;
int num;
int num2;
std::string str2
} data1;
I have a std::list<struct data> list;
I want to add struct in std::list, assuming there is no such structure, use std::find_if and lambda function's.
std::list<data>::iterator it = std::find(list.begi... | To use std::find_if and a lambda:
std::list<data>::iterator it = std::find_if(list.begin(), list.end(),
[&data1](const data& rhs) {
return
data1.str == rhs.str &&
data1.num == rhs.num &&
data1.num2 == rhs.num2 &&
data1.str2 == rhs.str2;
}
);
In this case... |
67,174,588 | 67,174,752 | Moving ctor not kicking-in | following code
#include <iostream>
class C
{
public:
C(int i) : i{i}{ }
C(const C&) = delete; // no copy allowed
C(C&& c){ std::cout << "moving from " << c.i << '\n'; i = c.i--; }
int i;
};
void func(C&& c) { std::cout << "func c " << c.i << '\n'; }
int main()
{
C c{123};
func(std::move(c));... | std::move doesn't actually call the move constructor. It is a cast to r-value reference (akin to static_cast<C&&>(c)). Once this is done, if you try to copy that object, it will call the move-constructor or the move-assignment operator. If you don't try to copy that object, nothing happens. Try this:
// By value
void f... |
67,174,663 | 67,222,949 | Cannot save the file to specific directory by wasm | OS : win10 64bits
Browser : edges Version 89.0.774.77 (Official build) (64-bit)
Emscripten : 1.39.7
The function saves file
void saveFile(const char *data, size_t length, const char *fileNameHint)
{
// Create file data Blob
val Blob = val::global("Blob");
val contentArray = val::array();
val content = v... |
Is this the limitation of the browser?
Yes, intentionally so. You can't just access arbitrary paths on user's computer from a Web page - that would be a huge security risk.
Instead, you have one of the following options:
Offer file download like you currently do, and let user take care of saving / copying / moving i... |
67,175,287 | 67,221,401 | XAudio2Create failed after the update 2021/4/20 | Windows10 version 20H2.
I followed every step-Getting started with XAudio2-How to: Initialize XAudio2.
The link is here.
https://learn.microsoft.com/en-us/windows/win32/xaudio2/getting-started
The code worked before the update.
But now when I try to do something like this:
pXAudio2->CreateSourceVoice( &pSourceVoice, (W... | The problem here seemed to be a mix of legacy DirectX SDK and newer Windows SDK headers in the build environment.
XAudio2 is fully supported on Windows 20H2 including it's various version.
Legacy XAudio 2.7 from the end-of-life DirectX SDK runs fine, as do all the legacy games and samples that use it. It is not part of... |
67,176,045 | 67,176,174 | for loop done without meeting the condition I set | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 5;
int nums[] = {0 ,1};
if (n == 0)
{
return 0;
} else if (n == 1)
{
return 1;
} else{
for (int i = 2; i < n + 1; i++)
{
cout << i << endl;
nums[i] =... | nums[i] has size 2. You can't access nums[i] for i >= 2. An array doesn't grow. You can't change the size of an array. Use a std::vector. You've already included the header. A return statement finishes a function. In case of the main function it causes the program to stop. The return value of the main function by conve... |
67,176,614 | 67,429,251 | does including <execution> require linking against tbb? | In my project on a Ubuntu 20 platform (with g++ 9.3.0), I use the following line
#include <execution>
to support parallel processing via standard library functions. I don't include anything from TBB, the parallel execution library from Intel. But then when I build the program I get the message:
/usr/bin/ld: CMakeFiles... | As @[n. 'pronouns' m.] rightly said, you may need libtbb in order to make your code work. You can download the Intel® oneAPI Base Toolkit which contains TBB as one of the components.
Link to download Intel® oneAPI Base Toolkit:
https://software.intel.com/content/www/us/en/develop/tools/oneapi/base-toolkit/download.html... |
67,176,820 | 67,177,368 | std::thread not waking up when using notify_one() function even with predicate | I've been trying to write both periodic and non-periodic messages on a serial port using Windows API. The architecture of my code is the following:
The main thread starts the following :
A "message sending thread" that will be responsible for writing data over the serial port. It will wait on a condition variable to b... | You have two different threads which can "send" a message. Neither of those threads whether theres already a pending message (e.g. newMessage==true;).
notify_one will eventually notify the receiving thread, but there's nothing that guarantees it does so immediately.
Add an assert(! newMessage); in both of your send fun... |
67,176,843 | 67,177,571 | Get IPv6 DNS Server Addresses using GetAdaptersAddresses() | I am trying to get the DNS Server IPv6 addresses in C++, and I found this article showing how to get the information using GetAdaptersAddresses(): GetAdaptersAddresses function (iphlpapi.h). This article also provides example code. Going through the instructions, it says the FirstDnsServerAddress member of the IP_ADAPT... | You're passing the wrong data to inet_ntop. You should pass the sin_addr or sin6_addr member, depending on the protocol.
inet_ntop(AF_INET, &((struct sockaddr_in*)pDnServer->Address.lpSockaddr)->sin_addr, ipv4_addrstr, INET_ADDRSTRLEN);
inet_ntop(AF_INET6, &((struct sockaddr_in6*)pDnServer->Address.lpSockaddr)->sin6_a... |
67,177,354 | 67,177,611 | Generic vs Overloading in terms of execution speed | I am trying to find how the execution speed defers while using generic programming concept over overloading.
Here is my code.
overloading
class Addition{
public:
int sum (int a, int b){
return a+b;
}
double sum (double a, double b){
return a+b;
}
};
int main(){
Addition a;
cout... | I benchmarked your code with https://quick-bench.com/q/OdgFIOROlvUVzajZkaa5hemVupQ
#include <iostream>
class Addition1{
public:
int sum (int a, int b){
return a+b;
}
double sum (double a, double b){
return a+b;
}
};
template <class T>
class Addition2{
public:
T sum(T a,T b){
... |
67,177,390 | 67,180,193 | Compile time if else in c++ 11 | I have this template function -
template <int N>
void foo() {
if (N < 2) {
bar1();
} else {
bar2();
}
}
I want to deduce if else during compile time in C++11 to make the function efficient. I thought of adding an additional template bool variable like this -
template <int N, bool I = (N < 2), std::enabl... | In C++11, you can use enable_if to write 2 overloads
template <int N, typename std::enable_if<N < 2, int*>::type = nullptr>
void foo() {
bar1();
}
template <int N, typename std::enable_if<N >= 2, int*>::type = nullptr>
void foo() {
bar2();
}
Here's a demo
Note that this is unlikely to give you any performan... |
67,177,640 | 67,177,782 | Add an element to a vector inside a struct, from within another struct | This is most probably trivial and I'm confusing struct allocation and pointers somehow, I apologize for this. I have read answers to similar questions but it didn't help. The code is, as always, way more complicted, this is a reduction from 3000+ lines of code to the gist.
The output I expected was
prep 1
main 1
Inste... | You don't store pointers in your vector<Entry> so you should not use new. Instead add a default constructed Entry using emplace_back.
A C++17 approach:
void prep()
{
Entry& entry = entries.emplace_back(); // returns a ref the added element
entry.list.push_back(0);
cout << "prep " << entry.list.size() << "\n... |
67,177,680 | 67,178,082 | I want to sort the sheet according to the rule | I have a list:
std::list<std::string> list = {data2, data2, data2, data3, data3, data1, data1};
I have a sorting rule:
std::list<std::string> sortRule = {data1, data2, data3};
I need to sort the list according to sortRule, i.e. that was:
list = {data1, data1, data2, data2, data2, data3, data3};
As I understand it, I... | std::list has no RandomAccessIterator, hence you cannot use std::sort, though there is std::list::sort that takes a custom predicate. Your predicate should compare the indices of to be compared elements in sortRule:
#include <list>
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::strin... |
67,177,943 | 67,194,214 | Tracing custom CUDA kernels with Nsight Systems | I work on library which is implemented in C++20 and CUDA 11. This library is called from Python via ctypes through a C API that just exchanges JSON strings. We compile it using Clang 11.
In order to profile the code I have added a lot of NVTX ranges to the C++ code. This works well for me with Nsight Systems, I can see... | The issue could have been that I have not properly stopped the data gathering and our program is an interactive server which one stops with a SIGINT. Perhaps the data was not properly stored after the interrupt.
I have added calls to the profiler API in the code such that I explicitly call cudaProfilerStop() after our ... |
67,178,490 | 67,178,917 | Rendering translucent triangles in models animated by a vertex shader? | Until now, I've been handling translucency by sorting my translucent triangles back to front. This works very well for quads, but I'd like to incorporate translucency in my models now.
I've thought of separating the translucent tris out and sorting them in the same way as my quads. Sorting by their centroids, then st... | Afaik, there's no easy solution to what you want to do. However, there are some things that you can do:
Don't sort triangles at all, and only sort individual draw calls. This is the easiest solution and is utilised by most games, if they use translucent/transparent objects in the first place. Of course, this might not... |
67,178,685 | 67,178,770 | pointer returned to an object turns null after function returns address | I am new to CPP and I am writing a program as an assignment to simulate a train path system that includes destinations and starts using object oriented programming .
I have 2 classes as shown below (there is a a passenger class but it is not relevant ) :
class Train
{
public:
int cooldown_time;
... | Station *station_search(vector<Station> stations, string key)
If you take a closer look here, you will see that the stations parameter is passed by value, which means that after this function returns, this stations parameters will get destroyed. It will be no more. It will cease to exist. It will become an ex-paramete... |
67,178,765 | 67,359,098 | C++ Addition of very large unsigned long and double | Following code:
#include <iostream>
#include <limits>
int main(int argc, char **argv) {
unsigned long n = 10ul;
unsigned long ul = std::numeric_limits<unsigned long>::max() - n;
double d = 1.;
ul += d;
std::cout << ul << std::endl;
}
One might expect that the output is std::numeric_limits<unsigned long>::ma... |
The question is what are the exact rules for C++ for evaluating an expression in which data format that lead to this unfortunate result.
Let's inspect the line:
ul += d;
Where d has type double and ul has type unsigned long.
From 7.6.19 Assignment and compound assignment operators :
The behavior of an expression o... |
67,179,015 | 67,179,074 | How to store pointers to objects that class doesn't own? | I am trying to code two classes FooFactory and Foo. FooFactory initializes an object ToolBox in the constructor and stores it in a unique_ptr as I want that to be cleaned after the factory is destructed. All the instances of Foo should be able to use ToolBox so I am passing ptr to ToolBox object in the constructor of F... | A factory would normally never control the lifetime of an object. It should hand out an appropriate pointer, preferably a std::unique_ptr and the caller determines it's lifetime.
#include <string>
#include <iostream>
#include <memory>
class Box
{
public:
Box() {}
};
class Foo
{
public:
Foo(std::shared_ptr<Box... |
67,179,833 | 67,180,921 | How to create pointer to different instantiation of template class | In making my first experiments with Abstract Factory in C++(while reading Modern C++ Design - A. Alexandrescu - part 9) i have a question.
If classes hierarchy looks like this:
struct B {};
struct D1 :public B {};
struct DD1 : public D1 {};
struct DD2 : public D1 {};
struct D2 :public B {};
struct DD3 : public D2 {}... | With some changes you might have:
// Way to "pass" Type.
template <typename T> struct Tag{};
template <typename T>
struct AbstractFactory
{
virtual ~AbstractFactory() = default;
virtual std::unique_ptr<T> Create(Tag<T>) const = 0;
};
template <typename ... Ts>
struct AbstractFactories : virtual AbstractFactor... |
67,180,016 | 67,186,467 | VSCode, C++ and CMake - One launch configuration per target | I use Visual Studio Code and the CMake extension to work on a big project. The project consists of some libraries and executables which all are available as separate cmake build targets.
I configured VSCode / tasks.json to build the selected target with its default build.task:
{
"version": "2.0.0",
"tasks": [
{... | You can use the extension Command Variable v1.17.0
If you use the command extension.commandvariable.file.fileAsKey you can use the command variable ${command:cmake.launchTargetPath} to get the path that is used for matching keys (file path parts) to command line arguments.
The chosen default value (-v0) is a command op... |
67,180,270 | 67,203,003 | Access listview model data in the delegate of another listview with a different model in Qt | The issue:
I got two listviews in qml, both have models implemented in C++ based on the QAbstractListModel.
As an example, say both listviews only have two roles, color and size, and both of these are dynamic and can change from some outside data input (i.e tcp client).
Each item in the second listview is related to th... | I tried the answer above with what I wrote in the comment, using the itemAtIndex, but this will not update the property in the second list when new data arrives.
I got this working by creating a function in the delegate of the second list that searches in the child items of the contentItem of the first list, and then b... |
67,180,282 | 67,183,027 | How to erase an element in a vector of vector or matrix | Hey there I am trying to erase an element in a vector of vector / most probably a matrix made of vector so I searched stack overflow but it didn't have any answers and I wasn't able to find it online as well so thought to ask here.Well I am new to programming and I'm trying to solve google kick start 2020 Round-A QUEST... | The erasing can be performed as:
S_Plates[SNo].erase(S_Plates[SNo].begin());
A few modifications are needed elsewhere, as indicated in comments.
Note that erasing is a costly function, and useless here: you could use indices instead. (one per stack)
However, this greedy algorithm does not provide the good result. For ... |
67,180,691 | 67,181,120 | Boost::variant with a object which references the same variant | How can I have a variant of different objects A, B, C where C has a reference to the variant?
class A {
...
};
class B {
...
};
class C {
...
std::vector<PossibleValues> storage; // reference to variant
...
};
boost::variant<A, B, C> PossibleValues;
| With correct order, you might have:
class A {
//...
};
class B {
//...
};
class C;
using PossibleValues = std::variant<A, B, C>;
class C {
//...
std::vector<PossibleValues> storage; // reference to variant
//...
};
Demo
|
67,181,350 | 67,181,572 | Convert uint32_t to double between 0 and 1 | I have a shamefully naive question: What is the best way to convert a uint32_t to a double between 0 and 1?
My naive way is
double myconvert(uint32_t a)
{
double n = static_cast<double>(std::numeric_limits<uint32_t>::max() - std::numeric_limits<uint32_t>::min());
return static_cast<double>(a) / n;
}
But I was ... | std::numeric_limits<uint32_t>::min() is 0. Although removing the subtraction doesn't improve the generated assembly since it is known at compile time, it can simplify the function.
Another potential improvement is to calculate the complement of the divisor and use multiplication. You might think that optimiser would do... |
67,181,376 | 67,182,841 | Iterate `std::vector<std::string>` from Go? | I'm trying to use a C++ library from Go. I also have little experience with Go.
My C++ method looks like this:
std::vector<std::string> getAttribute(const std::string key);
I have this in my .swigcxx file:
%include "std_string.i"
%include "std_vector.i"
%include "MyCode.h"
%template(StringVector) std::vector<std::st... | It looks like it's a problem with function overloading. I had 2 getAttribute functions with the same name and different parameters. When I rename the method so that it's unique, Capacity() and Get() work (although range doesn't).
It looks like Swig tried to generate wrapper code to call the correct method, but couldn't... |
67,181,496 | 67,181,742 | Can I declare multiple functions with comma? | Can we use , operator to declare multiple functions once ?
This code compiles on gcc:
void f(), g();
void f() {}
void g() {}
int main() {
f();
}
Is it standard or a particularity of the compiler ?
| It's standard. Look at all the things you can declare:
int a, *pa, f(int), *g(int);
This is a single declaration, with a single type specifier int and four declarators. Note that the two variable declarations there have different types, despite having the same type specifier. Same deal with the two function declaratio... |
67,181,635 | 67,182,024 | Is it necessary do a cudaMalloc and cudaMemcpy with a thrust::device_vector? | I am a newbie with CUDA. I have read that it is necesary to allocate variables with cudaMalloc and then use cudaMemcpy to copy the values to the device variables. Something like this:
__global__ void suma(int *a, int *b, int *c)
{
*c = *a + *b;
}
int suma_wrapper(int a, int b, int c,int* d_a, int* d_b, int* d_c)
{... | Thrust does all CUDA API calls for you. So while you can use Thrust algorithms on manually allocated memory or pass the memory from a thrust::device_vector to a kernel, you don't need cudaMalloc and cudaMemcpy, as everything is already included in the standard C++ vector interface.
The memory allocated by thrust::devic... |
67,181,682 | 67,181,754 | Using templates to pass array with N elements in C++ | Here we pass a reference to an entire array using templates, and it compiles fine:
template <int N>
void test(int (&in)[N]){
}
int main(){
int a[2] = {1,2};
test(a);
return 0;
}
But doing the same to pass a regular array doesn't work, the template can't figure out what N is on its own, why?
template <int N>
void t... | It is not "doing the same way". When a function takes an array like this:
void foo( int x[] )
Then that is just a slightly obfuscated way to write this:
void foo( int* x)
Arrays decay to pointers when passed to functions. You cannot pass arrays by value.
You can pass arrays by reference and thats what your first code... |
67,181,704 | 67,182,038 | When using WSASend in overlapped mode, when should I free the buffers? | I am using WSASend() to send some data with IOCP. I allocate a buffer and fill it with data to send, then create a WSABUF pointing to my buffer and pass it into WSASend().
The documentation says:
If this function is completed in an overlapped manner, it is the Winsock service provider's responsibility to capture the W... |
can I also locally allocate my underlying buffer, freeing it after WSASend() returns but before the IO finishes?
No. The buffer must remain allocated until after the IO is completely done using it. Only then can you free it.
Or should I transfer ownership of the underlying buffer to my IOCP worker thread so that i... |
67,181,885 | 67,182,050 | WinDbg find all C++ objects of type X on heap that do not use inheritance (no vftable) | I have a C++ application with debug symbols, and created a dump file of such application with all relevant gflags enabled:
gflags /i xxx.exe +hpa
gflags /i xxx.exe +ust
Now, I have found from other questions (see here), that by first looking for a type's vftable address:
x module!SomeClass*table*
And then searching t... | Given that an object can be created out of random bytes (so long as alignment requirements are met) it is impossible to say whether some random collection of bytes is of any particular type. Even in the case where there is a value that matches a vtable pointer that is only a very strong hint rather than conclusive proo... |
67,181,987 | 67,189,023 | What is the proper way to render multiobject scenes in d3d 11 | If I want to render a specific mesh I create it's vertex/index data, create vertex buffer, index buffer, bind them to the IA, set the desired shaders and call context->DrawIndexed. I guess one option of rendering multiple objects will be to loop this procedure for each object, but on msdn it says "Input assembly (IA):... | Direct3D is a low-level graphics API, so there are many ways you can render objects.
One common model for basic rendering is to organize each mesh as a Vertex Buffer, an Index Buffer, and a list of 'subsets' that share the same material/surface properties (a set of vertex shaders, pixel shaders, texture resources, etc)... |
67,182,312 | 67,182,814 | Trouble getting required output in C++ | We received a question in an assignment. I had trouble interpreting it so I rewrote it in c++, with the same conditions. However, I cannot seem to get the correct outputs listed in the question. Can anybody advise me on how to proceed?
This is a snip of the Question.
Here is my code:
#include <iostream>
#inclu... | We can examine and talk through the first case.
The output is supposed to be:
Almost
Yes we have arrived
That was annoying
That was annoying
If you draw out a number line:
<- <0 - 0 - 1 - 2-3-4-5 - 6+ ----->
Almost|Yes we have arrived|Almost|That was annoying|We just left|
Then, ... |
67,182,330 | 67,183,013 | constant array using programming C++ | const int new_WEIGHT[GENE] = { temp_WEIGHT[0],temp_WEIGHT[1],temp_WEIGHT[2],temp_WEIGHT[3],temp_WEIGHT[4],temp_WEIGHT[5],temp_WEIGHT[6],temp_WEIGHT[7] };
Is there another way, rather than copying all of the array indexes? I mean, somehow another way to copy the array to another constant array? Please help!
| You can copy a std::array:
const std::array temp_WEIGHT {1, 2, 3, 4, 5, 6, 7, 8};
const auto new_WEIGHT = temp_WEIGHT;
You can convert (and copy) a C array to a C++ array with to_array:
const int temp_WEIGHT[] = {1, 2, 3, 4, 5, 6, 7, 8};
const auto new_WEIGHT = std::to_array(temp_WEIGHT);
You can access the underlyin... |
67,182,429 | 67,182,658 | type erasure for functions in rust | Consider this C++ code:
#include <iostream>
#include <functional>
using namespace std;
std::function<int(int, int)> foo(int c) {
auto add = [] (int a, int b) { return a + b; };
auto sub = [] (int a, int b) { return a - b; };
if (c > 42) {
return add;
} else {
return sub;
}
}
int main() {
cout << ... | A rather exact translation of your example would be the following snippet.
fn foo(c: i32) -> Box<dyn Fn(i32, i32) -> i32> {
let add = |a, b| a + b;
let sub = |a, b| a - b;
Box::new(if c > 42 { add } else { sub })
}
fn main() {
println!("{}", foo(100)(10, 20));
}
A type of closure is unnameable, so we ... |
67,183,131 | 67,183,226 | OpenGL jpg image loaded with SOIL is displayed slanted | When loading the jpg image using SOIL, the image is displayed slanted and the colors are not right (i don't know how to describe it, because it is in color, but it looks black and white)
The intended version
However, it is displayed like this
The shaders are:
vertex shader
#version 330 core
layout (location = 0) in v... | By default OpenGL assumes that the start of each row of an image is aligned with 4 bytes. This is because the GL_UNPACK_ALIGNMENT parameter by default is 4. If the format of the image is RGB and width*3 is not divisibly by 4, you must change the parameter before specifying the two-dimensional texture image (glTexImage2... |
67,183,421 | 67,185,089 | Building sqlite3mc amalgamation fails with ‘_mm_aesimc_si128’: target specific option mismatch - Even with -march=native | I'm trying to build this project: https://github.com/utelle/SQLite3MultipleCiphers
Specifically the amalgamation files found at: https://github.com/utelle/SQLite3MultipleCiphers/releases/tag/v1.2.5
I'm getting this error from the _mm_aesimc_si128 function:
/usr/lib/gcc/x86_64-linux-gnu/9/include/wmmintrin.
h:77: error:... | Since the amalgamation file is a C file it should be:
QMAKE_CFLAGS += -march=native
not
QMAKE_CXXFLAGS += -march=native
Additionally, sqlite3mc uses pthread and ldl so these libraries must be linked:
LIBS += -pthread -ldl
After making these changes it builds successfully.
|
67,183,839 | 67,183,926 | C++: Can the destructor be the only virtual function in a class? | I read that the destructor should be declared virtual only if there is virtual function in a class.
Is this a requirement or is it possible to do otherwise?
| You should have virtual destructors if you intend to use your class in a polymorphic setting. If you don't plan to use polymorphism and polymorphic destruction (destruction through a base class) then you don't need a virtual destructor.
Usually, we use classes in a polymorphic setting when there are virtual functions. ... |
67,184,218 | 67,184,383 | How do I use a left handed coordinate system for rendering? | I'm trying to setup view, and projection matrices to work with my intended world coordinates and handedness. I'm going for a left handed coordinate system, +X to your right, +Y above you and +Z before you.
Y coordinates are working fine but objects placed in front of the camera (+Z) are showing up behind it, so I have ... | Vulkan, like non-legacy OpenGL and DX 11+ are all independent of any chosen "handdedness", that's an artefact of the math library you're using (if any).
As to your actual question, the matrix you're building is right handed because you assign -1 to matrix[3][2]. The left handed version is the same except it has 1 for t... |
67,184,255 | 67,184,369 | Duplicate the element of array to create a new word | I am trying to write a code, which would do this:
Input: Sample
Output: Saammmppppllllleeeeee
This is what I've done so far:
#include <string>
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
int main()
{
string s;
cout << "Input a word: ";
cin >> s;
int n = s.length();
... | I would do it like this, one loop for the word and another inside for the amount to repeat for each letter:
int main()
{
string s;
cout << "Input a word: ";
cin >> s;
int n = s.length();
for (int i = 0; i < n; ++i)
{
for (int j = 0; j <= i; ++j) {
cout << s[i];
... |
67,184,524 | 67,184,765 | How to get the lines of a file and the amount of characters per line | I am trying to get the amount of lines in a file in order to make an array to store the characters of each line. I think the problem is with the two while loops iterating at the same time.
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using std::cin;
using std::cout;
us... | A main issue with your code is that you consume the stream in the first while loop and then try to do it again. They are not "iterating at the same time", they are two successive loops with the same exit condition. In virtually every case that results in the second one not executing at all.
Also, if you are allowing yo... |
67,184,616 | 67,184,840 | Is this allowed syntax for defaulted template argument? | I want to be able to have a template type argument as empty, which case the class just has an empty T, or U, or whatever. I tried to do this defaulting the template argument to a simple lambda:
template <typename U = decltype([]() {})>
On Visual Studio 2019 16.9.3 I don't get the right result when I query the type of ... | In C++17, a lambda may not appear in an unevaluated context. This restriction was lifted in C++20, but your compiler might not have implemented this feature yet (even if it already supports [[no_unique_address]], another C++20 feature), so you need to upgrade your compiler. And in any case I would recommend not writing... |
67,184,835 | 67,185,248 | Merge sort a Linked list (segementation fault) | The below code is for merge sorting a linked list. Its giving out a segmentation fault. I really dont know how to deal with the above. All I could find was that I was trying to access a restricted part of the memory, the only place I think i could've gone wrong is re combining the two linked lists after splitting and s... | Your call to split will not make h1 or h2 get a value. Arguments are passed by value. Since you evidently need h1 and h2 to get a different value from that split call, you should pass their addresses:
split(temp, &h1, &h2)
The function itself should therefore accept these addresses instead of the node pointers themse... |
67,184,857 | 67,186,092 | Using a 2D array for a game map in C++ | Software: Visual Studio 2017 Community
Hi, everybody,
I am making a simple 2d console game in C++ (perhaps very simplified Dwarf Fortress if you know it).
And I want a map to be displayed in console with ASCII.
Something like this:
I have a WorldMap class declared in the header file(simplified version).
And I declare ... |
What's the best way of declaring a 2d array for a class and then defining it in the object?
What's the best way to store a map for such a console game? (Not necessarily using arrays)
This is not "the best way" but it's one way of doing it.
Create a class wrapping a 1D std::vector<char>.
Add operator()s to access t... |
67,184,950 | 67,185,891 | Upcast to abstract base class | I try to have an abstract base class act like an interface and instantiate a derived class based on user input. I tried to implement it like this
class A
{
public:
virtual void print() = 0;
};
class B : A
{
public:
void print() override { cout << "foo"; }
};
class C : A
{
public:
... | There are two problems with the code in its current state.
By default in C++, a class that inherits from a class or struct will be private inheritance. E.g. when you say class B : A, it's the same as writing class B : private A -- which in C++ restricts the visibility of this relationship only to B and A.
This is impo... |
67,185,327 | 67,185,458 | How to remove a whole tuple from vector with a string match? | I am trying to remove a tuple from a vector that matches the input string.
vector< tuple<string, int, int> > goals;
So, if the string matches with the input string x, I want it to be removed.
void remove_goal(const string& x){
goals.erase(remove(goals.begin(), goals.end(), x));
}
But I am getting this error
e... | Here's an example that demonstrates a fairly efficient way to delete std::tuples from a std::vector that match a criteria.
It uses the aptly named erase/remove idiom.
#include <algorithm>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
int main() {
std::vector<std::tuple<std::string, int, in... |
67,185,536 | 67,186,157 | Calling delphi procedure from C++ | I have a DLL written in Delphi that I need to call from a C++ code. The signature of the procedure in Delphi is:
procedure GetDeviceName( No: integer;
Name: PChar;
Len: integer;
var Error: integer); stdcall;
From the code from the DLL I b... | From the fairly small amount of information you have provided, my initial thought is that you have declared the array DeviceName as a local variable so it's on the stack, and then overrun the stack giving you an AV when you try to return.
In modern versions of Delphi, Char is wchar_t and PChar is wchar_t* (so a Len of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.