question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,901,239 | 69,902,363 | Points depth buffer not sorting properly | I am fairly new to OpenSceneGraph and I am working on an application that generates point clouds. We first create an osg::Geometry object containing the points of a particular area, we then create an osg::Geode that contains the geometry and then we add it as a child to an osg::Group that contains all of the terrain points. We then add that as the scene data of our osgViewer::Viewer in which we also setup our camera.
So we generate our geode/geometry like this:
osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry());
geometry->setVertexArray(vertices.get());
geometry->setColorArray(colors.get());
geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS, 0, static_cast<int>(segment_size)));
geometry->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
geometry->getOrCreateStateSet()->setRenderingHint(osg::StateSet::OPAQUE_BIN);
osg::ref_ptr<osg::Geode> geode(new osg::Geode());
geode->addDrawable(geometry.get());
geode->setNodeMask(TERRAIN_ENABLED_NODE_MASK);
And we add it to our group and viewer like this:
m_terrain_group = new osg::Group();
m_terrain_group->addChild(geode);
m_viewer = new osgViewer::Viewer();
m_viewer->setCamera(make_camera(width(), height(), m_graphics_window_embedded));
m_viewer->setCameraManipulator(make_camera_manipulator(), true);
m_viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
m_viewer->realize();
m_viewer->setSceneData(m_terrain_group);
The make_camera function looks like this:
osg::Camera* OsgWidget::make_camera(int width, int height, osg::GraphicsContext* graphics_context) const noexcept
{
double aspect_ratio = static_cast<double>(width) / static_cast<double>(height);
osg::CullSettings cull_settings;
cull_settings.setCullingMode(osg::CullSettings::CullingModeValues::VIEW_FRUSTUM_SIDES_CULLING | osg::CullSettings::CullingModeValues::CLUSTER_CULLING);
cull_settings.setCullMask(TERRAIN_ENABLED_NODE_MASK);
osg::Camera* camera = new osg::Camera();
camera->setViewport(0, 0, width, height);
camera->setProjectionMatrixAsPerspective(m_camera_vertical_fov, aspect_ratio, m_camera_clipping_planes.first, m_camera_clipping_planes.second);
camera->setGraphicsContext(graphics_context);
camera->setCullSettings(cull_settings);
camera->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
return camera;
}
The final results looks like this when moving the camera:
As you can see, the depth of the points seems very wrong, with planes popping in and out of each other.
Does anyone have a clue on how to fix this? Am I even looking at the right part of the code to fix this?
| As suggested by @Scheff'sCat, depth testing was not enabled. Adding the following line fixed my problem.
m_terrain_group->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
|
69,901,249 | 69,918,732 | UE4 C++ APlayerController::GetHUD always return null | Here is my code.
void AFpsCharacter::ClientRPCInitializeHud_Implementation()
{
AFpsPlayerController* PlayerController = (AFpsPlayerController*)GetOwner();
if (IsValid(PlayerController))
{
AFpsPlayerState* State = PlayerController->GetPlayerState<AFpsPlayerState>();
UE_LOG(LogTemp, Log, TEXT("PlayerController now on %s"), *State->GetPlayerName());
HUD = (AFpsHud*)PlayerController->GetHUD(); //AHUD* HUD in AFpsCharacter.
//HUD = Cast<AFpsHud>(PlayerController->GetHUD());
if (!IsValid(HUD))
{
UE_LOG(LogTemp, Log, TEXT("AFpsCharacter::InitializeHud() : HUD is not valid"));
}
}
else
{
UE_LOG(LogTemp, Log, TEXT("PlayerController is not exist"));
}
}
The function ClientRPCInitializeHud() is run when the character is spawned and PlayerController possess it. My problem is the pointer HUD has invalid value. Of course i checked default HUD of GameMode. What can i do for get valid value of APlayerController::GetHUD?
I just follow the step below to run ClientRPCInitializeHud.
Run PlayerController's function on button event in Widget Blueprint .
Run ServerRPCSpawnAsPlayableCharacter function
Run ClientRPCInitializeHud function after call APlayerController::Possess(SpawnedCharacter).
Here is the code.
void AFpsPlayerController::OnSelectedTeam(EPlayerTeam team, TSubclassOf<class AFpsCharacter> CharacterClass, FTransform SpawnTransform)
{
ServerRPCSetTeam(team);
ServerRPCSpawnAsPlayableCharacter(CharacterClass, SpawnTransform);
}
void AFpsPlayerController::ServerRPCSpawnAsPlayableCharacter_Implementation(TSubclassOf<AFpsCharacter> CharacterClass, FTransform SpawnTransform)
{
FActorSpawnParameters SpawnParameters;
AFpsCharacter *SpawnedCharacter = GetWorld()->SpawnActor<AFpsCharacter>(CharacterClass, SpawnTransform.GetLocation(), SpawnTransform.GetRotation().Rotator(), SpawnParameters);
SpawnedCharacter->SetSpawnTransform(SpawnTransform);
Possess(SpawnedCharacter);
SpawnedCharacter->OnPossess();
}
void AFpsCharacter::OnPossess()
{
ClientRPCInitializeHud();
}
I tried to check GetPlayerController(0)->GetHUD is valid or not if is called at Level Blueprint or Widget Blueprint but it is also invalid.
| I guess the problem is the default HUD instance isn't created by default HUD class of GameMode. I don't know well why it is happened even i checked default HUD class in GameMode. So i choose temporary solution. Using APlayerController::ClientSetHUD(TSubclass<AHUD>). In my case, each ACharacter has TSubclassOf<AHUD> and run APlayerController::ClientSetHUD(TSubclass<AHUD>) at APlayerController::OnPossess(APawn* InPawn).
|
69,901,358 | 69,902,111 | Comparing same types with different names | I've got
typedef void* TA;
typedef void* TB;
I need to compare names of types as different types.
There are std::is_same<TA, TB>::value and typeid(TA)==typeid(TB) return true, but I need false.
| That is not possible because they are the same type.
If you are trying to use these as opaque handles with strong type-checking, another thing you can do is to forward-declare the classes in a header, and define them in your implementation file:
// ta_tb.hpp
typedef struct ta_impl* TA;
typedef struct tb_impl* TB;
Later:
// ta_tb.cpp
struct ta_impl { /* ... */ };
struct tb_impl { /* ... */ };
This enables type-checking for the handles, but doesn't leak the implementation details.
|
69,901,406 | 69,901,715 | How to define the include & lib path when building pybind11 proj | I am building a pybind11 project with Visual Studio (2017). The setup file is like below:
from setuptools import setup, Extension
import pybind11
# The following is for GCC compiler only.
#cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
cpp_args = []
sfc_module = Extension(
'test_sample',
sources=['Test.cpp'],
include_dirs=[pybind11.get_include()],
language='c++',
extra_compile_args=cpp_args,
)
setup(
name='test_sample',
version='1.0',
description='Python package with Test C++ extension (PyBind11)',
ext_modules=[sfc_module],
)
Then in the windows power shell, I will run
python setup.py build
However it complains cannot find multiple include files, I believe it will complain about missing library files later too:
C:\VS2017Pro\VC\Tools\MSVC\xxxx\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Anaconda3_CS\lib\site-packages\pybind11\include -IC:\Anaconda3_CS\include -IC:\Anaconda3_CS\include -IC:\VS2017Pro\VC\Tools\MSVC\xxxx\ATLMFC\include -IC:\VS2017Pro\VC\Tools\MSVC\xxxx\include /EHsc /TpCppPython.cpp /Fobuild\temp.win-amd64-3.7\Release\Test.obj
Test.cpp
Z:\test_pybind11\stdafx.h(8): fatal error C1083: Cannot open include file: 'targetver.h': No such file or directory
I know where this targetver.h is, just don't know how to add its location to the include path.
Your help will be greatly appreciated.
| I know where to add more include paths, and the lib paths. One need to add them in the system environment variables: INCLUDE and LIB.
Control Panel->Edit Environment Variable. Then add all the intended paths for include files to the variable INCLUDE, and add all the library paths to the variable LIB.
Then the rebuild should be successful.
|
69,901,682 | 69,903,562 | Debug Assertion Fail (vector subscript out of range) | I found that my result.push_back(make_pair(a[i], b[j]));, which
causing this error but i dont know why (i don't even access vector<pair<int,int>>result;)
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<utility>
using namespace std;
void input(int n,vector<int>&a) {
int temps;
for (int i = 0; i < n; i++) {
cin >> temps;
a.push_back(temps);
}
}
int main() {
//input
long n, m;
cin >> n; //6
vector<int>a, b;
input(n, a); //{2 5 4 1 7 5}
cin >> m; //7
input(m, b); //{2 3 1 3 2 4 6}
//algorithm
long max = *max_element(a.begin(), a.end()) + *max_element(b.begin(), b.end());
long min = *min_element(a.begin(), a.end()) + *min_element(b.begin(), b.end());
vector<pair<int, int>>result;
int possible = max, plate = 0;
for (int check = max; check >= min; check--) {
int j = 0, i = 0, plate2 = 0;
for (; i < a.size(); i++) {
if (a[i] >= check) {}
else {
if (j > b.size() - 1) { break; }
if (a[i] + b[j] >= check) {
j++; plate2++;
result.push_back(make_pair(a[i], b[j]));
}
else {
i--; j++;
}
}
}
if (i > a.size() - 1) { possible = check; plate = plate2; break; }
}
cout << possible << " " << plate << endl; //5 3
return 0;
}
if you remove the line result.push_back(make_pair(a[i],b[j]);, there is no error message anymore, so i think i'm not access wrong a[i] and b[j] elements
| if (j > b.size() - 1) { break; } //(1)
if (a[i] + b[j] >= check) { //(2)
j++; plate2++; // HERE IS YOUR PROBLEM (3)
result.push_back(make_pair(a[i], b[j])); //(4)
Assume that j == b.size()-1 at the beginning. The if (j > b.size() - 1) clause is false, so the loop does not break. It continues with (2), which is okay. In (3) you add +1 to j, so now j == b.size(). In (4) you try to access b[j], which is now b[b.size()], which is invalid, as indizes start at 0.
IOW: You tried to assure that j never points beyond the number of valid elements, but then you increment j after that test and access invalid memory.
|
69,901,741 | 69,902,171 | Automate repeated code for various types? | Is there is any way by which I can automate this
DeserializeComponent<IDComponent>(json, e);
DeserializeComponent<NameComponent>(json, e);
DeserializeComponent<PointLightComponent>(json, e);
// ...
As you can see here, the same code is executed for different types, but in C++ you can't store types in a std::vector as far as my knowledge goes. Is there is any way by which I can automate this? Like looping over the components that I add to a vector in application startup? Also, I want to avoid RTTI.
| Types can't be stored in variables. Types are only for the compiler. Even RTTI doesn't store types in variables, but rather "names" of types.
I think you just want to make the code shorter by not having to type DeserializeComponent<>(json, e); over and over. Well, you can do that with parameter pack expansion.
template<typename... Components>
void DeserializeComponents(json_t& json, e_t& e)
{
(DeserializeComponent<Components>(json, e), ...);
}
// ...
DeserializeComponents<IDComponent, NameComponent, PointLightComponent>(json, e);
The magic is in typename... Components - which says Components is not just one type argument but a list of type arguments - and (DeserializeComponent<Components>(json, e), ...); which says to copy-paste the function call for each Components argument, and join them together with the comma operator ,
When the compiler expands the template, the expanded template looks like this:
void DeserializeComponents<IDComponent, NameComponent, PointLightComponent>(json_t& json, e_t& e)
{
(
DeserializeComponent<IDComponent>(json, e),
DeserializeComponent<NameComponent>(json, e),
DeserializeComponent<PointLightComponent>(json, e)
);
}
|
69,901,977 | 69,902,567 | How to get all child objects of a class | Is it possible to retrieve a list of child objects (of a cetain type) of an object ?
For example in this code I have an App with several available Commands. A function print all availible commands this way the user knows what he can do.
I want to iterate over each object of type Command found in App to print his doc, this way the doc updates itself automatically every time a Command is added in App.
class Command {
public:
std::string Name;
std::string Description;
virtual void Compute() = 0;
};
class StartCommand : public Command {
std::string Name = "start";
std::string Description = "Start the process";
virtual void Compute() {
// Code to start the process
}
};
class StopCommand : public Command {
std::string Name = "stop";
std::string Description = "Stop the process";
virtual void Compute() {
// Code to stop the process
}
};
class App {
public:
StartCommand StartCommand;
StopCommand StopCommand;
void PrintAvailibleCommands() {
std::cout << "All availible commands are: " << std::endl;
for (Command command : this.GetObjects<Command>()) {
std::cout << command.Name << ": " << command.Description << std::endl;
}
}
};
It's the this.GetObjects<Command>() function which does not exist and which I would like to implement.
Do you have an idea ?
| This may solve your problem.
#include <cassert>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class Command {
public:
std::string Name;
std::string Description;
Command(std::string Name, std::string Description)
: Name(Name), Description(Description) {}
virtual void Compute() = 0;
};
class StartCommand : public Command {
public:
StartCommand() : Command("start", "Start the process") {}
virtual void Compute() {
// Code to start the process
cout << "startcmd compute" << endl;
}
};
class StopCommand : public Command {
public:
StopCommand() : Command("stop", "Stop the process") {}
virtual void Compute() {
// Code to stop the process
cout << "stopcmd compute" << endl;
}
};
class App {
public:
App() {
commands.push_back(&startCommand);
commands.push_back(&stopCommand);
}
StartCommand startCommand;
StopCommand stopCommand;
vector<Command *> commands;
void PrintAvailableCommands() {
std::cout << "All available commands are: " << std::endl;
for (Command *command : commands) {
std::cout << command->Name << ": " << command->Description
<< std::endl;
}
}
};
int main() {
App app;
app.PrintAvailableCommands();
app.startCommand.Compute();
app.stopCommand.Compute();
return 0;
}
|
69,902,222 | 69,902,302 | Print struct pointer using function c++ | The problem is that the program does not print any values when using the pointer, I searched a lot and there seems to be no solution. any ideas?
#include <iostream>
using namespace std;
struct Brok{
string name;
int age;
void pt(){
cout << "Name : " << name << "\nAge : " << age;
}
};
int main()
{
Brok *a1;
a1->name = "John Wick";
a1->age = 46;
a1->pt();
return 0;
}
Output:
...Program finished with exit code 0
Press ENTER to exit console.
| You need to allocate the object a1 is "pointing to", e.g. Brok *a1 = new Brok();.
EXAMPLE:
/*
* SAMPLE OUTPUT:
* g++ -Wall -pedantic -o x1 x1.cpp
* ./x1
* Name : John Wick
* Age : 46
*/
#include <iostream>
using namespace std;
struct Brok{
string name;
int age;
void pt(){
cout << "Name : " << name << "\nAge : " << age;
}
};
int main()
{
Brok *a1 = new Brok();
a1->name = "John Wick";
a1->age = 46;
a1->pt();
return 0;
}
|
69,902,400 | 69,902,517 | While loop breaks early | I've made a program that asks for student information (name, course and grade) and it is configured to break whenever the input name of a course or a student is stop
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> v;
string name;
string course;
string grade;
while (name != "stop") {
cout << "Please type a student name: ";
getline(cin, name);
if (name != "stop") {
v.push_back(name);
}
while (course != "stop") {
cout << "Please type a course name: ";
getline(cin, course);
if (course != "stop") {
v.push_back(course);
}
if(course != "stop" == 0){
break;
}
else {
cout << "Please type the grade: ";
getline(cin, grade);
v.push_back(grade);
}
}
}
//for (auto iter = v.begin(); iter != std::prev(v.end()); ++iter){
// std::cout << *iter << std::endl;
//}
return 0;
}
I want the program to ask for a new student whenever the first students course is called "stop", but that just means that whenever the new student name is typed, the while loop for "course" keeps "breaking" because the last course entered is "stop".
Any ideas on how to fix this?
Sorry if the question is elaborated badly, let me know if you need more clarification!
Thanks :)
| For starters this if statement
if (name != "stop") {
should be enlarged and include the inner while loop that should be rewritten as a do while loop.
For example
while (name != "stop") {
cout << "Please type a student name: ";
getline(cin, name);
if (name != "stop") {
v.push_back(name);
do
{
cout << "Please type a course name: ";
getline(cin, course);
if (course != "stop") {
v.push_back(course);
cout << "Please type the grade: ";
getline(cin, grade);
v.push_back(grade);
}
} while ( course != "stop" );
}
}
Also as @Remy Lebeau wrote in a comment the outer while loop also can be rewritten as a do-while loop.
|
69,902,639 | 69,903,739 | How can I avoid relative paths in #includes when building with Bazel | I'm struggling to understand the logic of how includes work in Bazel targets. I want my code to be modular, so I am trying to avoid #include statements with relative or long absolute paths.
Suppose I have the following workspace structure:
tree .
.
├── BUILD
├── is_binary_tree
│ ├── BUILD
│ └── is_binary_tree.cpp
├── lib
│ ├── BUILD
│ ├── graphs.cpp
│ └── graphs.h
└── WORKSPACE
I'm getting the following warning when trying to bazel build //is_binary_tree:is_binary_tree and I don't understand what it means :
WARNING: /is_binary_tree/BUILD:1:10:
in includes attribute of cc_binary rule
//is_binary_tree:is_binary_tree: '../lib' resolves to 'lib' not below
the relative path of its package 'is_binary_tree'. This will be an
error in the future
Why would ../lib resolve to lib. Lib should be in the parent directory of is_binary_tree, so from the standpoint of is_binary_tree it can be found at ../lib, isn't this right?
To get rid of the relative path and avoid having something like #include ../lib/graphs.h in is_binary_tree/is_binary_tree.cpp I added an includes attribute to my is_binary_tree target like so:
is_binary_tree/is_binary_tree.cpp
#include "graphs.h"
int main(){
return 0;
}
is_binary_tree/BUILD
cc_binary(
name="is_binary_tree",
srcs=["is_binary_tree.cpp"],
includes=["../lib"],
deps=["//lib:graphs"],
)
And I'm getting the aforementioned WARNING. What am I missing?
And more broadly, what is the best way to include dependencies without having long relative paths in #include statements ? (I want my code to be modular and not specific to a given Bazel workspace folder organization)
Thanks
| That includes should go in //lib:graphs, so that anything which depends on it (has it in deps) uses it. lib/BUILD should look like this:
cc_library(
name = "graphs",
hdrs = ["graphs.h"],
srcs = ["graphs.cpp"],
includes = ["."],
visibility = ["//visibility:public"],
)
Then you drop includes from is_binary_tree and it should work.
In general, each Bazel target contains information about its files. It depends on other targets to use their files.
More broadly, Bazel defaults to #include paths relative to the base of the repository. That means you'd write #include "lib/graphs.h" in any file, whether that's is_binary_tree/is_binary_tree.cpp or x/y/z/foobar.cpp. That avoids collisions between graphics/constants.h and audio/constants.h, without using absolute paths.
|
69,902,741 | 69,902,889 | Constructor invocation in C++ | I tried to find out the output of this program in C++.
#include<iostream>
using namespace std;
class MyInt {
int i;
public:
MyInt() {
cout<<1;
i = 0;
}
MyInt(int i) {
cout<<2;
this->i = i;
}
int value(){
return i;
}
};
int main() {
MyInt i;
i = 10;
cout<<i.value();
}
I expected the output to be 210 but the output of the program is 1210.
So why are both the default constructor and parameterized constructor invoked in this case?
| MyInt i;
The above line invokes MyInt::MyInt(), creating an object and outputting 1.
i = 10;
The above line invokes MyInt::MyInt(int i), creating another object and outputting 2. The second object is then assigned to the first object, which outputs nothing.
cout<<i.value();
The above line invokes MyInt::value(), outputting 10.
|
69,903,058 | 69,903,138 | Why move assignment in my class wasn't called? | Consider this code:
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
struct BigInteger
{
vector<int> arr;
BigInteger()
{
cout << "default constructor" << endl;
this->arr.push_back(0);
}
BigInteger(initializer_list<int> il)
{
cout << "initializer_list constructor" << endl;
for (const int x : il)
{
arr.push_back(x);
}
}
BigInteger(const BigInteger& obj) //copy constructor
{
cout << "copy constructor" << endl;
this->arr = obj.arr;
}
BigInteger(BigInteger&& obj) //move constructor
{
cout << "move constructor" << endl;
swap(*this, obj);
}
~BigInteger() //destructor
{
cout << "destructor" << endl;
arr.clear(); //probably because of RAII, I guess I don't have to write this
}
BigInteger& operator=(const BigInteger& rhs)
{
cout << "copy assignment" << endl;
BigInteger tmp(rhs);
this->arr = tmp.arr;
return *this;
}
BigInteger& operator=(BigInteger&& rhs) noexcept
{
cout << "move assignment" << endl;
swap(*this, rhs);
return *this;
}
};
int main()
{
BigInteger another = BigInteger({0, 1, 2});
}
So, I'm creating a temporary object BigInteger({0, 1, 2}) and then doing the move assignment for my class instance a (theoretically). So expected output is:
initializer_list constructor //creating temporary object
default constructor //creating glvalue (non-temporary) object
move assignment
destructor
But the output is:
initializer_list constructor
destructor
And I don't even understand why is that happening. I suspect that operator= is not the same as initialization, but still I don't understand how my object is constructed.
| Primarily, move assignment operator isn't called because you aren't assigning anything. Type name = ...; is initialisation, not assignment.
Furthermore, there isn't even move construction because BigInteger({0, 1, 2}) is a prvalue of the same type as the initialised object, and thus no temporary object will be materialised, but rather the the initialiser of the prvalue is used to initialise another directly, as if you had written BigInteger another = {0, 1, 2}; (which is incidentally what I recommend that you write; There's simply no need to repeat the type).
I suspect that operator= is not the same as initialization
This is correct. Assignment operator and initialisation are two separate things. You aren't using the assignment operator in this example.
|
69,903,174 | 69,903,753 | C++ how to copy contents of std::array to another? | Its fairly well known on how to copy a standard c array into another:
char test[20] = "asdasd";
char test2[19] = "asdassdsdfd";
strcpy_s(test, sizeof(test), test2);
But how can I do the same with a std::array? (preferably without for loops)
std::array<char, 20> test = {"asdasd"};
std::array<char, 19> test2 = {"asdassdsdfd"};
// copy test2 into test
| There are many ways. You could use strcpy_s(test.data(), sizeof(test), test2.data()), but I wouldn't recommend it. The more-generic version of basically the same thing is std::copy_n(test.begin(), test.size(), test2.begin()); which would continue to be correct even if the type in the std::arrays changes. Given they are statically sized, I'd throw in a static_assert(test.size() <= test2.size()); for good measure.
|
69,903,891 | 69,904,034 | Is it legal to cast array of wrapper structs containing POD to the array of POD type it contains? | Is this C++ code valid or undefined behaviour? The idea is to be able to wrap a POD you have no control over into another struct to provide helper functions but still be able to use it as if it was the original POD.
struct Data
{
...//POD
};
struct Wrapper
{
Data data;//contains only this
void HelperFuncA();
void HelperFuncB();
...//only member functions
};
...
//is this legal?
std::vector<Wrapper> vec_of_wrappers;
Data* array_of_data = reinterpret_cast<Data*>(vec_of_wrappers.data());
| Now, this code is not valid. There are several reasons for this. First, casting a pointer to the first member of the struct to the struct itself violates strict aliasing rule. This you can fix by making Wrapper a child class of the Data.
The second issue is more problematic, as you are trying to treat an array (vector in this case) polymorphically. sizeof Data is different from the sizeof Wrapper, so an attempt to index an array of Wrapper elements as if it was an array of Data elements will end up pointing into random areas of the array.
|
69,904,119 | 69,904,212 | Minimum number of squares | There is a problem that states:
John has a piece of paper with NxM dimensions, he wants to cut it into
1x1 squares, with the rules:he can cut the piece of paper only once at
a certain time, every cut has to go all the way around the paper
This is the code for it:
int n , m;
cin >> n >> m;
cout << (n - 1) + 1LL * n * (m - 1);
Can somebody explain why do you solve it like this?
| This is my understanding of the question based on the answer:
You cut the paper into N equal length pieces. Each has a length of 1 and width of M. This requires (N-1) cuts.
For each of these N sheets, you cut them into M equal pieces which have 1 width and 1 length. This requires (M-1) for each sheet so, N * (M-1) in total.
Therefore the result is (N-1) + N * (M-1)
|
69,904,152 | 69,904,279 | Reading integer then rest of the line as a single string from input | Suppose I'm trying to read from the following input.txt
6 Jonathan Kim Jr
2 Suzie McDonalds
4 Patty
... and I want to store the first integers from every line and the rest of the strings as a string variable. This is what I have tried:
int num;
string name1, name2, name3;
while ( ins >> num >> name1 >> name2 >> name3 )
{
// do things
}
Unfortunately this won't work since line 2 and line 3 only has 2 and 1 strings in a respective order so the loop will terminate at the very first loop.
Is there a way to store the rest of the strings after an integer in a single variable, including the white spaces? For example, string variable name would hold:
"Jonathan Kim Jr" // first loop
"Suzie M" // second loop
"Patty" // third loop
I thought about using getline to achieve this as well, but that would require me to isolate the integers from the string and I was hoping there's a better approach do this. Perhaps using a vector?
| By default, the >> operator splits on a space, so you could use that to pull the integer into the variable. You could then use getline to grab the rest of the line, and store that into the variable.
Example (if you are reading from std::cin):
int num;
std::string name;
std::cin >> num;
std::getline(std::cin, name);
|
69,904,573 | 69,905,066 | Optional template parameter combinatorials | I have a set of template specializations (C++11) that uses the base template below, where both tPayLoad and tReturnType is present:
template <class tDerivedOperation, class tBridgeType, class tPayLoadType = void, class tReturnType = void> class OperationT ...
The 1st specialzation is when there is neither tPayLoadType nor tReturnType:
template <class tDerivedOperation, class tBridgeType> class OperationT<tDerivedOperation, tBridgeType, void, void> ...
The second specialization is when there is only tPayLoadType:
template <class tDerivedOperation, class tBridgeType, class tPayLoadType> class OperationT<tDerivedOperation, tBridgeType, tPayLoadType, void> ...
Finally, I want the 3rd case (4th combination), having no tPayLoadType but a tReturnType, and that is where the problem pops up. I can't use (I think):
template <class tDerivedOperation, class tBridgeType, class tReturnType> class OperationT<tDerivedOperation, tBridgeType, void, tReturnType> ...
since that is essentially the same as specialization 2. Anyone having an idea of how to do this, if it's even possible???
/N
| The following
#include <iostream>
template<class tDerivedOperation, class tBridgeType, class tPayLoadType = void, class tReturnType = void>
struct OperationT {
static constexpr auto overload = "base";
};
template<class tDerivedOperation, class tBridgeType>
struct OperationT<tDerivedOperation, tBridgeType, void, void> {
static constexpr auto overload = "both void";
};
template<class tDerivedOperation, class tBridgeType, class tPayLoadType>
struct OperationT<tDerivedOperation, tBridgeType, tPayLoadType, void> {
static constexpr auto overload = "back void";
};
template<class tDerivedOperation, class tBridgeType, class tReturnType>
struct OperationT<tDerivedOperation, tBridgeType, void, tReturnType> {
static constexpr auto overload = "front void";
};
int main() {
std::cout << OperationT<int, int>::overload << '\n';
std::cout << OperationT<int, int, int>::overload << '\n';
std::cout << OperationT<int, int, void, int>::overload << '\n';
std::cout << OperationT<int, int, int, int>::overload << '\n';
}
gives the output
both void
back void
front void
base
exactly as one would expect. Does this answer your question?
|
69,905,020 | 69,905,092 | What is the best/most intuitive way for a class to store a reference to a unique_ptr? | I have a class that manages a vector of unique_ptrs:
class Foo
{
public:
...
private:
std::vector<std::unique_ptr<SomeClass>> vec_;
};
I have another class, Bar, that I want to store some reference type that refers to an object in the vector. What is the most logical and intuitive way to achieve this?
The ones I can think of are four options:
Bar stores a reference
struct Bar
{
Bar(std::unique_ptr<SomeClass>& ref) : ref_(ref) {}
std::unique_ptr<SomeClass>& ref_;
};
This is simple enough, but references can't be reset without constructing the object again. Is this still the preferred method?
Use shared_ptrs both in Foo and Bar
class Foo
{
public:
...
private:
std::vector<std::shared_ptr<SomeClass>> vec_;
};
struct Bar
{
std::shared_ptr<SomeClass> ref_;
};
The problem with this one is that it implies that Foo and Bar have equal ownership over the object, even though Foo should have ownership. But maybe that isn't such a big deal? The reason I hesitate is that I've read that you should only use shared_ptr if the ownership really is equal. I also know that shared_ptr comes with quite some overhead compared to unique_ptr.
Use a weak_ptr to show that Bar does not have ownership of the object (however, forcing you to still use a shared_ptr in Foo)
struct Bar
{
std::weak_ptr<SomeClass> ref_;
};
This one seems like a nice and clean method to me. The only flaw I can see is that we have to use a shared_ptr in Foo even though Foo has sole ownership.
Use unique_ptr::get to get a raw pointer that Bar stores
struct Bar
{
SomeClass* ref_;
}
This is my least favorite option. The whole reason we use smart pointers is to avoid having to work with raw pointers. It feels silly to use them for something as simple as referencing a smart pointer.
Which of these options is preferred when factoring in performance and code maintainability, or is it subjective?
|
The whole reason we use smart pointers is to avoid having to work with raw pointers
No: the whole reason we use smart pointers is to avoid having to work with owning raw pointers.
See, for reference, the C++ Core Guidelines:
R.3: A raw pointer (a T*) is non-owning
We do indeed prefer smart pointers to own resources. However, this doesn't own the resource, so using a raw pointer is fine.
Your alternatives from worst to best:
Bar stores a reference: if you ever want to reseat it, don't use a reference. You say you do want to reseat it, so this is out. There's no benefit in trying to work around this, it just makes your code more surprising and no better.
Use shared_ptr in both places: do this if you need the object kept alive so long as a reference to it exists.
Don't worry about "equal ownership", worry about whether the semantics make sense for your program. Your job is to decide whether resetting the pointer in Foo::vec_ should destroy the object, not to express the communist manifesto in C++.
Use shared_ptr plus weak_ptr: if you want Bar to detect that the object has been destroyed.
The advantage is that it documents the relationship nicely, and you don't have to worry about accidentally accessing a dangling pointer in between updating Foo and Bar.
|
69,905,120 | 69,908,358 | How to put what the user picks for the row and column in the board | So my question is how do I put what the user enters, for example, they put row : 1 and column: 2 in my board that I made. I'm working on this in the void playerChoice function.
I've thought of some solutions to this problem like board[row][column] = 'X' in like an if statement with board[row][column] = 'O' as well. Is this alright?
Hopefully you guys can help figure this problem this out with me.
const int ROWS = 3; // For the rows
const int COLS = 3; // For the number of columns;
void showBoard(const char[][COLS], int); // Shows the board
void playerChoice(char[][COLS], char); // shows the player choice
int winner(const char[][COLS],
const char, string);
int main() {
char board[ROWS][COLS] = {
{
'*',
'*',
'*'
},
{
'*',
'*',
'*'
},
{
'*',
'*',
'*'
}
};
string winner = " ";
showBoard(board, 3); // displays the board
for (int i = 0; i < 3; i++) {
playerChoice(board, 'X');
showBoard(board, 3);
playerChoice(board, 'O');
showBoard(board, 3);
}
cout << "The winner is:" << winner;
}
void showBoard(const char arr[][COLS], int SIZE) {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++)
cout << '|' << arr[row][col];
cout << '|' << endl;
}
}
void playerChoice(char arr[][COLS], char name) {
int row, columns;
cout << "What row would you like?\n";
cout << "Row: ";
cin >> row;
while (row < 1 || row > 3) {
cout << "Error please pick a row in between 1 and 3.\n";
cout << "Row: ";
cin >> row;
cout << endl;
}
cout << "What column would you like?\n";
cout << "Column: ";
cin >> columns;
while (columns < 1 || columns > 3) {
cout << "Error,please pick a row in between 1 and 3.\n";
cout << "Column: ";
cin >> columns;
cout << endl;
}
}
int winner(const char[][COLS],
const char, string) {
// working on this.
return winner;
}
|
I've thought of some solutions to this problem like board[row][column]
= 'X' in like an if statement with board[row][column] = 'O' as well.
Yes. You can try the code below:
if (arr[row - 1][columns - 1] == '*')
{
arr[row - 1][columns - 1] = name;
}
else
{
cout << "Retry" << endl;
playerChoice(arr, name);
}
|
69,905,226 | 69,910,082 | Display modified data from QAbstractListModel in QTableView | I have a QAbstractListModel that has a bunch of custom objects stored in it, and you can access the different fields of the custom objects in the model by specifying a role (if this is an improper use of Qt roles let me know because I must be confused). I want to display this data in a user friendly QTableView. I can get things displaying using a proxy model, but the issue is I don't want to display the raw values, I want to display specific data derived from the raw data. So for instance, I don't want a column for both ItemA.foo and ItemA.bar, I want to display just ItemA.foo - ItemA.bar in a single column. And to add to that, I want the automatic update functionality you get with models where if either ItemA.foo or ItemA.bar change, I want the difference column to automatically update and recalculate.
I would think that the way to do this would be to use some kind of table proxy model that listens to the source model, and then populates its own fields with the values derived from the source model and listens for dataChanged() signals from the source model. Then you plug this proxy model in to a QTableView. But to me this sounds like something that should be done in a view. Or is this something that should be done by the delegate? I could even go so far as to do these calculations in the base model itself and add roles specific to these values that should be displayed in the table, but that sounds like I am really overloading the responsibilities of the model.
TLDR: How do you manipulate data from a model in a QTableView? Should I do the data manipulation in the base model and then send that to the QTableView? Should I use a proxy model that manipulates the base data and sends it to the QTableView? Or am I completely misunderstanding something?
|
and you can access the different fields of the custom objects in the model by specifying a role
If you look at the documentation for Qt::ItemDataRole, you would see that Qt models should indeed provide different data for different roles but each role means some distinguished purpose of the data corresponding to the role. For example, the most commonly used role is probably Qt::DisplayRole as the data for this role defines the content displayed in the view e.g. it's the text in the table cell. If you are satisfied with all the other aspects of the view - font, background etc - you can just return empty QVariant for corresponding roles from your model, the view would figure out these details on its own. If you are using roles as a substitute for columns i.e. to return different pieces of conceptually the same data item, it is probably not the intended use of roles.
For the other part of your question - you can customize the appearance of data displayed in the view through the use of a delegate. For example, you could subclass QStyledItemDelegate, override its displayText method to display ItemA.foo - ItemA.bar instead of just ItemA.foo and then set this delegate into the column of your view corresponding to ItemA.foo via setItemDelegateForColumn. The tricky part here would be to detect changes in both ItemA.foo and ItemA.bar columns which would affect the text displayed in the delegate. A while back I implemented a dedicated class in one of my projects which listens to changes in some column of the original model and "reroutes" the change into another column through signal emitting. I did it to solve this very issue - to catch changes in what delegate should display although technically another model column is affected into which the delegate is not set.
|
69,905,233 | 69,905,767 | How can I fix my C++ code ? (no match for operators) | How can I fix my C++ code ? (no match for operators)
I got an error : no match for "operators-". What can be the problem and how can I solve it?
Can anybody help me to fix it ?
error: no match for 'operator-' (operand types are 'std::set::iterator' {aka 'std::_Rb_tree_const_iterator'} and 'std::set::iterator' {aka 'std::_Rb_tree_const_iterator'})|
#include <iostream>
#include <set>
using namespace std;
int main()
{
int O;
int N;
int M;
cin >> O >> N >> M;
int tanarsorszama[O];
int tantargysorszama[O];
int nap [O];
int ora [O];
for(int i=0; i<O; i++)
{
cin >> tanarsorszama[i] >> tantargysorszama[i] >> nap[i] >> ora[i];
}
int dblyukas[N]={0};
set<int>orai;
for(int i=0; i<N; i++)
{
for(int k=1; k<6; k++)
{
orai.clear();
for(int j=0; j<9; j++)
{
if(tanarsorszama[i]!=0 && ora!=0 && nap[k]!=0)
{
orai.insert(ora[j]);
}
}
if (orai.size() > 1)
{
dblyukas[i] += orai.end() - orai.begin() +1 - orai.size(); // There is the error
}
}
}
return 0;
}
| std::set doesn't have random-access iterators. That is why you are getting the error.
To access the first and last elements of a set, use orai.begin() and std::prev(orai.end()). These return iterators, which will have to be de-referenced with operator*. So, correcting what I think you are intending to do, leads to the following:
if (orai.size() > 1)
{
dblyukas[i] += *std::prev(orai.end()) - *orai.begin() +1 - orai.size(); // There is the error
}
|
69,906,614 | 69,906,677 | C++ how to check for all variadic template type in a member function | e.g. I have the following Foo class with the foo() to check if all the types are std::int32_t
class Foo {
public:
/// check if all the types are std::int32_t
template<typename ...Ts>
bool foo() {
return true && std::is_same<Ts, std::int32_t>::value...;
}
};
int main()
{
Foo f;
std::cout<<f.template foo<std::int32_t, std::int32_t>(); //true
std::cout<<f.template foo<std::int32_t, std::int64_t>(); //false
return 0;
}
return true && std::is_same<Ts, std::int32_t>::value...; is not a correct syntax. How do I make it correct?
| https://en.cppreference.com/w/cpp/language/fold
return (true && ... && std::is_same<Ts, std::int32_t>::value);
# or
return (std::is_same<Ts, std::int32_t>::value && ... && true);
# or really just
return (std::is_same<Ts, std::int32_t>::value && ...);
|
69,906,870 | 69,906,904 | const int, member array size | My code basically:
class myclass : public singleton<myclass> {
public:
myclass();
private:
const float myfloat = 6000.0f;
const int sz_arr = (int)myfloat;
int arr[sz_arr]; // compiler complains about this line
};
Need to create arr at compile-time. Size of arr is known at compile-time! Ought to be computed based on myfloat value. How to achieve it? Also, myclass is singleton, only one instance of it is ever going to be created.
| Firstly, sz_arr can't be used to specify the size of the array, you need to make it static. And mark myfloat as constexpr to make it known at compile-time (and better for sz_arr too).
class myclass : public singleton<myclass> {
public:
myclass();
private:
constexpr static float myfloat = 6000.0f;
constexpr static int sz_arr = myfloat; // implicit conversion is enough
int arr[sz_arr];
};
|
69,907,247 | 73,815,163 | Eigen sparse solvers give drastically different solutions for the same linear system | I am trying to solve a sparse linear system as quickly as possible using eigen.
The docs give you 4 sparse solvers toc hoose from (but really it;s more like these three):
SimplicialLLT
#include<Eigen/SparseCholesky> Direct LLt factorization SPD Fill-in reducing LGPL
SimplicialLDLT is often preferable
SimplicialLDLT
#include<Eigen/SparseCholesky> Direct LDLt factorization SPD Fill-in reducing LGPL
Recommended for very sparse and not too large problems (e.g., 2D Poisson eq.)
SparseLU
#include<Eigen/SparseLU> LU factorization Square Fill-in reducing, Leverage fast dense algebra MPL2
optimized for small and large problems with irregular patterns
When I use the last solver, i.e. I do:
Eigen::SparseLU<Eigen::SparseMatrix<Scalar>> solver(bijection);
Assert(solver.info() == Eigen::Success, "Matrix is degenerate.");
solver.compute(bijection);
Assert(solver.info() == Eigen::Success, "Matrix is degenerate.");
Eigen::VectorXf vertices_u = solver.solve(u);
Assert(solver.info() == Eigen::Success, "Matrix is degenerate.");
Eigen::VectorXf vertices_v = solver.solve(v);
Assert(solver.info() == Eigen::Success, "Matrix is degenerate.");
I get the correct result, which graphically looks like this:
If I use simplicialLDLT, i.e. if I change the solver line and nothing else to:
Eigen::SimplicialLDLT<Eigen::SparseMatrix<Scalar>> solver(bijection);
I get this degenerate monstrosity:
Basically the two solvers are returining wildely different results for the exact same sparse system. How is this possible?
None of the error checks return false, so in both versions the matrices are considered to be fine.
| https://eigen.tuxfamily.org/dox/group__TopicSparseSystems.html => SimplicialLDLT only for SPD matrices. You might try a least squares approach https://snaildove.github.io/2017/08/01/positive_definite_and_least_square/
|
69,907,324 | 69,907,505 | Word counter returning incorrect number of words | I've been trying to create a program that reads text from a file and stores it in a string. I feed the string to a function that counts every word in the string.
However its only accurate assuming the user leaves some whitespace at the end of a line and doesn't creates blank lines.... not a very good word counter.
Creating a blank line results in a false increment to the word count.
I'm not sure if my main problem is using a boolean to do this or checking for whitespace and '\n' characters.
bool countingLetters = false;
int wordCount = 0;
for (int i = 0; i < text.length(); i++)
{
if (text[i] == ' ' && countingLetters == true)
{
countingLetters = false;
wordCount++;
}
if (text[i] != ' ' && countingLetters == false)
{
countingLetters = true;
}
if (text[i] == '\n' && countingLetters == true)
{
countingLetters = false;
wordCount++;
}
}
| Your code is basically a state machine. To complete your solution, just count in the string ending.
Add this to the end of your code:
if(countingLetters) { // word at the end of string, without any space charactor
wordCount++;
}
Or if you can be sure it's C-style string, like std::string, you can just index 1 pass the last charactor, and handle '\0'in same way of space and '\n' .
To improve your code, use isspace (and this covers more space charactor, including '\t', etc.). And better to use else if pattern. Also, it's not good pratice to ==true. Just use boolean as condition.
Or maybe, isalpha(c) fits more to your need.
bool countingLetters = false;
int wordCount = 0;
for (char c:text) {
if (!isalpha(c) && countingLetters) { // this also works for newline
countingLetters = false;
++wordCount;
} else if (isalpha(c) && !countingLetters) {
countingLetters = true;
} // otherwise just skip
}
if(countingLetters) { // word at the end of string, without any space charactor
++wordCount;
}
And it's not acceptable to insert extra charactor just for such a simple task. For example, text may be const.
|
69,907,598 | 69,916,648 | Why doesn't the Variadic Template Function inside a while loop print to the console? | I want to try the flag-controlled while-loop statement that prints a statement and accept user input using variadic template function? Is this possible?
#include <iostream>
template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }
template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }
auto main() -> int {
int a;
while(a > 100) {
write("Enter a number: ");
read(a);
}
}
| As mentioned in comment, the variable a is not initialized. Hence, the variable contains a garbage value, so it will result into a runtime error.
Therefore first initialize the variable, then run a while loop on it.
And the code need to take the user input using variadic template function. So you can do this:
#include <iostream>
template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }
template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }
auto main() -> int {
int a;
// To initialize a
write("Enter a number: ");
read(a);
while(a > 100) {
write("Enter a number: ");
read(a);
}
}
If do-while loops are allowed, then the below is also a possible solution:
#include <iostream>
template<typename... _args> void write(_args && ...args) { ((std::cout << args), ...); }
template<typename... __args> void read(__args && ...args) { ((std::cin >> args), ...); }
auto main() -> int {
int a;
do {
write("Enter a number: ");
read(a);
}while(a > 100);
}
|
69,907,633 | 69,908,116 | In C++, why the 'iterator object' becomes invalid after calling 'erase()'? | I know the 'grammatical why'.
What I'd like to know is, 'techincal why'.
As far as I know, the 'iterator object' is mimic 'pointer'.
If it really mimics 'pointer', it should 'point' the erased index in the container.
Like, if a vector contains
index 0 1 2 3 4
val 10 20 30 40 50
and
vector<int>iterator iter = veciter.begin();
++iter;
veciter.erase(iter);
then the 'iter' should 'point' the 'index 1' which has value of '30' after calling erase if 'iterator object' really mimics 'pointer'.
But it doesn't.
Why?
What's the purpose?
|
If it really mimics 'pointer', it should 'point' the erased index in the container.
This inference doesn't make sense to me. Pointers are iterators for arrays. It isn't possible to erase elements from arrays, so they cannot be used as an example of how iterators should behave on erasure.
Even if the inference was applicable, you need to understand that iterators are a generalisation of pointers. The intersection of features that are common to all iterators is a subset of features of pointers. It isn't reasonable to assume that all iterators behave the same as pointers in every regard.
why the 'iterator object' becomes invalid after calling 'erase()'?
Because that is the only option that is efficient to implement for all iterators.
Furthermore, iterators are an abstract concept. Try to forget everything about pointers, and concentrate on the following abstract description of iterators: It's an object that refers to an entity, and you can indirect through it (if refers to valid entity) to get an object and you can increment it to move to the next entity (if there is next entity).
Is it intuitive to you that if I refer to something, and that when the referred entity no longer exists, then I am suddenly referring to some other entity? If I indirect through the iterator after the original entity has been destroyed, with the intention of accessing the destroyed entity, then that is a logical error. Getting some other object doesn't improve the situation. Unfortunately though, there isn't an efficient way to generally check for this error either, so it is simple deemed "undefined behaviour".
Since the implementation isn't bound by the standard to return the other object, and is instead free to do whatever, it may attempt to be helpful and detect the error when that is desired (but you cannot rely on that), or it may skip all checks when efficiency is desired in which case the error may cause the program to crash and burn (if you're lucky).
|
69,907,901 | 69,908,739 | Understanding template function declarations | First place I saw syntax I didn't understand was here.
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Had a couple other small questions as I read this.
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
What I (think) I understand:
Templates are used to help keep the DRY principle.
Templates have the common attributes across classes that you want to be able to use.
Let's start with the first code example.
To me, it looks like there are two return types but I think I'm supposed to read it as "this is a template function with <typename T> where T is the class. Therefore, only for this function, declare T as a class which will be determined at compile time and will by the class called T. This function will return an int.
Is that a correct understanding of the function declaration? It seems strange to have to declare template <class T> but it looks like when you have more than one template class you list them like so template <class T, class U>.
Where in the code do we actually declare what attributes T has and fit under that template? Is that what mypair is being declared as in the next block? If I wanted mypair to also be considered a U would I just say template <class T, class U> class mypair {...
Second code example.
The specificate part I'm trying to understand is the declaration for getmax template <class T> T mypair<T>::getmax ()
I think mypair<T>::getmax() is saying that we're declaring the getmax function for mypair. What does the T in mypair<T> refer to?
Final clarification question.
From what I read, it sounds like the main complaint about using templates is that they can increase compile time but it sounds like they have no impact on run time. Right?
| Let's start with:
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Say you call sgn(42). Because 42 is an int, sgn<int> will be need to be instantiated so the signature becomes int sgn(int val) to match the call. Then the body becomes return (int(0) < val) - (val < T(0));, which makes two boolean tests:
is 0 less than val? (another way of saying, is val > 0?)
is val less than 0?
Each of these tests yields a true or false boolean result, and in an arithmetic context (which is created by using a - on the boolean values), true implicitly converts to 1, and false implicitly converts to 0.
So, the possible values are:
(0 < val) - (val < 0)
val > 0 (true - false) == 1 - 0 == 1
val == 0 (false - false) == 0 - 0 == 0
val < 0 (false - true) == 0 - 1 == -1
So the sgn function returns 1 if val is positive, 0 if it's 0, and -1 if it's negative. Put another way, it returns an int indicative of the sign of val.
If you'd instantiated sgn for another type - say double - you'd get logically equivalent behaviour for doubles from a distinct instantiation of the template, with machine code instructions suitable for comparing doubles.
Where in the code do we actually declare what attributes T has and fit under that template?
We don't declare what attributes T has to have, but it is implicit in the use we make of T and the val variable of T type: firstly, there's the T(0) construction that must be supported, and secondly, we must be able to use < to compare T values and get a boolean result back (well, there's nothing checking it returns a bool, but that's normal for operator< and if it returned something else, the - logic would probably break).
Is that what mypair is being declared as in the next block?
No - the T used for sgn is distinct from any other use of T in the program.
Templates have the common attributes across classes that you want to be able to use.
It's hard to even know what you're thinking about there. A template like sgn doesn't even involve a class.
Discussing the other code snippet:
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
Above, getmax is defined out-of-line, but all that is equivalent to:
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax() {
T retval;
retval = a>b? a : b;
return retval;
}
}
When you call the constructor, it will work out a unifying type based on the first and second arguments. For example, if you called with mypair{12, 45.2} it will decide that T = double is suitable, and instantiate the class template for double. You can then simply think of the behaviour the code would have by mentally replacing T everywhere with double. You can also explicitly instantiate a template: mypair<double>{4, 8} would have T, and therefore a and b, be doubles, so the return type of getmax() would also be a double. (The getmax() function should be made const, as it doesn't need to mutate any data members).
|
69,907,931 | 69,908,099 | Zig-zag pattern in C++ using cout function, for and if-else statements | While I was making a program in C++ for a zig-zag pattern I coded it as follows:
#include <iostream>
using namespace std;
int main () {
cout << "how many stars you want in zig zag pattern";
int n;
cin >> n;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= n; j++) {
if ((i + j) % 4 == 0 && i == 1 ) { cout << "*"; }
if (j % 2 == 0 && i == 2) { cout << "*"; }
if ((i + j) % 4 == 0 && i == 3) { cout << "*"; }
else { cout << " "; }
}
cout << endl;
}
return 0;
}
But using this I am not getting the desired pattern.
The non desired pattern by the initial code
Please answer these:
What is the fault in the above code?
What I observed that when I put the other two if-statements in the comment line, I see that the individual statements do their respective jobs but on pairing any two and putting the third one in comment brings non-desired result.Please clear this result also.
Though I have come to know what's the right way as given below I want to know what was the fault in my initial attempt.
#include <iostream>
using namespace std;
int main () {
cout << " how many stars you want in zig zag pattern";
int n;
cin >> n;
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= n; j++) {
if ((i + j) % 4 == 0 || (i == 2 && j % 4 == 0)) { cout << "*"; }
else { cout << " "; }
}
cout << endl;
}
return 0;
}
The desired pattern
I am a beginner, so I request you to use simple terms. Thanking you in advance.
| You program is printing extra spaces because of the way you have wrote the if statements. Look at these statements:
if (((((i+j)%4)==0) && (i==1) )){ cout<< "*";}
if ((( j%2)==0) && ( i==2 )) { cout<< "*";}
if ( ((i+j)%4==0) && (i==3)) { cout << "*";}
else { cout<< " ";}
note that every iteration will check all the 3 if conditions and space character will be printed every time except when the third if condition results in true, irrespective of first and second if condition results (true or false), and this is the cause of problem that you are noticing in your program output.
Lets dry run the inner for loop for value i = 1:
Iteration I : j = 1
First if condition:
i+j = 1+1 = 2
2 % 4 != 0
result: false,
Second if condition ultimately result in false because of '&& ( i==2 )', and
Third if condition ultimately result in false because of '&& (i==3)', so a
space character will be printed
Iteration II: j = 2
First if condition:
i+j = 1+2 = 3
3 % 4 != 0
result: false,
Second if condition ultimately result in false because of '&& ( i==2 )', and
Third if condition ultimately result in false because of '&& (i==3)', so a
space character will be printed
Iteration III: j = 3
First if condition:
i+j = 1+3 = 4
4 % 4 != 0
result: true, '*' will be printed
Second if condition ultimately result in false because of '&& ( i==2 )', and
Third if condition ultimately result in false because of '&& (i==3)', so a
space character will be printed
Here you can see that the third if condition resulting in false and the else part of this if will be executed which will print the undesired space character after the '*' character printed by from if block. Thats why you are getting the extra spaces in your output. Change the if conditions to this:
if (((((i+j)%4)==0) && (i==1) )) { cout<< "*";}
else if ((( j%2)==0) && ( i==2 )) { cout<< "*";}
else if ( ((i+j)%4==0) && (i==3)) { cout << "*";}
else { cout<< " ";}
Note the else in above code, the space should only printed when all the 3 if condition result in false and if any of the if condition result in true only a '*' should be printed. With this your program will output as expected.
|
69,908,310 | 73,515,621 | cannot open source file "locale.h" (dependency of "iostream") | I continue to run into this include error / cannot open source file. I have now also tried resetting all of vs codes setting to default, but nothing I have tried has worked so far. Any advice on where to look would, or what's causing this would be extremely appreciated!
I have tried editing configurations in the json, adding to and editing the include paths and a few other long shot changes that I've come across on here.
I included a screen shot of the errors that I am currently encountering. I read somewhere that installing xcode fixed this issue for other people. But I don't use xcode, nor do I really want to.
My compiler is brew g++-11, I have also checked to make sure that the path in the json and the actual path match. I'm kind of at a loss what to do, I tried asking my professors today for help and they were just as lost. Any advice on where to look for a solution would be amazing.
I have also tried changing the include path from "${workspaceFolder}/**" to "${workspaceFolder}/inc". Which didn't work either.
Here is the current c_cpp_properties.json
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"macFrameworkPath": [],
"compilerPath": "/usr/local/bin/gcc-11",
"cStandard": "gnu17",
"cppStandard": "gnu++17",
"intelliSenseMode": "macos-gcc-x64"
}
],
"version": 4
I also tried to check the intellisense extension settings, but that is admittedly a bit outside of my scope.
| I had the same problem.
Adding this to the include path fixed it:
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1
I got the path from running:
gcc -v -E -x c++ -
Which outputs information about your gcc compiler.
I'm on an M1 Mac running Monterey.
This is my vscode config:
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1"
],
"defines": [],
"macFrameworkPath": [],
"compilerPath": "/opt/homebrew/bin/gcc-11",
"cStandard": "gnu17",
"cppStandard": "gnu++17"
}
],
"version": 4
}
As you see, the compiler is homebrew but the include path is xcode.
|
69,908,612 | 69,908,776 | Cast QList of derived to QList of base | I have these classes:
class IParameter {};
class ModuleParameter : public IParameter {};
Now I have QList of derived:
QList<ModuleParameter*> list;
When I cast single item it's ok:
IParameter *p = list[0]; // ok
When I cast the list I've got an error.
QList<IParameter*> *list = static_cast<QList<IParameter*>*>(&list);
Invalid static_cast from type QList<ModuleParameter*>* to type QList<IParameter*>*.
So, how can I cast?
| QList is a template without common base class type and QList<ModuleParameter*> is a type unrelated to QList<IParameter*>, you can't access QList<ModuleParameter*> polymorphically through a pointer to QList<IParameter*>. What you trying to do is impossible to do this way.
Instead you may store pointers to ModuleParameter in QList<IParameter*> and use cast when accessing them.
|
69,908,758 | 69,908,836 | What is the difference between {} and () in std::visit function? | The following code is basically a more "naive" version of the example on variant found on CPP Reference. It defines a std::variant type (line [1]) and uses std::visit to iterate through a vector of that type. Here, I used a functor (line [2]) inside the std::visit function as an attempt for a better understanding of how std::visit works.
What puzzles me the most lies in lines [4] and [5]. It appears that either Print{}, with curly brackets, or Print(), with parentheses, can serve as the first parameter to std::visit function. The later, i.e., Print(), is an instantiation and is thus supplying an object as the first parameter, which is comprehensible. I don't quite understand why the former, Print{}, works too. Can anyone shed some light on this peculiarity?
using var_t = std::variant<int, long, double, std::string>; // [1]
class Print { // [2]
public:
void operator()(int arg) {
std::cout << "Integer is " << arg << '\n';
}
void operator()(double arg) {
std::cout << "Double precision is " << arg << '\n';
}
void operator()(long arg) {
std::cout << "Long type is " << arg << '\n';
}
void operator()(const std::string& arg) {
std::cout << "String is " << arg << '\n';
}
};
std::vector<var_t> vec = {10, 15l, 1.5, "Hello, World", 900}; // [3]
for (auto& v : vec) {
//std::visit(Print{}, v); // [4]
std::visit(Print(), v); // [5]
}
| Print() is a call to constructor of class Print. Print{} is list initialization of class Print. In this case the difference is only int that list initialization actually would be aggregate initialization and would init members of Print if it had any, the constructor would not.
In both cases you pass an instance of Print.
|
69,908,798 | 69,909,053 | Difference Between Double's Notation | On the learncpp.com there is advice to write doubles as:
double num {5.0}
Is there any real difference between that and:
double num {5}
It seems that my compiler (VS 2019) treats those as equivalent.
| For that specific case, they are effectively equivalent, however, that's not always the case.
For example:
#include <iostream>
void foo(int v) {
std::cout << "foo(int) called\n";
}
void foo(double v) {
std::cout << "foo(double) called\n";
}
int main() {
foo(5.0);
foo(5);
}
That program produces:
foo(double) called
foo(int) called
If only for this reason, it's good to get into the habit of always using a double literal when you want to express a double value, even if an int literal would have worked just as well. Otherwise, sooner or later, you will run into some surprises.
|
69,908,818 | 69,908,844 | C++: How to create a "conditional" constructor/avoid destruct on assignment? | Let's start with some example code:
class Shader {
public:
static absl::StatusOr<Shader> Create(const std::string &vertexShaderFile, const std::string &fragmentShaderFile) {
ASSIGN_OR_RETURN(GLuint vertexShader, gl::createShader(GL_VERTEX_SHADER, readFile(vertexShaderFile)))
ASSIGN_OR_RETURN(GLuint fragmentShader, gl::createShader(GL_FRAGMENT_SHADER, readFile(fragmentShaderFile)))
Shader s;
glAttachShader(s._programId, vertexShader);
glAttachShader(s._programId, fragmentShader);
RETURN_IF_ERROR(gl::linkProgram(s._programId));
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
std::cerr << "AAA" << std::endl;
return s;
}
void use() const {
std::cerr << "use " << _programId << std::endl;
glUseProgram(_programId);
}
~Shader() {
std::cerr << "destruct!" << std::endl;
glDeleteProgram(_programId);
}
private:
explicit Shader() : _programId(glCreateProgram()) {}
GLuint _programId{0};
};
usage:
const auto &_statusOr4 = (Shader::Create("resources/vertex.glsl", "resources/frag.glsl"));
if (!_statusOr4.ok())return _statusOr4.status();
Shader shader = *_statusOr4;
std::cerr << "BBB" << std::endl;
This will print:
AAA
destruct!
BBB
I think the s in Shader::Create is being copied to a new object and then the old one is destructed, which calls the ~Shader destructor.
I want to avoid the copy + destruct.
I can't just throw all the Create code in the c'tor because there's a few operations that might fail.
How can I do this?
Adding
Shader(const Shader&) = delete;
Shader& operator=(const Shader&) = delete;
Prevents this program from compiling. Which is fine, because this is indeed an error, but then I still don't know how to write such a Create method (without moving everything into a constructor and throwing exceptions instead)
I tried to add a move constructor:
Shader(Shader&& o) noexcept : _programId(o._programId){
std::cerr << "move ctor" << std::endl;
}
Had to change the assignment to make it a reference:
const auto &_statusOr4 = (Shader::Create("resources/vertex.glsl", "resources/frag.glsl"));
if (!_statusOr4.ok()) return _statusOr4.status();
const Shader& shader = *_statusOr4;
Which I think should be fine because _statusOr4 will have the same lifetime.
However.... now I get
AAA
move ctor
destruct!
BBB
It seems the destructor is still called on the object that it was "moved" out of.
StatusOr is from Abseil
|
I want to avoid the copy + destruct.
Normally, when your function return type matches the type of the variable you return, you don't need to do anything. There is no copying and no destruction taking place. Read about copy elision.
In your case, you construct Shader but return absl::StatusOr<Shader>. So there are two different objects: the local variable s in your function, and the return value. They are of different types so the compiler cannot make them the same thing, and you will see the destructor of s being called. However this is harmless if you write Shader correctly. Support move construction, and s will be moved to the return value, leaving behind an empty shell that is trivial to destroy. There is still no copying.
Assuming that 0 is an invalid/empty shader program and glDeleteProgram(0) is essentially a no-op, the move constructor could look like this:
Shader(Shader&& other) {
_programId = other._programId;
other._programId = 0;
}
You don't want to freely copy objects Shader objects, because otherwise you will end up deleting the same _programId more than once. To avoid this, mark the copy constructor and the copy assignment operator as delete.
I can't just throw all the Create code in the c'tor because there's a few operations that might fail.
That's what exceptions are for.
|
69,908,968 | 69,909,207 | How to count words in huge file by spliting data? | I try to count word in huge file. I want to use max of CPU resources and i try to split input data and count words in threads. But i have a problem, when i split data it can split the words and in the end i have wrong answer. How can i split data from file to avoid spliting words? Can somebody help me?
#include <iostream>
#include <fstream>
#include <set>
#include <string>
#include <thread>
#include <mutex>
#include <sstream>
#include <vector>
#include <algorithm>
#define BUFER_SIZE 1024
using namespace std;
std::mutex mtx;
void worker(int n, set<std::string> &mySet, std::string path)
{
mtx.lock();
ifstream file (path, ios::in);
if (file.is_open())
{
char *memblock = new char [BUFER_SIZE];
file.seekg (n * (BUFER_SIZE - 1), ios::beg);
file.read(memblock, BUFER_SIZE - 1);
std::string blockString(memblock);
std::string buf;
stringstream stream(blockString);
while(stream >> buf) mySet.insert(buf);
memblock[BUFER_SIZE] = '\0';
file.close();
delete[] memblock;
}
else
cout << "Unable to open file";
mtx.unlock();
}
int main(int argc, char *argv[])
{
set<std::string> uniqWords;
int threadCount = 0;
ifstream file(argv[1], ios::in);
if(!file){
std::cout << "Bad path.\n";
return 1;
}
file.seekg(0, ios::end);
int fileSize = file.tellg();
file.close();
std::cout << "Size of the file is" << " " << fileSize << " " << "bytes\n";
threadCount = fileSize/BUFER_SIZE + 1;
std::cout << "Thread count: " << threadCount << std::endl;
std::vector<std::thread> vec;
for(int i=0; i < threadCount; i++)
{
vec.push_back(std::thread(worker, i, std::ref(uniqWords), argv[1]));
}
std::for_each(vec.begin(), vec.end(), [](std::thread& th)
{
th.join();
});
std::cout << "Count: " << uniqWords.size() << std::endl;
return 0;
}
| The problem right now is that you're reading in a fixed-size chunk, and processing it. If that stops mid-word, you're doing to count the word twice, once in each buffer it was placed into.
One obvious solution is to only break between buffers at word boundaries--e.g., when you read in one chunk, look backwards from the end to find a word boundary, then have the thread only process up to that boundary.
Another solution that's a bit less obvious (but may have the potential for better performance) is to look at the last character in a chunk to see if it's a word character (e.g., a letter) or a boundary character (e.g., a space). Then when you create and process the next chunk, you tell it whether the previous buffer ended with a boundary or within a word. If it ended within a word, the counting thread knows to ignore the first partial word in the buffer.
|
69,909,294 | 69,910,477 | How do I get the IPv4 address of my server application? | Even after sifting through many related posts I can't seem to find a suitable answer. I have a winsock2 application (code for server setup is adapted for my needs from the microsoft documentation) and I simply want to display the server IPv4 address after binding.
This is the code I have so far (placed after binding to the ListenSocket):
char ipv4[80];
sockaddr_in inaddr;
int len = sizeof(inaddr);
int error = getsockname(m_ListenSocket, (sockaddr*)&inaddr, &len);
const char* p = inet_ntop(AF_INET, &inaddr.sin_addr, ipv4, 80);
std::cout << "Server address: " << ipv4 << std::endl;
However this will return "0.0.0.0". If I use inet_ntop with struct addrinfo* result (see linked documentation above) I get an IP starting with "2.xxx.xxx.xxx", while I know my local address is "192.168.1.18". In the code above, error is 0 and the result of inet_ntop is not NULL.
How does one get the actual IP address to show up?
| Example code from Microsoft
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
// Link with Iphlpapi.lib
#pragma comment(lib,"IPHLPAPI.lib")
#pragma comment(lib,"Ws2_32.lib")
const unsigned int WORKING_BUFFER_SIZE = 15 * 1024;
void displayAddress(const SOCKET_ADDRESS &Address)
{
// cout << "\n Length of sockaddr: " << Address.iSockaddrLength;
if (Address.lpSockaddr->sa_family == AF_INET)
{
sockaddr_in *si = (sockaddr_in *)(Address.lpSockaddr);
char a[INET_ADDRSTRLEN] = {};
if (inet_ntop(AF_INET, &(si->sin_addr), a, sizeof(a)))
cout << "\n IPv4 address: " << a;
}
else if (Address.lpSockaddr->sa_family == AF_INET6)
{
sockaddr_in6 *si = (sockaddr_in6 *)(Address.lpSockaddr);
char a[INET6_ADDRSTRLEN] = {};
if (inet_ntop(AF_INET6, &(si->sin6_addr), a, sizeof(a)))
cout << "\n IPv6 address: " << a;
}
}
int main(){
DWORD dwSize = 0;
DWORD dwRetVal = 0;
ULONG outBufLen = WORKING_BUFFER_SIZE;
ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL;
pAddresses = (IP_ADAPTER_ADDRESSES *) malloc(WORKING_BUFFER_SIZE);
dwRetVal = GetAdaptersAddresses(AF_INET, flags, NULL, pAddresses, &outBufLen);
if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
free(pAddresses);
cout << "Buffer error!" << endl;
return -1;
}
pCurrAddresses = pAddresses;
while (pCurrAddresses) {
for (PIP_ADAPTER_UNICAST_ADDRESS pu = pCurrAddresses->FirstUnicastAddress; pu != NULL; pu = pu->Next)
displayAddress(pu->Address);
pCurrAddresses = pCurrAddresses->Next;
}
free(pAddresses);
cout << endl;
return 0;
}
|
69,909,424 | 69,909,694 | C++ Template: Kind of like infinite recursion but not really | I have the following code:
#include <cstdint>
template <uint32_t test_value, uint32_t ...Vn>
struct is_prime_tmpl;
template <uint32_t test_value>
struct is_prime_tmpl<test_value> {
static constexpr bool value = true;
};
template <uint32_t test_value, uint32_t V1, uint32_t ...Vn>
struct is_prime_tmpl<test_value, V1, Vn...> {
static constexpr bool value = (test_value % V1 != 0) && is_prime_tmpl<test_value, Vn...>::value;
};
template <uint32_t ...Vn>
struct prime {};
template <uint32_t max_target, uint32_t test_value, class PrimeList>
struct generate_prime_helper_tmpl;
template <uint32_t max_target, uint32_t test_value, uint32_t ...Vn>
struct generate_prime_helper_tmpl<max_target, test_value, prime<Vn...>> {
static constexpr auto result = test_value <= max_target ?
(is_prime_tmpl<test_value, Vn...>::value ?
generate_prime_helper_tmpl<max_target, test_value + 1, prime<Vn..., test_value>>::result : generate_prime_helper_tmpl<max_target, test_value + 1, prime<Vn...>>::result) :
prime<Vn...>();
};
int main() {
static_assert(is_prime_tmpl<2>::value);
static_assert(std::is_same_v<generate_prime_helper_tmpl<2, 2, prime<>>::result, prime<2>);
}
The code is trying to generate a sequence of prime numbers. But it fails to compile on my local machine with g++10. The compiler doesn't emit any warning nor error. It just compiles forever.
It seems like the recursion is broken somehow. But I fail to see it. I am more interested in what goes wrong than the actual solution.
Any idea what has gone wrong?
| Your ternary operator does not stop recursion, which makes your code fall into infinite recursion. You should use if constexpr to prevent recursion when the argument does not meet the condition.
Something like this:
template <uint32_t max_target, uint32_t test_value, uint32_t ...Vn>
struct generate_prime_helper_tmpl<max_target, test_value, prime<Vn...>> {
static constexpr auto result = [] {
if constexpr (test_value <= max_target) {
if constexpr (is_prime_tmpl<test_value, Vn...>::value)
return generate_prime_helper_tmpl<max_target, test_value + 1, prime<Vn..., test_value>>::result;
else
return generate_prime_helper_tmpl<max_target, test_value + 1, prime<Vn...>>::result;
}
else
return prime<Vn...>();
}();
};
Demo.
|
69,909,847 | 69,911,589 | Logic for the string to not fall in the middle of another string | I need help in figuring out the logic or code to when I want my string not to fall in the middle of another string. For example my given word is "Birthday!" and the other string to look for it is "Happy Birthday Scott". It's going to return a false value because it's missing an exclamation point. Here is the code that I've worked
int Words::matchWords(const char* string, const char* sentence, int wordNum){
int wordCount = words(sentence); // the words function counts the number of words in the sentence
int strLength = strlen(str);
int sentLength = strlen(sentence);
int i = 0;
char strTemp[100];
char sentenceTemp[100];
strcpy(strTemp, str);
strcpy(sentenceTemp, sentence);
if (wordNum > wordCount) {
return false;
}
char* temp;
for (i = 0; i < strLength; i++) {
strTemp[i] = tolower(str[i]);
}
for (i = 0; i < sentLength; i++) {
sentenceTemp[i] = tolower(str[i]);
}
temp = strstr(sentenceTemp, strTemp);
if (temp != NULL) {
return true;
if (strTemp[i] != sentenceTemp[i]) {
return false;
}
else
return true;
}
else
return false;
}
| Here is a super simple program for you to look at.
All you have to do for this problem is create your strings using std::string, determine if they are inside the big string using find(), and lastly check if it was found using string::npos.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string bday = "Birthday!";
string str1 = "Happy Birthday Scott";
int found1 = str1.find(bday);
string str2 = "Scott, Happy Birthday!";
int found2 = str2.find(bday);
if (found1 == string::npos) //if Birthday! is NOT found!
{
cout << "str1: " << "FALSE!" << endl;
}
if (found2 != string::npos) //if Birthday! IS found!
{
cout << "str2: " << "TRUE!" << endl;
}
}
Note that for string::npos, you use == for something NOT being found and != for something that IS found.
|
69,909,851 | 69,910,199 | How to use it->empty() in an iterator | I want to use an iterator as a condition of a for loop, but when I define it, it->empty() always reports an error. I don’t know where the error is. When I change it to (*it).empty() It will also report an error later
The error is: the expression must contain a pointer type to the class, but it has type "char *"
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
string s("some string");
for (auto it = s.begin(); it != s.end() && !it->empty(); it++)
{
cout<< *it <<endl;
}
}
| The problem is that you are trying to access a member function called empty through a non-class type object(a char type object in this case). You can change your code to look like below:
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
std::vector<std::string> vec = {"some", "string", "is", "this"};
for (auto it = vec.begin(); it != vec.end() && !it->empty(); it++)
{
cout<< *it <<endl;
}
}
The above code works because this time we are using/calling the member function empty through a class type object(a std::string object in this modified example).
Also if you only wanted to know why you're having this error then i think the comments and my answer, answer that. If you have any other/further question then you can edit your question to add that.
|
69,910,819 | 69,911,669 | Binary addition using char array | #include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
int main(){
char Pbuf8[9]={"01100000"};
char Mbuf4[10]={"01110000"};
int num=0;
char Snum[9]="0";
int carry=0;
for(int c=7;c>=0;c--){
//Convert a string to a number and add
num=(Pbuf8[c]-'0')+(Mbuf4[c]-'0')+carry;
//binary addition
if(num==1){
Snum[c]=num;
carry=0;
}else if(num==2){
num=0;
carry=1;
Snum[c]=num;
}else if(num==3){
num=1;
carry=1;
Snum[c]=num;
}
//Convert num to string and store in Snum
sprintf(Snum, "%d", num);
}
//output
printf("%s",Snum);
return 0;
}
Calculate and output the sum of Pbuf8 and Mbuf4.
I want to output '00001011' but '1' is output.
If there is no 'sprintf(number, "%d", number);' does not exist, 'rr' is output.
How do I get the value I want?
| You have 3 minor bugs in your code.
Snum must be initialized with everything being 0. Otherwise it will just be filled with one 0 and the lower part of the addition will not be visible
You need to convert "num" back to a number, before adding it back to the char array. So, num+'0'
Delete the "sprintf", It will overwrite the previously created result.
The corrected code will look like:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
int main(){
char Pbuf8[9]={"01100000"};
char Mbuf4[10]={"01110000"};
int num=0;
char Snum[9]="00000000";
int carry=0;
for(int c=7;c>=0;c--){
//Convert a string to a number and add
num=(Pbuf8[c]-'0')+(Mbuf4[c]-'0')+carry;
//binary addition
if(num==1){
Snum[c]=num+'0';
carry=0;
}else if(num==2){
num=0;
carry=1;
Snum[c]=num+'0';
}else if(num==3){
num=1;
carry=1;
Snum[c]=num+'0';
}
//Convert num to string and store in Snum
//sprintf(Snum, "%d", num);
}
//output
printf("%s",Snum);
return 0;
}
|
69,911,010 | 69,912,440 | ReadFile only returns after newline | I'm trying to read every character pressed in my console in realtime.
I'm using ReadFile to read from stdin, but it seems to only complete the read operation after a newline (when I press enter).
Here is my code:
char buf[1] = { 0 };
HANDLE stdInHandle = GetStdHandle(STD_INPUT_HANDLE), stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
while (true) {
ReadFile(stdInHandle, buf, sizeof(buf), NULL, NULL);
WriteFile(stdOutHandle, buf, sizeof(buf), NULL, NULL);
}
How would I read the characters pressed realtime, instead of after a newline?
| As I've mentioned in a comment you could use SetConsoleMode to disable line-buffering:
#include <windows.h>
int main()
{
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
// Get the current console mode
DWORD mode;
GetConsoleMode(hInput, &mode);
// Save the current mode, so we can restore it later
DWORD original_mode = mode;
// Disable the line input mode
mode &= ~ENABLE_LINE_INPUT;
// And set the new mode
SetConsoleMode(hInput, mode);
// Then read and write input...
for (;;)
{
TCHAR buffer[1];
DWORD nread = 0;
// TODO: Need to add some error checking here!
ReadConsole(hInput, buffer, 1, &nread, nullptr);
WriteConsole(hOutput, buffer, nread, nullptr, nullptr);
// Allow some way to exit the program
if (buffer[0] == 'q' || buffer[0] == 'Q')
{
break;
}
}
// Restore the original console mode
SetConsoleMode(hInput, original_mode);
}
|
69,911,242 | 69,911,490 | SdFat write floats to file ESP32 | I Need to write float or Strings value into the SDVolume Cache in SDFAT library, I'm using ESP32 with SdCard module.
uint8_t* pCache = (uint8_t*)sd.vol()->cacheClear();
memset(pCache, ' ', 512);
for (uint16_t i = 0; i < 512; i += 4) {
pCache[i + 0] = 'r'; // I Need to write a Float value or String into this cell
pCache[i + 1] = ',';
pCache[i + 2] = '0';
pCache[i + 3] = '\n';
}
Libray link: https://github.com/greiman/SdFat
| First:
// I Need to write a Float value or String into this cell
makes no sense - that "cell" is a single character, like 'e'. How do you write a full float value into a single character?
You probably just want to fill pCache with a string representation of your float. So do that!
We've got all C++ at our disposal, so let's use a somewhat memory efficient method:
std::to_chars is the C++ way to convert numeric values to strings. Something like
#include <charconv>
…
std::to_chars(pCache, pCache+512-1, floatvalue);
would be appropriate.
Couple of things:
You need to zero-terminate strings if your needs to be able to know where they end. So, instead of memset(pCache, ' ', 512), memset(pCache, 0, 512); would be more sensible.
Are you sure your even using the right functions? vol()->cacheClear() is pretty unambigously marked as "do not use in your application" here! It also seems to be very unusual to me that you would write your string to some block device cache instead of getting a buffer for a file from the file system, or passing a buffer to the file system to write to a file.
|
69,911,364 | 69,925,141 | What's the difference in results of cv::boundingRect() and cv::minAreaRect()? | I tried reading the docs but couldn't understand the difference.
I was expecting the same results when the target is a 3x3 square,
but I get 3x3 with cv::boundingRect() and 2x2 with cv::minAreaRect().
I'm using OpenCV 4.4.
Here is a sample code.
char data[25] = {
0, 0, 0, 0, 0,
0, 255, 255, 255, 0,
0, 255, 255, 255, 0,
0, 255, 255, 255, 0,
0, 0, 0, 0, 0
};
cv::Mat image = cv::Mat(5, 5, CV_8U, data);
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(image, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
cv::Rect boundingRect = cv::boundingRect(contours[0]);
std::cout << "[cv::boundingRect]" << std::endl;
std::cout << "w, h: " << boundingRect.size().width << " x " << boundingRect.size().height << std::endl;
cv::RotatedRect minAreaRect = cv::minAreaRect(contours[0]);
std::cout << "[cv::minAreaRect]" << std::endl;
std::cout << "w, h: " << minAreaRect.size.width << " x " << minAreaRect.size.height << std::endl;
And the output is:
[cv::boundingRect]
w, h: 3 x 3
[cv::minAreaRect]
w, h: 2 x 2
Thanks in advance.
| OpenCV has inconsistencies and sloppy/no "definitions", especially in those old parts.
Some of that stems from the reluctance to return fractional values to express that a line (contour) should be between pixels. Some more stems from not being clear on whether the "bottom right" of a rectangle is the last pixel in it, or the first pixel outside of it... or if we're considering the points that are on the extreme corners of those pixels.
In OpenCV, the center of a pixel is an integer coordinate. That much is sure.
In your example, which is clearly a box with sides of length 3, you would expect results to reflect that size.
findContours gives you strictly points that are in the shape... it gives the centers of those border pixels. Those would be (1,1), (1,3), (3,3), (3,1). And that's the first problem.
If you assume they're pixels (little squares), you could figure out that the true size is 3 by 3.
If they're considered points, the size would have to be 2 by 2.
boundingRect seems to assume the values to be pixels. It tells you the correct size. The top left corner is on the top left pixel, instead of its top left corner... and the bottom right corner of the rectangle isn't on the bottom right corner of the last inside pixel, but on the center of the pixel just outside of it.
minAreaRect seems to assume the values to be points. That explains its result of size 2 by 2.
Depending on what you need the results for, you'll have to correct. Sometimes that means adding/subtracting one from the size. Sometimes that means shifting the result by one half to get points on the corners of pixels.
Additionally, OpenCV's drawing functions are equally sloppily defined. Try drawing a Line of specific thickness, say 1 or 2, with LINE_AA style... it's a mess. A rectangle will probably be drawn such that the line sits on the top left inside pixel, and on the bottom right pixel just outside.
|
69,911,367 | 69,912,180 | What is the use of a test fixture in google test? | Google recommends to use the text fixture constructor/destructor when possible instead of SetUp()/TearDown() (https://google.github.io/googletest/faq.html#CtorVsSetUp). Assuming I do it this way, what is the use of even using a test fixture? How are the following different, and what is the advantage of the first?
TEST_F(MyFixture, MyTest) {
... run test, using member functions of MyFixture for common code ...
}
TEST(MySuite, MyTest) {
MyFixture fixture; // will call ctor
... run test, using public functions of MyFixture for common code ...
} // will call dtor
| The advantages are visible when there are more than one TEST/TEST_F.
Compare:
TEST(MyTest, shallX)
{
MyTest test;
test.setUpX();
test.objectUnderTest.doX();
}
TEST(MyTest, shallY)
{
OtherTest test;
test.setUpY();
test.objectUnderTest.doY();
}
with
TEST_F(MyTest, shallX)
{
setUpX();
objectUnderTest.doX();
}
TEST_F(MyTest, shallY)
{
setUpY();
objectUnderTest.doY();
}
What we can see, are:
DRY (don't repeat yourselves) principle is followed. You do not have to repeat creating of some test-helper object. In TEST_F - the macro creates this instance.
The code is safer with TEST_F. See MyTest..shallDoY -- have you spot that wrong test-helper object is used, not the one that testname is promising.
So it is better to use TEST_F if your tests require some test-helper class.
If not - then use TEST.
|
69,911,406 | 69,911,528 | Type-pun uint64_t as two uint32_t in C++20 | This code to read a uint64_t as two uint32_t is UB due to the strict aliasing rule:
uint64_t v;
uint32_t lower = reinterpret_cast<uint32_t*>(&v)[0];
uint32_t upper = reinterpret_cast<uint32_t*>(&v)[1];
Likewise, this code to write the upper and lower part of an uint64_t is UB due to the same reason:
uint64_t v;
uint32_t* lower = reinterpret_cast<uint32_t*>(&v);
uint32_t* upper = reinterpret_cast<uint32_t*>(&v) + 1;
*lower = 1;
*upper = 1;
How can one write this code in a safe and clean way in modern C++20, potentially using std::bit_cast?
| Using std::bit_cast:
Try it online!
#include <bit>
#include <array>
#include <cstdint>
#include <iostream>
int main() {
uint64_t x = 0x12345678'87654321ULL;
// Convert one u64 -> two u32
auto v = std::bit_cast<std::array<uint32_t, 2>>(x);
std::cout << std::hex << v[0] << " " << v[1] << std::endl;
// Convert two u32 -> one u64
auto y = std::bit_cast<uint64_t>(v);
std::cout << std::hex << y << std::endl;
}
Output:
87654321 12345678
1234567887654321
std::bit_cast is available only in C++20. Prior to C++20 you can manually implement std::bit_cast through std::memcpy, with one exception that such implementation is not constexpr like C++20 variant:
template <class To, class From>
inline To bit_cast(From const & src) noexcept {
//return std::bit_cast<To>(src);
static_assert(std::is_trivially_constructible_v<To>,
"Destination type should be trivially constructible");
To dst;
std::memcpy(&dst, &src, sizeof(To));
return dst;
}
For this specific case of integers quite optimal would be just to do bit shift/or arithmetics to convert one u64 to two u32 and back again. std::bit_cast is more generic, supporting any trivially constructible type, although std::bit_cast solution should be same optimal as bit arithmetics on modern compilers with high level of optimization.
One extra profit of bit arithmetics is that it handles correctly endianess, it is endianess independent, unlike std::bit_cast.
Try it online!
#include <cstdint>
#include <iostream>
int main() {
uint64_t x = 0x12345678'87654321ULL;
// Convert one u64 -> two u32
uint32_t lo = uint32_t(x), hi = uint32_t(x >> 32);
std::cout << std::hex << lo << " " << hi << std::endl;
// Convert two u32 -> one u64
uint64_t y = (uint64_t(hi) << 32) | lo;
std::cout << std::hex << y << std::endl;
}
Output:
87654321 12345678
123456788765432
Notice! As @Jarod42 points out, solution with bit shifting is not equivalent to memcpy/bit_cast solution, their equivalence depends on endianess. On little endian CPU memcpy/bit_cast gives least significant half (lo) as array element v[0] and most significant (hi) in v[1], while on big endian least significant (lo) goes to v[1] and most significant goes to v[0]. While bit-shifting solution is endianess independent, and on all systems gives most significant half (hi) as uint32_t(num_64 >> 32) and least significant half (lo) as uint32_t(num_64).
|
69,911,628 | 69,917,424 | Getting REG_DWORD from windows registry as a wstring | I am working on a test which should check the registry value. My goal is to take 3 windows registry variables. I am using the modified solution from this LINK. The issue is that when I try to get the value which is REG_DWORD it just prints empty brackets. When I try to use it on REG_SZ it works perfectly fine. For now I use this code:
wstring UpgradeAutocompleteBeCopyFilesUt::ReadRegValue(HKEY root, wstring key, wstring name)
{
HKEY hKey;
if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
throw "Could not open registry key";
DWORD type;
DWORD cbData;
if (RegQueryValueEx(hKey, name.c_str(), NULL, &type, NULL, &cbData) != ERROR_SUCCESS)
{
RegCloseKey(hKey);
throw "Could not read registry value";
}
if (type != REG_SZ && type != REG_DWORD)
{
RegCloseKey(hKey);
throw "Incorrect registry value type";
}
wstring value(cbData / sizeof(wchar_t), L'\0');
if (RegQueryValueEx(hKey, name.c_str(), NULL, NULL, reinterpret_cast<LPBYTE>(&value[0]), &cbData) != ERROR_SUCCESS)
{
RegCloseKey(hKey);
throw "Could not read registry value";
}
RegCloseKey(hKey);
size_t firstNull = value.find_first_of(L'\0');
if (firstNull != string::npos)
value.resize(firstNull);
return value;
}
and this is how I print the variables:
std::wcout << L"first: " << regfirst << std::endl;
std::wcout << L"second: " << regsecond << std::endl;
std::wcout << L"third: " << regthird << std::endl;
Third one is REG_DWORD. First two are REG_SZ.
Is there any possible way to get the wstring out of the third variable?
I checked registry there should be a value of "1".
| if (type != REG_SZ && type != REG_DWORD) ...
You just have to treat REG_SZ and REG_DWORD differently.
Also add an extra +1 for the null terminator to be safe.
wstring ReadRegValue(HKEY root, wstring key, wstring name)
{
HKEY hKey;
if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
throw "Could not open registry key";
DWORD type;
DWORD cbData;
if (RegQueryValueEx(hKey,
name.c_str(), NULL, &type, NULL, &cbData) != ERROR_SUCCESS)
{
RegCloseKey(hKey);
throw "Could not read registry value";
}
std::wstring value;
if (type == REG_SZ)
{
value.resize(1 + (cbData / sizeof(wchar_t)), L'\0');
if (0 == RegQueryValueEx(hKey, name.c_str(), NULL, NULL,
reinterpret_cast<BYTE*>(value.data()), &cbData))
{ //okay
}
}
else if (type == REG_DWORD)
{
DWORD dword;
if (0 == RegQueryValueEx(hKey, name.c_str(), NULL, &type,
reinterpret_cast<BYTE*>(&dword), &cbData))
value = std::to_wstring(dword);
}
RegCloseKey(hKey);
return value;
}
|
69,911,849 | 69,912,024 | c++ map threadsafe behavior through iterator | My need is just like below:
One thread (named thread 1)just keeps inserting pairs into the common map.
And the other thread (named thread 2)keeps getting the element at the begin position(no matter if it is still the begin while other thread insert an element at the begin position) and do some operation to the element and erase the iterator.
I know that STL is not threadsafe, but it is still a good container to use. So my method is every time thread 2 get the element, I make a copy of it and do my work, and protect insert/delete/begin/end by one mutex.
pseudocode like below under c++17
my_map {
insert(){
lock_guard(mutex)
map.insert()
}
erase(){
lock_guard(mutex)
map.erase()
}
end(){
lock_guard(mutex)
map.end()
}
begin(){
lock_guard(mutex)
map.begin()
}}
thread 1:
while(1){
sleep(1)
my_map.insert()
}
thread 2:
while(1){
auto it = my_map.begin()
auto k = it->first;
auto v = it->second;
work(k, v);
my_map.erase(it);
}
My question is would my code be threadsafe? And will insert in thread 1 affects the actual value of k and v in thread 2?(again no matter if it is at the real begin position, I just want to get k and v of the iterator when thread 2 gets using "auto it = my_map.begin()")
| It's not thread safe if the underlying map is std::unordered_map. With unordered_map insert may invalidate iterators (if rehasing occurs).
With std::map iterators aren't invalidated on insert so I think the code would be ok.
|
69,912,336 | 69,912,356 | Creating a vector with n elements in a struct | If I just write this code:
std::vector<int> vec(24, 3);
It'll create a vector called vec with 24 elements all equal to 3.
But if I have a struct:
struct Day
{
std::vector<int> days(24, 3);
};
And try to do the exact same thing it doesn't work, why is this?
| Syntax would be:
struct Day
{
vector<int> days = vector<int>(24, 3);
};
You cannot call constructor with () syntax there (to avoid vexing parse) (but can with {}or = /*...*/).
|
69,912,392 | 69,912,451 | C++ move constructor for a class with string member | I've wrote a class with following code:
class Test {
public:
...
Test( const Test &&that ) : i(that.i), s(std::move(that.s)) {
cout << "move contructor." << endl;
}
...
private:
int i;
std::string s;
};
if I disassemble the generated code I see:
.type Test::Test(Test const&&), @function
Test::Test(Test const&&):
...
call std::remove_reference<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&>::type&& std::move<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&>(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
movq %rax, %rsi
movq %rbx, %rdi
.LEHB3:
call std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)@PLT
it surprises me the call to basic_string<...>::basic_string( basic_string<...> const&) because I expected a call to the move constructor of the basic_string basic_string<...>::basic_string( basic_string<...> &&).
I'm implementing in a incorrect way the move constructor ?
| Rvalue references to const types aren't very useful. They say that code can steal from the object, but must do so without changing its value?
Since std::string doesn't have a string(const string&&) move constructor, overload resolution can only use the string(const string&) copy constructor.
A normal move constructor doesn't use the const:
Test( Test &&that ) : i(that.i), s(std::move(that.s)) {
std::cout << "move constructor." << std::endl;
}
|
69,912,402 | 69,912,466 | Using a variable to define other variable before taking it as input | In the below code I defined both n and k initially and then if I define n as k/2 after I take k as input using cin, the code is successful but instead of this if I define n=k/2 before cin function I get an infinite loop as output? Please tell why is defining below or after cin function is affecting the output.
#include <iostream>
using namespace std;
int main () {
cout<< "how many asterisks you want in the middle column:";
int n,k;
// n=k/2 ;
cin>>k;
// n=k/2;
//some code involving n
return 0;
}
| The order of statements makes a difference:
int k = 2;
int n = k/2;
k = 4;
is different than
int k = 2;
k = 4;
int n = k/2;
In the first case, you get n = 1, and in the second n = 2. This really shouldn't surprise you! You might need to revise your programming basics before dealing with loops if it does :)
Other things:
never use using namespace std;. Not doing that, but specifically only importing the things you need will save you a lot of time later on, debugging very strange problems (I don't know why this is still taught): using std::cin;, using std::cout; is maybe longer, but much better, because you know what you get in your name space!
Properly indent your code. Yes, your editor has a function for that, and if it hasn't, get a better editor (these things really make a difference, especially for a beginner, because they help you spot little typos much easier!). Many beginners like Code::blocks as editor, because it's easy to set up and good, others like the more mightier VS Code.
|
69,912,672 | 69,912,757 | Implicit conversion from char to int for constructors in C++ | class A {
int x;
std::string s;
public:
A(std::string _s): x(0), s(_s) {
std::cout << "\tA(string)\n" ;
}
A(int _x): x(_x), s("") {
std::cout << "\tA(int)\n" ;
}
A(const A &other): x(other.x), s(other.s) {
std::cout << "\tA(A& other)\n" ;
}
};
int main() {
std::string str = "Hello";
A obj_1(str);
A obj_2 = str;
A obj_3(10);
A obj_4 = 10;
char ch = 'a';
A obj_5 = ch; // How is this working?
// A obj_6 = "Hello"; // And not this?
const char *ptr = "Hello";
// A obj_7 = ptr; // or this?
return 0;
}
On executing this code, the output is:
A(string)
A(string)
A(int)
A(int)
A(int)
As far as I understand, obj_1 and obj_3 are created directly by using the respective ctors. For obj_2 and obj_4, the compiler does an implicit conversion by calling their respective ctor (so only 1 implicit conversion is required in each case). However, for obj_5 the compiler first has to convert from char to int and then one more implicit conversion to call the int-ctor. But C++ standard allows only 1 implicit conversion. So what is happening here?
Also, in that case "Hello" should first get converted to a std::string then one more implicit conversion to call the string-ctor. But this doesn't work.
|
But C++ standard allows only 1 implicit conversion.
Thats not correct.
From cppreference:
Implicit conversion sequence consists of the following, in this order:
zero or one standard conversion sequence;
zero or one user-defined conversion;
zero or one standard conversion sequence.
From the language point of view, const char[N] -> std::string (or const char* to std::string) is a user-defined conversion. Hence, the commented out lines are errors. On the other hand,
A obj_5 = ch; // How is this working?
is fine, because there is only a single user-defined conversion involved.
|
69,913,008 | 69,913,185 | How to center numbers and add list | i made a program for converting Celcius to Fahrenheit and have some troubles with modifying it. I need to all numeration for each line and center numbers in lines. rn my program outputs all to left. Can you please help me with this?
#include <stdio.h>
#include <iostream>
int main(){
// Table header
setlocale(LC_ALL, "");
system("color F0");
printf("\tTable Output\t");
printf("\n----------------------------------\n");
printf("| Celcius \t | Fahrenheit \t |\n");
printf("----------------------------------\n");
// Table body
for (double i = 15; i <= 30; i++)
{
printf("| %.f\t\t | %.1f\t\t |\n", i, 1.8 * i + 32);
}
printf("----------------------------------\n");
printf("\n\tList output\n");
using namespace std;
int main();
{
for (double i = 15; i <= 30; ++i)
{
cout << "Celcius: " << i << " --> Fahrenheit: " << 1.8 * i + 32 << endl;
}
}
return 0;
}
| As I already stated in the comments, 'padded output' may be able to help you.
There's some finetuning to be done here, maybe use sprintf to get the number of characters and prepend/append spaces accordingly, but here you go with a C-Style answer.
setlocale(LC_ALL, "");
system("color F0");
printf("\tTable Output\t");
printf("\n----------------------------------\n");
printf("| Celcius | Fahrenheit |\n");
printf("----------------------------------\n");
// Table body
for (int i = 15; i <= 30; i++)
{
printf("| % 6d | % 6.1f |\n", i, 1.8 * i + 32);
}
|
69,913,259 | 69,913,321 | How to make multiple vectors in c++ | Brief :-
How to make multiple vectors ?
We generally make vectors using - vector<int> vector_name;
But any method to make multiple vectors at once ?
| I assume that you're trying to create multiple vector at once and store them. You can use a simple for loop, or use a vector of vectors!
For example:
#include <vector>
// Using a for loop
//#define VECTOR_COUNT 5 (EDIT)
constexpr int VECTOR_COUNT = 5;
std::vector<int> myFiveVectors[VECTOR_COUNT];
for(int i = 0; i < VECTOR_COUNT; i++)
myFiveVectors[i] = {1, 2, 3};
// Using vector of vectors
std::vector<std::vector<int>> myVectors{};
myVectors.push_back({1, 2, 3});
|
69,913,286 | 69,913,455 | Is f(U(*)()) just a specialized version of f(U*)? | When reading a wiki page, I found this sample code
template <class T>
struct is_pointer
{
template <class U>
static char is_ptr(U *); #1
template <class X, class Y>
static char is_ptr(Y X::*);
template <class U>
static char is_ptr(U (*)()); #2
static double is_ptr(...);
static T t;
enum { value = sizeof(is_ptr(t)) == sizeof(char) };
};
To me, #2 is just a specialized version of #1, so it seems superfluous.
Did I make something wrong? What would it be like in the eyes of C++ compilers?
|
To me, #2 is just a specialization of #1, so it seems superfluous.
An overload, not a specialization. And yes, it is superfluous. In a template accepting U* for a parameter, U can resolve to an entire function type. It's what makes is_pointer<int(*)(char)>::value be true, despite the fact int(*)(char) will not match the overload #2.
Did I make something wrong?
Since you did not make this code yourself, I don't believe you did. You correctly surmised there's a redundancy.
What would it be like in the eyes of C++ compilers?
It would be an overload that gets picked for the specific case of checking a function pointer type that accepts no arguments. It conveys no interesting information compared to the U* overload, and can be removed.
It's possible this implementation was added to get around a compiler bug (where said function pointer types were not correctly handled). Modern compilers handle said function pointers correctly even if the superfluous overload is removed.
|
69,913,307 | 69,913,733 | Is it acceptable for all ".h" files import "macros.h" to set verbosity with preprocessing directives | As described in the title, the question is if it considered a good practice to set a code's verbosity by making all ".h" files import one single ".h" file where preprocessing directives are defined? e.g.
macros.h contains
#ifndef VERBOSE
#define VERBOSE true
#endif
then functions1.h could be
#include "../macros/macros.h"
void eatBurguers(int i){
if (VERBOSE) {
printf("Today I ate %d burguers, yum!", i);
}
}
And functions2.h could be
#include "../macros/macros.h"
#include <vector>
void preallocateVector(std::vector<int> &v){
if (VERBOSE) {
printf("About to resize a vector");
}
v.resize(100);
if (VERBOSE) {
printf("A vector has just been resized");
}
}
Besides saving us the time that it would take to just add the macro at each ".h" file, it occurs to me that it could be less untidy.
EDIT: indeed answers and comments addressed how the answer depends on the specifics of each project, which I understand somehow means that there is nothing inherently wrong in the practice previously described.
More info: the present use-case is a Scientific Computing application which moved the definition of verbosity a step prior to compilation in order to allow some 'smart compiler' to erase the ifs, so producing a final app that allows verbose output is not necessary and explicitly checking for the definition in each print was considered to decrease readability.
EDIT2: after Chris' answer, indeed there was a 'better' method.
| Littering code with ifs or #if defined is madness and makes a codebase difficult to read and work with.
If you are going to have a common header to define macros, then make the expansion of the macros be what you actually want (instead of making them only be a condition that must be checked.) I'm not a big fan of macros in code to do this in general but if you're going to do it, at least put all the conditional code in a single place.
That is, if you have macros.h, do something like this:
#if defined(VERBOSE)
#define PRINTF_DBG printf
#else
#define PRINTF_DBG(...)
#endif
Then in your files that use it, just call PRINTF_DBG without any testing at all and it'll either expand to printf(<args>) or will simply go away.
void preallocateVector(std::vector<int> &v){
PRINTF_DBG("About to resize a vector");
v.resize(100);
PRINTF_DBG("A vector has just been resized");
}
The code is much cleaner and less noisy.
Compare the results of the preprocessor with and without VERBOSE defined:
https://godbolt.org/z/hG33MYvr3
|
69,913,536 | 70,719,124 | Executing multiple self-avoiding walks, recursively | I have a 3D simple cubic lattice, which I call Grid in my code, with periodic boundary conditions of size 20x20x20 (number are arbitrary). What I want to do is plant multiple polymer chains with a degree of polymerization N (graphs with N nodes) that do no overlap, are self-avoiding.
At the moment, I can plant one polymer recursively. This is my code
const std::vector <int> ex{1,0,0}, nex{-1,0,0}, ey{0,1,0}, ney{0,-1,0}, ez{0,0,1}, nez{0,0,-1}; // unit directions
const std::vector <std::vector <int>> drns = {ex, nex, ey, ney, ez, nez}; // vector of unit directions
void Grid::plant_polymer(int DoP, std::vector <std::vector <int>>* loc_list){
// loc_list is the list of places the polymer has been
// for this function, I provide a starting point
if (DoP == 0){
Polymer p (loc_list);
this->polymer_chains.push_back(p); // polymer_chains is the attribute which holds all polymer chains in the grid
return; // once the degree of polymerization hits zero, you are done
};
// until then
// increment final vector in loc_list in a unit direction
std::vector <int> next(3,0);
for (auto v: drns){
next = add_vectors(&((*loc_list).at((*loc_list).size()-1)), &v);
impose_pbc(&next, this->x_len, this->y_len, this->z_len);
if (this->occupied[next]==0){ // occupied is a map which takes in a location, and spits out if it is occupied (1) or not (0)
// occupied is an attribute of the class Grid
dop--; // decrease dop now that a monomer unit has been added
(*loc_list).push_back(next); // add monomer to list
this->occupied[next] == 1;
return plant_polymer(DoP, loc_list);
}
}
std::cout << "no solution found for the self-avoiding random walk...";
return;
This is not a general solution. I am providing a seed for the polymer, and also, I am only planting one polymer. I want to make it such that I can plant multiple polymers, without specifying a seed. Is it possible to recursively hunt for a starting position, every time I want to add a polymer, and then build a polymer while making sure it is not overlapping with other polymers already in the system? Any advice you have would be appreciated.
| Self-avoiding walks has been studied at least since the 1960s and there's a vast literature on them. Fortunately, the problem you face belong to the simplest ones (walks' length is fixed at a relatively small value).
1
The first thing you should be aware of is that your question is too broad to have a unique answer. That is, if you plant many polymers in the system, the result you're going to get depends on the dynamics of the polymer planting and growing. There are two major cases. Either you plant a number of seeds and start growing polymers from them, or you grow each polymer "elsewhere" and then try to plant them in the system at a random location, one by one, keeping the condition of self-avoidance. The two methods will result in statistically different distributions of polymers, and there's nothing you can do about it, except to specify the system dynamics in more detail.
I believe the second approach is a bit easier, as it saves you from deciding what to do if some polymers cannot grow to the desired length (restart the simulation?), so let's focus just on it.
The general algorithm might look like this:
Set maximum_number_of_attempts to reasonably large, but not too large a value, say a million
Set required_number_of_polymers to the required value
Set number_of_attempts to 0
Set number_of_planted_polymers to 0
While number_of_attempts < maximum_number_of_attempts AND number_of_planted_polymers < required_number_of_polymers
increase number_of_attempts by 1
generate the next random polymer
chose a random position (lattice site) in the system
check if the polymer can be planted at this position without intersections
if and only if yes,
accept the polymer (add it to the list of polymers; update the list of occupied lattice nodes)
increase number_of_planted_polymers by 1
To speed thing up, you can be choosing the initial positions only from unoccupied sites (e.g. in a while loop). Another idea is to try and use a polymer, on its first plating failure, several times (but not too many, you'd need to experiment) at different positions.
2
Now the next step: how to generate a self-avoiding random walk. Your code is almost OK, except for a few misconceptions.
In function void Grid::plant_polymer there's one grave error: it always performs the search in the space of possible polymer shapes in exactly the same order. In other words, it is deterministic. For Monte Carlo methods it sounds like a disaster. One thing you might do to handle it is to randomly shuffle the directions.
auto directions = drns;
std::shuffle(begin(directions), end(directions), random_generator); // c++17
for (const auto & v: directions)
{
...
For this to work, you'll need a random number generator already defined and initialized, e.g.
std::random_device rd;
std::mt19937 random_generator(rd());
somewhere much earlier, and only once, in the program.
If you don't use C++17, use std::random_shuffle instead of std::shuffle, but be warned that the former has been depreciated, see https://en.cppreference.com/w/cpp/algorithm/random_shuffle for the discussion why.
As a side remark, when asking a specific software-related question, please try and provide a Minimal, reproducible example. Answering questions based only on reading code is almost always more time-consuming, and the answers tend to be more sketchy and less accurate.
|
69,913,808 | 69,915,947 | Semaphore latency faster than expected - why? | Acquisition of a semaphore is done by blocking. According to the internet and clockres, the interrupt frequency / timer interval on Windows shouldn't be under 0.5ms. The program below measures the time between the release and acquisition of a semaphore in different threads. I would not expect this to be faster than 0.5ms, yet I reliably get results of ~0.017ms. (Curiously with a high standard deviation of +- 100%)
Either my measurement code is wrong, or my understanding of how semaphores work is. Which is it? Code without the boring code to calculate mean and standard deviation:
namespace {
std::binary_semaphore semaphore{ 0 };
std::atomic<std::chrono::high_resolution_clock::time_point> t1;
}
auto acquire_and_set_t1() {
semaphore.acquire(); // this is being measured
t1.store(std::chrono::high_resolution_clock::now());
}
auto measure_semaphore_latency() -> double {
std::jthread j(acquire_and_set_t1);
std::this_thread::sleep_for(5ms); // To make sure thread is running
// Signal thread and start timing
const auto t0 = std::chrono::high_resolution_clock::now();
semaphore.release();
std::this_thread::sleep_for(5ms); // To make sure thread is done writing t1
const double ms = std::chrono::duration_cast<std::chrono::nanoseconds>(t1.load() - t0).count() / 1'000'000.0;
return ms;
}
auto main() -> int {
std::vector<double> runtimes;
for (int i = 0; i < 100; ++i)
runtimes.emplace_back(measure_semaphore_latency());
const auto& [mean, relative_std] = get_mean_and_std(runtimes);
std::cout << std::format("mean: {:.3f} ms, +- {:.2f}%\n", mean, 100.0 * relative_std);
}
edit: sources for windows timer resolution is https://randomascii.wordpress.com/2020/10/04/windows-timer-resolution-the-great-rule-change/ and ClockRes
| Your confusion is coming from the faulty assumption that this comes into play:
According to the internet and clockres, the interrupt frequency / timer interval on Windows shouldn't be under 0.5ms.
Preemptive / timer-based scheduling does not have to be the only opportunity for an OS to assign threads to CPU cores. Explicit/Manual signalling can bypass it.
You can think of it as std::binary_semaphore::release() triggering an immediate partial run of the scheduler only targeting threads that happen to have a std::binary_semaphore::acquire() on the same semaphore.
This is what's happening here. The measure_semaphore_latency() thread is being woken up and potentially assigned to a CPU core immediately as the release() call is made, without waiting for the next scheduling "cycle".
It's still not guaranteed that the OS will choose to preempt anything for that just-woken-up thread. This is where the high standard deviation you are seeing comes from: The thread either gets immediate CPU time, or gets it at a later scheduling cycle, there's no in-between.
As to why I can be so confident that this is the case in your test: With a bit of debugging and symbols loading, we can get the following call stacks:
On the acquire side:
ntdll.dll!00007fffa4510764() Unknown
ntdll.dll!00007fffa44d379d() Unknown
ntdll.dll!00007fffa44d3652() Unknown
ntdll.dll!00007fffa44d3363() Unknown
KernelBase.dll!00007fffa225ce9f() Unknown
> msvcp140d_atomic_wait.dll!`anonymous namespace'::__crtWaitOnAddress(volatile void * Address, void * CompareAddress, unsigned __int64 AddressSize, unsigned long dwMilliseconds) Line 174 C++
msvcp140d_atomic_wait.dll!__std_atomic_wait_direct(const void * _Storage, void * _Comparand, unsigned __int64 _Size, unsigned long _Remaining_timeout) Line 234 C++
ConsoleApplication2.exe!std::_Atomic_wait_direct<unsigned char,char>(const std::_Atomic_storage<unsigned char,1> * const _This, char _Expected_bytes, const std::memory_order _Order) Line 491 C++
ConsoleApplication2.exe!std::_Atomic_storage<unsigned char,1>::wait(const unsigned char _Expected, const std::memory_order _Order) Line 829 C++
ConsoleApplication2.exe!std::counting_semaphore<1>::acquire() Line 245 C++
ConsoleApplication2.exe!acquire_and_set_t1() Line 17 C++
ConsoleApplication2.exe!std::invoke<void (__cdecl*)(void)>(void(*)() && _Obj) Line 1586 C++
ConsoleApplication2.exe!std::thread::_Invoke<std::tuple<void (__cdecl*)(void)>,0>(void * _RawVals) Line 56 C++
ucrtbased.dll!00007fff4c7b542c() Unknown
kernel32.dll!00007fffa2857034() Unknown
ntdll.dll!00007fffa44c2651() Unknown
On the release side:
ntdll.dll!00007fffa44d2550() Unknown
> msvcp140d_atomic_wait.dll!`anonymous namespace'::__crtWakeByAddressSingle(void * Address) Line 179 C++
msvcp140d_atomic_wait.dll!__std_atomic_notify_one_direct(const void * _Storage) Line 251 C++
ConsoleApplication2.exe!std::_Atomic_storage<unsigned char,1>::notify_one() Line 833 C++
ConsoleApplication2.exe!std::counting_semaphore<1>::release(const __int64 _Update) Line 232 C++
ConsoleApplication2.exe!measure_semaphore_latency() Line 29 C++
ConsoleApplication2.exe!main() Line 36 C++
ConsoleApplication2.exe!invoke_main() Line 79 C++
ConsoleApplication2.exe!__scrt_common_main_seh() Line 288 C++
ConsoleApplication2.exe!__scrt_common_main() Line 331 C++
ConsoleApplication2.exe!mainCRTStartup(void * __formal) Line 17 C++
kernel32.dll!00007fffa2857034() Unknown
ntdll.dll!00007fffa44c2651() Unknown
Poking around the code of __crtWakeByAddressSingle(), and __crtWaitOnAddress() (see on github) we find that the invoked kernel functions are WaitOnAddress() ref and WakeByAddressSingle() ref.
From this documentation, we find our confirmation in the remarks section of WaitOnAddress():
WaitOnAddress does not interfere with the thread scheduler.
|
69,914,394 | 69,914,581 | variadic number of methods as template input parameter | Is it possible to specify a member-function template parameter pack?
Something like this:
template <typename foo, void (foo::*bar)(void) ...>
void application()
{
}
None of my solutions work, and I would like to avoid putting every function that I'm gonna use in a struct.
| The syntax for this is
template <typename C, void (C::*...mfuncs)()>
void application()
{
// ...
}
or with typedef:
template <typename C>
using MemberFunc = void (C::*)();
template <typename C, MemberFunc<C>...mfuncs>
void application();
|
69,914,457 | 69,915,496 | How to handle connect errno in cpp socket programming | I am new to Network Programming and am currently following Beej's Guide to get familiar with this content.
When the book was introducing the getaddrinfo() function, it told me about using gai_strerror() to interpret the error code returned to readable strings. However, the book doesn't cover the error handle method for connect() and I wonder if there is a similar function that would do the same job as what gai_strerror() does for getaddrinfo()?
Here is my code:
if((status=connect(sockfd, res->ai_addr, res->ai_addrlen)) != 0){
fprintf(stderr, "connect: %s\n", function_to_be_used(status));
return 2;
}
| From connect function reference:
If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set to indicate the error.
So, you need the following code:
fprintf(stderr, "connect: %s\n", strerror(errno));
getaddrinfo error handling is kind of exception, most API set errno on error, which can be converted to error message using strerror.
|
69,914,464 | 69,914,699 | Is it valid to pass use nullptr as a streambuf, to default initialize std::istream? | Is this code standard-compliant?
class MyIstream : std::istream {
MyStreamBuf buf;
public:
MyIstream():
std::istream(nullptr)
{
set_rdbuf(&buf);
}
}
Do I have to create MyDummyStreamBuf, to bypass lack of default istream c-tor?
| https://en.cppreference.com/w/cpp/io/basic_ios/rdbuf
says
Returns the associated stream buffer. If there is no associated stream buffer, returns a null pointer.
Seems to me like it is valid to have an istream (basic_istream/basic_ios) with no stream associated, iow with nullptr.
BTW, I would perhaps use rdbuf(...), instead of set_rdbuf().
Interestingly, rdbuf(ptr) also seems to explicitly allow passing a nullptr:
Sets the associated stream buffer to sb. The error state is cleared by calling clear(). Returns the associated stream buffer before the operation. If there is no associated stream buffer, returns a null pointer.
|
69,914,624 | 70,235,898 | How do I properly initialise the input/output arguments for this C++ for openCL kernel? | This is my first time writing OpenCL compute units, so I'm starting small; Here is my basic test kernel:
kernel void test_kernel(global float* in, global float* out)
{
int thread_id = get_global_id(0);
printf("%d", thread_id);
out[thread_id] = in[thread_id] + thread_id;
}
And here is the c++ code that is trying to construct buffers for the arguments and run it:
...
...
cl::Kernel kernel(program, "test_kernel", &cl_error);
if (cl_error != 0) {
std::cout << "Error - cl::Kernel - " << getErrorString(cl_error) << std::endl;
return 1;
}
cl::CommandQueue command_queue(context, device);
cl::vector<float> input_vector{ 0.1f, 0.2f, 0.3f, 0.4f, 0.5f };
cl::vector<float> output_vector{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
cl::Buffer input_buffer(std::begin(input_vector), std::end(input_vector), true);
cl::Buffer output_buffer(std::begin(output_vector), std::end(output_vector), false);
cl::EnqueueArgs enqueue_args(command_queue, cl::NDRange(5));
cl::KernelFunctor<cl::Buffer, cl::Buffer> functor(kernel);
functor(enqueue_args, input_buffer, output_buffer);
for (const auto& value : output_vector) {
std::cout << value << ", ";
}
My hope is to print the results of output vector buffer after running the kernel, which should equate to input[n] + n, however I'm only getting the initial 0s that I populated the output vector with. I have tried a number of things, but to no avail as of yet so I've scaled it back for clarity. The kernel does build, and I get no errors running it, I just don't get the results I hoped for. I also can't see any of the print statement output.
For further context, my hardware is capable of up to openCL 1.2, running on macOS, and I have defined the openCL definitions to state that I'm using openCL 1.2 specifically.
Can anyone see what I'm doing wrong in my setup code?
| Your test_kernel looks good.
But on the C++ side, you are missing a few things:
Create the buffers on the device context, so OpenCL knows on the memory of what device it should allocate the memory:
const int N = 5;
cl::Buffer input_buffer(context, CL_MEM_READ_WRITE, N*sizeof(float));
cl::Buffer output_buffer(context, CL_MEM_READ_WRITE, N*sizeof(float));
You have to link the Buffer objects to the Kernel parameters. Otherwise, OpenCL does not know which of the buffers in memory corresponds to which of the parameters of test_kernel.
kernel.setArg(0, input_buffer);
kernel.setArg(1, output_buffer);
Before you execute the kernel, you need to copy over input_vector from CPU memory to input_buffer in GPU memory:
command_queue.enqueueWriteBuffer(input_buffer, true, 0, N*sizeof(float), (void*)input_vector);
Note: output_buffer in GPU memory remains uninitialized and could contain random values. Since your test_kernel writes every entry in output_buffer and dos not read any entry of output_buffer, you don't need command_queue.enqueueWriteBuffer(output_buffer, ...) here.
Execute the kernel:
const int local = 1; // GPU warp size is 32, so this should be 32 or a multiple of 32 to get full performance. For the test with N=5, I have set it to 1.
const int global = ((N+local-1)/local)*local;
cl::NDRange range_local = cl::NDRange(local);
cl::NDRange range_global = cl::NDRange(global);
command_queue.enqueueNDRangeKernel(kernel, cl::NullRange, range_global, range_local);
command_queue.finish();
Copy output_buffer from GPU memory back to output_vector in CPU memory:
command_queue.enqueueReadBuffer(output_buffer, true, 0, N*sizeof(float), (void*)output_vector);
Note: The true in enqueueReadBuffer makes it a blocking command, meaning after this line the queue is automatically emptied and the data transfer is complete; you don't need an additional command_queue.finish(); here.
The updated data is now in CPU memory in output_vector and can be further processed on the CPU or printed in the console.
|
69,914,635 | 69,914,672 | How do I make an Int in C++ have a limit? | Is there any way I could ensure an int doesn't cross a certain limit? and if it needs to (if the program is adding numbers to the int and it crosses the limit) it goes back to 0 and does the job from there?
| It sounds like you want the modulo operator %.
If the upper limit is limit then
value = value % limit; // Or value %= limit
will "reset" the value back to zero if it's about to pass the limit.
|
69,915,393 | 69,915,510 | How to use class in a different class constructor | I started learning C++ recently and I'm having a problem with an assignment I need to write, my assignment requires that I will create a class constructor that has another variable of a different class type.
my main class is 'person' and I have two other classes 'address and 'job', in my assignment I need to create setter and getter for each variable I have in the different classes, and in each setter and getter I have to print if the operation was successful or not.
so here is the problem I haveing, when I call the 'person' parameter constructor in my main file its immediately call 'address' and 'job' default constructor which prints the default setter and getter in their constructors and that is something I want to avoid because I don't want it to print the default values, is there any way of avoiding the default constructor?
unfortunately, I can't remove the printד from the setter and getter and I can't change the variables of the 'person' constructor, also I have to use the set and get in the default constructor
class person
{
private:
char *name;
char *phoneNumber;
char *email;
int savings;
address Address;
job Job;
public:
person();
person(const char *name, const char *phoneNumber, const char *email, address Address, job Job);
~person();}
address:
class address {
private:
char* street;
char* city;
int postalCode;
public:
address();
address(const char* street,const char* city, int postalCode);
~address();}
job:
class job {
private:
char* title;
int salary;
departmentEnum department;
public:
job();
job(const char* title, int salary, departmentEnum department);
~job();}
person constructor - it actually prints both the default values of 'address' and 'job' and the values I sent to the person constructor.
person::person(const char *nameP, const char *phoneNumberP, const char *emailP, address AddressP, job JobP)
{
setName(nameP);
setPhoneNumber(phoneNumberP);
setEmail(emailP);
Address.setCity(AddressP.getCity());
Address.setPostalCode(AddressP.getPostalCode());
Address.setStreet(AddressP.getStreet());
Job.setSalary(JobP.getSalary());
Job.setDepartment(JobP.getDepartment());
Job.setTitle(JobP.getTitle());
}
address default constructor
address::address()
{
setStreet("test");
setCity("test");
setPostalCode(12345);
}
| If all you want is to avoid the default constructor being called, all you have to is use an initializer instead.
person::person(person::person(const char *nameP, const char *phoneNumberP, const char *emailP, address AddressP, job JobP) :
Address(AddressP),
Job(JobP)
{
//Do your stuff
}
This way, the default constructor of the internal address and job are skipped. Instead the (implicit) copy constructor is used.
You could also use the (explicit) secondary constructor, if you were to pass the raw values instead of the already done object.
Example:
person::person(const char *nameP, const char *phoneNumberP, const char *emailP, address AddressP, char* title, int salary, departmentEnum department) :
Address(AddressP),
Job(title, salary, department)
{
//Do your stuff
}
In the lower example, you will find that Job's second constructor is called.
The upper will not produce any output by the way, because you have not defined Job::Job(const Job &otherJob); (the copy constructor).
|
69,915,569 | 70,274,713 | Modern CMake: How do you deal with .dll files on Windows? | I am currently in the process of porting a Linux codebase on Windows. I finally got everything to compile and run, except for one thing: I do not know how to handle .dll files. So far I have been copying them manually because I was working on a single cmake configuration, but this is far from ideal.
So my question is: how can I make my executable work with CMake ? As far as I understand, DLL files HAVE to be in the same directory, so I probably need to copy them, but I do not understand the proper way to do it. I have been googling and results were not very satisfying (usually they had code snippets for specific libs and it seemed relatively 'quick and dirty').
I have multiple dependencies I need to get dlls from, most notably OpenCV, Qt, openssl, etc.
Is there a way to do it in a "generic" way, as in getting a property from an imported target and copying it ? I don't really want to explicitly list every single .dll...
In my CMakeLists I handle my dependencies using Find_Package and using target_link_libraries with the imported target.
I'm just wondering what is the best way to do this, or if I am doing something fundamentally wrong.
Edit: Consider the following CMakeLists.txt:
cmake_minimum_required (VERSION 3.8)
project ("OpenCV_HelloWorld")
find_package(OpenCV 4.4.0 REQUIRED COMPONENTS core imgproc video)
# Add source to this project's executable.
add_executable (OpenCV_HelloWorld OpenCV_HelloWorld.cpp OpenCV_HelloWorld.h) # pretty much empty files, the main just declares a cv::Mat
target_link_libraries(OpenCV_HelloWorld ${OpenCV_LIBS} )
This compiles properly, however, when trying to run it I get a message saying I need opencv_core440.dll.
What would be the best way to correct this ?
| I have managed to partly solve this problem using CMake 3.21's $<TARGET_RUNTIME_DLLS:tgt> generator expression. However, this will only work if the libraries tgt links with are properly set as SHARED. In theory, this will handle all dependencies. In real life, a lot of package config files were written with UNKNOWN type instead of shared, so these will have to be handled individually.
|
69,916,043 | 69,916,135 | C++ Templates for classes | in this code I tried to make a template for my class, and also 2 template functions, one for standard types and one for my template class, but I wanted to see if I can make a template in a template to get a defined function (I don't know if this was the right way to make it). Finally, after I run the code it gives me some weird errors, like syntax errors etc. Thx for help!
#include <iostream>
template <typename T>
class Complex
{
T _re, _im;
public:
Complex(T re = 0, T im = 0) :_re{re}, _im{im} {};
~Complex() {}
Complex<T>& operator=(const Complex<T>& compl) { if (this == &compl) return *this; this._re = compl._re; this._im = compl._im; return *this; }
Complex<T> operator+(const Complex<T>& compl) { Complex<T> temp; temp._re = _re + compl._re; temp._im = _im + compl._im; return temp}
friend std::ostream& operator<<(std::ostream& os, const Complex<T>& compl) { os << compl._re << " * i " << compl._im; return os; }
};
template <typename T>
T suma(T a, T b)
{
return a + b;
}
template <template<typename> typename T, typename U>
void suma(T<U> a, T<U> b)
{
T<U> temp;
temp = a + b;
std::cout << temp;
}
int main()
{
int a1{ 1 }, b1{ 3 };
std::cout << "Suma de int : " << suma<int>(a1, b1) << std::endl;
double a2{ 2.1 }, b2{ 5.9 };
std::cout << "Suma de double: " << suma<double>(a2, b2) << std::endl;
Complex<int> c1(3, 5), c2(8, 9);
std::cout << "Suma comple int: ";
suma<Complex, int>(c1, c2);
return 0;
}
| compl is a c++ keyword (as an alternative for unary operator ~). You used compl as your operator overload parameters.
I didn't know this just a few minutes ago. How did I find out? I pasted your code into godbolt.org and it highlighted the words "compl" as if they were keywords. One Internet search later, they are indeed keywords.
There's also the use of this._re = ... and this._im = ... which doesn't work since this is a pointer and not a reference, so it should be this->_re = ... or preferably, just _re = ....
|
69,916,044 | 69,916,116 | Implementing Factory Function with STL by Replicating Abseil Example | Trying to better understand Tip of the Week #42: Prefer Factory Functions to Initializer Methods by replicating the example using the standard template library. OP provides the example code:
// foo.h
class Foo {
public:
// Factory method: creates and returns a Foo.
// May return null on failure.
static std::unique_ptr<Foo> Create();
// Foo is not copyable.
Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;
private:
// Clients can't invoke the constructor directly.
Foo();
};
// foo.c
std::unique_ptr<Foo> Foo::Create() {
// Note that since Foo's constructor is private, we have to use new.
return absl::WrapUnique(new Foo());
}
When trying to replicate the example, I use a different approach in the foo.c section:
std::unique_ptr<Foo> Foo::Create() {
// Attempt to create using std::unique_ptr instead of absl::WrapUnique
return std::unique_ptr<Foo>(new Foo());
}
Compiling with the following commands results in a failed linker command
$ clang++ -g -Wall -std=c++11 -fsanitize=address foo.cc -o Foo
Undefined symbols for architecture arm64:
"Foo::Foo()", referenced from:
Foo::Create() in robots-cda3fd.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Thoughts about what I'm missing here? Thanks!
| You still need to define Foo::Foo()
In the header you can do Foo() = default, even in the private section
In the cpp you can do Foo::Foo() = default or Foo::Foo() {}
|
69,916,126 | 69,918,014 | Unaligned address in vtable | I don't know if this is the right place to ask a question like this, so please redirect me if needed.
I am working on an embedded MCU (STM32L5) and am having trouble with some C++ code crashing with a hard fault. After further investigation, I determined that the cause is a branch to an unaligned (i.e., no word aligned) memory address. After more digging, I found that this is happening on a branch to a virtual method. And, to the best of what I can determine, it looks like the address within the vtable itself is "invalid" (i.e., not word aligned). Here are some images to illustrate what I am seeing.
While stepping through those three lines (0x080349ce to 0x080349d2) the register values are as follows:
R2 = 0x20005484 -> Pointer address to my abstract object
R3 = 0x805a398 -> Pointer to within the vtable of the class (see the highlighted entry in "memory details")
R3 = 0x8032f15 -> The unaligned address read from the the vtable in memory (see the highlighted entry in "memory")
My question is, should I be blaming the compiler for doing something it shouldn't be, or could there be something wrong with my code that would cause this type of problem? I am compiling the code using -Og optimizations.
EDIT
The actual object (which I am calling the virtual method of) resides in the stack within a lambda as follows:
[this, event, args...](){
Event<ARGS...> e(event, args...);
dispatch(&e);
}
Where Event<> is a templated class that inherits from my abstract base class AbstractEvent and which implements the virtual method clone().
The dispatch() function takes a const AbstractEvent* and calls a few more methods before eventually reaching the assembly code above (which is the defer method below). Thus, at the point where I attempt to call the virtual method, the object should still be on the stack.
bool defer(const AbstractEvent* e) {
if ((e == nullptr) || (_deferQueue.full())) {
return false;
} else {
AbstractEvent* clone = e->clone();
_deferQueue.push(clone);
return true;
}
And for reference, the implementation of AbstractEvent and Event<> are as follows:
class AbstractEvent {
public:
AbstractEvent(int index) : _index(index) { }
virtual ~AbstractEvent() = default;
int event() const { return _index; }
virtual AbstractEvent* clone() const = 0;
private:
int _index;
};
template <typename... ARGS>
class Event : public AbstractEvent {
public:
Event(int index, const ARGS&... args) :
AbstractEvent(index),
_values(args...)
{
}
Event(const Event& other) = default;
AbstractEvent* clone() const override { return new Event(*this); }
template <unsigned int INDEX = 0>
inline const auto& value() const {
return std::get<INDEX>(_values);
}
private:
std::tuple<ARGS...> _values;
};
| Thank you to @11c for pointing our about "thumb" instructions. It turns out that my problem is no actually where I think it is and is thus not a compiler issue. What I believed to be an unaligned address was actually normal behavior for the processor.
For reference, see the following:
https://www.embedded.com/introduction-to-arm-thumb/
https://www.keil.com/support/man/docs/armasm/armasm_dom1361289866046.htm
|
69,916,244 | 69,916,941 | C++ getting lowest level of a tree | I need to know how many leafs have a tree but with some conditions.
All the children or leafs, will be always on the same level, but it can be the level 1,2,3,4,5 ... I don't know which one will be. So you can't count grandhildren + grandgrandchildren ... they will be at the same level and will be the lower of them, in that case: grandgrandchildren.
There must be a node without leafs, but if it is not the lowest level of leafs, it doesn't have to count as leaf.
I will try to explain myself with some examples. Imagine you have this tree:
A
|- B
| |- B1
| |- B2 Number of 'leafs' = 2 (B1 and B2). C doesn't count as it is in an
| upper level)
|- C
Another example:
A
|- B
| |- B1
| |- B2 Number of 'leafs' = 3 (B1,B2,D1)
|
|- C
|- D
|-D1
Another example:
A
|- B
| |- B1
| | |-B11
| |- B2 Number of 'leafs' = 1 (B11). D1 is not a leaf. It is a 'node' as
| leafs in this case are in level 4 (counting A as 1)
|- C
|- D
|-D1
I'm working with C++ and Qt with something similar to QTreeWidgetItem so I have an object (let's call it myTree and I can ask something like: myTree->childCount() so in the first example, if I call it, it will say 2 (B and C) and for each one I can repeat the operation.
I was trying to count everything that gives me childcount() but then, it gaves me 4 (B,C,B1 and B2) instead of 2 (B1,B2) which is what i want...Here I put what I was trying:
int grandchild = 0;
for (int i = 0; i < myTree->childCount( ); ++i)
{
Obj* child = myTree->child( i ); //Get the children. First time will be B and C
if (child)
{
grandchild += p_child->childCount( ); // Here I wanted to get a total, for first example, I will get 3 which is not what I want
}
}
Thank you in advance.
| For recursive functions, you start with the assumption that the function, when operating on a node, will return all relevant information about that node. Each node then only needs to inspect its children and itself to decide what to return to the level above it.
If the node has no children, then the result is trivial: this node has one max depth node at a depth of 0 (itself).
Otherwise, the max depth is equal to the largest max depth among its children + 1, and the count is equal to the sum of the counts of all children that share the largest max depth.
#include <utility>
#include <vector>
struct node_type {
std::vector<node_type*> children;
};
// returns the max depth between the node and all of its children
// along with the number of nodes at that depth
std::pair<int, int> max_depth_count(const node_type& node) {
int depth = 0; // itself
int count = 1; // itself
for (const auto c : node.children) {
auto [child_depth, child_count] = max_depth_count(*c);
child_depth++;
if (child_depth > depth) {
depth = child_depth;
count = child_count;
}
else if (child_depth == depth) {
count += child_count;
}
}
return {depth, count};
}
|
69,916,654 | 70,010,102 | PyImport_Import segmentation fault after reading in TSV with C++ | I am using C++ as a wrapper around a Python module. First, I read in a TSV file, cast it as a numpy array, import my Python module, and then pass the numpy array to Python for further analysis. When I first wrote the program, I was testing everything using a randomly generated array, and it worked well. However, once I replaced the randomly generated array with the imported TSV array, I got a segmentation fault when I tried to import the Python module. Here is some of my code:
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#define PY_SSIZE_T_CLEAN
#include <python3.8/Python.h>
#include "./venv/lib/python3.8/site-packages/numpy/core/include/numpy/arrayobject.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <random>
#include <fstream>
#include <sstream>
int main(int argc, char* argv[]) {
setenv("PYTHONPATH", ".", 0);
Py_Initialize();
import_array();
static const int numberRows = 1000;
static const int numberColumns = 500;
npy_intp dims[2]{ numberRows, numberColumns };
static const int numberDims = 2;
double(*c_arr)[numberColumns]{ new double[numberRows][numberColumns] };
// ***********************************************************
// THIS PART OF THE CODE GENERATES A RANDOM ARRAY AND WORKS WITH THE REST OF THE CODE
// // initialize random number generation
// typedef std::mt19937 MyRNG;
// std::random_device r;
// MyRNG rng{r()};
// std::lognormal_distribution<double> lognormalDistribution(1.6, 0.25);
// //populate array
// for (int i=0; i < numberRows; i++) {
// for (int j=0; j < numberColumns; j++) {
// c_arr[i][j] = lognormalDistribution(rng);
// }
// }
// ***********************************************************
// ***********************************************************
// THIS PART OF THE CODE INGESTS AN ARRAY FROM TSV AND CAUSES CODE TO FAIL AT PyImport_Import
std::ifstream data("data.mat");
std::string line;
int row = 0;
int column = 0;
while (std::getline(data, line)) {
std::stringstream lineStream(line);
std::string cell;
while (std::getline(lineStream, cell, '\t')) {
c_arr[row][column] = std::stod(cell);
column++;
}
row++;
column = 0;
if (row > numberRows) {
break;
}
}
// ***********************************************************
PyArrayObject *npArray = reinterpret_cast<PyArrayObject*>(
PyArray_SimpleNewFromData(numberDims, dims, NPY_DOUBLE, reinterpret_cast<void*>(c_arr))
);
const char *moduleName = "cpp_test";
PyObject *pname = PyUnicode_FromString(moduleName);
// ***********************************************************
// CODE FAILS HERE - SEGMENTATION FAULT
PyObject *pyModule = PyImport_Import(pname);
// .......
// THERE IS MORE CODE BELOW NOT INCLUDED HERE
}
So, I'm not sure why the code fails when ingest data from a TSV file, but not when I use randomly generated data.
EDIT: (very stupid mistake incoming) I used the conditional row > numberRows for the stopping condition in the while loop and so this affected the row number used for the final line in the array. Once I changed that conditional to row == numberRows, everything worked. Who knew being specific about rows when building an array was so important? I'll leave this up as a testament to stupid programming mistakes and maybe someone will learn a little something from it.
| Note that you don't have to use arrays for storing the information(like double values) in 2D manner because you can also use dynamically sized containers like std::vector as shown below. The advantage of using std::vector is that you don't have to know the number of rows and columns beforehand in your input file(data.mat). So you don't have to allocate memory beforehand for rows and columns. You can add the values dynamically.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include<fstream>
int main() {
std::string line;
double word;
std::ifstream inFile("data.mat");
//create/use a std::vector instead of builit in array
std::vector<std::vector<double>> vec;
if(inFile)
{
while(getline(inFile, line, '\n'))
{
//create a temporary vector that will contain all the columns
std::vector<double> tempVec;
std::istringstream ss(line);
//read word by word(or double by double)
while(ss >> word)
{
//std::cout<<"word:"<<word<<std::endl;
//add the word to the temporary vector
tempVec.push_back(word);
}
//now all the words from the current line has been added to the temporary vector
vec.emplace_back(tempVec);
}
}
else
{
std::cout<<"file cannot be opened"<<std::endl;
}
inFile.close();
//lets check out the elements of the 2D vector so the we can confirm if it contains all the right elements(rows and columns)
for(std::vector<double> &newvec: vec)
{
for(const double &elem: newvec)
{
std::cout<<elem<<" ";
}
std::cout<<std::endl;
}
return 0;
}
The output of the above program can be seen here. Since you didn't provide data.mat file, i created an example data.mat file and used it in my program which can be found at the above mentioned link.
|
69,917,163 | 69,922,574 | How to draw the content of a NavigationView page? | I'm trying to make an UWP app.
I decided to add a NavigationView object, and I created some sections. I read the documentation, but I didn't find out how to draw the content of the page.
There is a Content property, but it sets the content of the page's label in the menu, not the content of the page of a single label as I'm trying to do.
How can I do it?
Thanks to everyone that will answer.
| Update:
For the setting page, if you are using the default item of the NavigationView by enabling the IsSettingsVisible property, you could check the IsSettingsInvoked value of the NavigationViewItemInvokedEventArgs.
Here is the code that you could refer to
void App3::MainPage::nvSample_ItemInvoked(Windows::UI::Xaml::Controls::NavigationView^ sender, Windows::UI::Xaml::Controls::NavigationViewItemInvokedEventArgs^ args)
{
if (args->IsSettingsInvoked == true)
{
contentFrame->Navigate(Windows::UI::Xaml::Interop::TypeName(SettingPage::typeid));
}
else
{
auto navItemTag = args->InvokedItemContainer->Tag->ToString();
if (navItemTag != nullptr)
{
// navigation logic here. You could use switch or other condition. This if is just a example.
if (navItemTag->Equals("SamplePage1"))
{
contentFrame->Navigate(Windows::UI::Xaml::Interop::TypeName(SamplePage1::typeid));
}
}
}
}
If I understand you correctly, you want to show a Page in the NavigationView, right?
Generally, we will add a Frame object in the NavigationView content. The Frame Object could show the Page as you want.
Here is a very simple example about the NavigationView:
<NavigationView x:Name="nvSample" ItemInvoked="nvSample_ItemInvoked" Loaded="nvSample_Loaded">
<NavigationView.MenuItems>
<NavigationViewItem Icon="Play" Content="Menu Item1" Tag="SamplePage1" />
<NavigationViewItem Icon="Save" Content="Menu Item2" Tag="SamplePage2" />
<NavigationViewItem Icon="Refresh" Content="Menu Item3" Tag="SamplePage3" />
<NavigationViewItem Icon="Download" Content="Menu Item4" Tag="SamplePage4" />
</NavigationView.MenuItems>
<Frame x:Name="contentFrame"/>
</NavigationView>
In the code-behind, you will need to handle the NavigationView.ItemInvoked Event to control the navigation. Like the following code:
void App3::MainPage::nvSample_ItemInvoked(Windows::UI::Xaml::Controls::NavigationView^ sender, Windows::UI::Xaml::Controls::NavigationViewItemInvokedEventArgs^ args)
{
auto navItemTag = args->InvokedItemContainer->Tag->ToString();
if (navItemTag != nullptr)
{
// navigation logic here. You could use switch or other condition. This if is just a example.
if (navItemTag->Equals("SamplePage1"))
{
contentFrame->Navigate(Windows::UI::Xaml::Interop::TypeName(SamplePage1::typeid));
}
}
}
void App3::MainPage::nvSample_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
//This is the HomePage
contentFrame->Navigate(Windows::UI::Xaml::Interop::TypeName(HomePage::typeid));
}
This is a very simple c++/cx demo. You could get more information about the NavigationView Document:NavigationView. Or check it in the XAML Controls Gallery app.
You could also check the NavigationView Source code here: Get the source code (GitHub).
|
69,917,276 | 69,917,801 | Can you delete a specific file before building in Visual Studio 2019/2022 | The project I am working on creates a cache file the first time it is built and ran, but if you make a code change and then re-run the project the file doesn't replace the cache and will instead run the old version of the code. To fix this you have to manually delete the file every time, but I was wondering if there is a way to get Visual Studio to delete that file any time it has to build/rebuild new code?
I am using a regular VS solution generated by CMake.
| A good idea would be use Visual Studio Build Events.
Read the doc about how to personalize Build Events here.
Using custom Build events you can run command before or after a compiling process.
|
69,917,287 | 69,926,289 | c++20, clang 13.0.0, u8string support | I'm using clang 13.0.0 in a CMAKE-based project, CMAKE_CXX_STANDARD is defined as 20. The following code causes a compilation error (no type named 'u8string' in namespace 'std'):
#include <iostream>
#include <string>
int main() {
#ifdef __cpp_char8_t
std::u8string sss = u8"a"; // <---- this branch is picked up
#else
std::string sss = "b"
#endif
return 0;
}
Below is the CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
project(clang_test)
add_executable(clang_test main.cpp)
Am I missing something or is it a clang bug? I mean, if std::u8string is not yet there, the macro shouldn't be defined, right? By the way, if you know the way to undefine it somehow with the CMake, please, share your experience. Here the topic starter faces the same problem, I think, but there is no solution proposed yet.
Update: the platform is RHEL 8.4
Update 2: moved the 'project' call below the compiler settings in the CMakeLists.txt
| Frank's suggestion was correct - the problem is in that Clang was using an older version of libstdc++ and not libc++;
target_compile_options(clang_test PRIVATE -stdlib=libc++)
fixes the issue for me. Though I don't entirely understand why it doesn't work with libstdc++, if you have any idea, please, share it here - I assume that this is a separate question.
Also, Tsyvarev's point is indeed a very important one, and the compiler should be set before the project call. I've corrected the example in my question.
Update: Finally I understand the reason why it fails: __cpp_char8_t is not sufficient for std::u8string, __cpp_lib_char8_t should be used instead.
Thanks everyone for your help!
|
69,917,696 | 69,917,856 | How do I test if a type is within another class exists? | I was thinking that I could test (with C++14) if a class contained a type, I could do this:
#include <type_traits>
struct X {
using some_type = int;
};
struct Y {};
template <typename T, typename = void>
struct has_some_type : std::false_type {};
template <typename C>
struct has_some_type<C, typename C::some_type> : std::true_type {};
static_assert(has_some_type<X>::value); // unexpectedly fails
static_assert(has_some_type<Y>::value); // correctly fails
But the static_assert fails, which surprised me, since checking for a member function would work in a similar way.
#include <type_traits>
struct X {
void some_function();
};
struct Y {};
template <typename T, typename = void>
struct has_some_function : std::false_type {};
template <typename C>
struct has_some_function<C, decltype(std::declval<C>().some_function())> : std::true_type {};
static_assert(has_some_function<X>::value); // correctly succeeds
static_assert(has_some_function<Y>::value); // correctly fails
Why doesn't this work and how would I test if a class has a type?
| Why does the has_some_type trait fail?
It's because the deduction of the second template argument only uses the primary template, and doesn't "take hints" from your template specialization.
Think of your partial specialization of has_some_type when you substitute X for C:
template <>
struct has_some_type<X, int> : std::true_type {};
this substitution doesn't fail, but - why would it match has_some_type<X>? When the compiler sees has_some_type<X>, it will ruthlessly ignore your attempts to catch its attention, and simply use the = void for deducing the second template parameter.
Why does the has_some_function trait succeed?
Look at the second type you use in the specialization: decltype(std::declval<C>().some_function()). What is that type resolve to, for X? ... yes, it resolves to void. So when you substitute X for C, it's:
template <>
struct has_some_function<X, void> : std::true_type {};
and this will match has_some_function<X>, using the = void from the primary template.
How can we fix the has_some_type trait?
While C++17 and C++20 offer easier solutions (as suggested by @Frank and @Quimby) - let's stick to C++14 and think about fixing what we've already written.
From the has_some_function example, we might be inspired to "fix" the type trait by replacing the primary template with template <typename T, typename = int> ; but while this would work for X and Y, it would not work if you had using some_type = double or any other non-int type. And that's not what we want :-(
So, can we have a type whose definition is: "check the validity of some_type, whatever it may be, but eventually just behave like a single fixed type"? ... Yes, it turns out that we can.
#include <type_traits>
struct X {
using some_type = int;
};
struct Y {};
template<typename T>
using void_t = void;
// Please Mr. Compiler, make sure T is a legit type, then use void.
template<typename, typename = void>
struct has_some_type : std::false_type { };
template<typename T>
struct has_some_type<T, void_t<typename T::some_type>> : std::true_type { };
static_assert(has_some_type<X>::value, "Unfortunately, X doesn't have some_type");
static_assert(has_some_type<Y>::value, "Unfortunately, Y doesn't have some_type");
Only the second assertion fails.
See this in action on GodBolt.
Notes:
This solution is actually valid C++11.
C++17 introduced std::void_t to save you some typing. It also supports variadic parameter packs rather than just single types.
If you use an old compiler, the code above may fail due to C++ standard defect CWG1558.
|
69,918,132 | 69,918,499 | Localization of Special Folder Constants | Does anyone happen to know if there is a complete list of Windows 10 localized folders (like this one just for all folders)?
I am trying to create a custom explorer where the folder should be displayed in the user's native language.
I have already tried to get a complete list of localized folders using the ShellSpecialFolderConstants enumeration or the Environment.SpecialFolder enumeration.
but there are still a few missing (C:/Users for example).
SHGetFileInfo is unfortunately also out of the question, because otherwise the performance would suffer massively.
I have thought of simply designing a long selection statement for it in which all localized folders are stored.
And if there was already a table of equivalents, it would of course be very handy to know.
Thanks in advance!
| Microsoft does not provide a list because you are not supposed to know, you are supposed to use the special/known folder API. This is to prevent people from hard-coding c:\Program files etc. In older versions of Windows the folders on disk were often localized. In Vista this changed and the real names are English now.
If you are building a custom Explorer then you should be dealing with IShellFolder/IShellItem and they can provide the display name.
If you are working at a lower level and ignoring the shell namespace you can call SHGetLocalizedName. This name can be applied to any folder, not just special folders.
If you for some reason only care about the special folders and not paths in general, IKnownFolder::GetFolderDefinition claims to return a structure that includes the localized name.
|
69,918,203 | 69,918,969 | Executing threads taking turns | I have a function that just prints thread id it is called from. I want 2 threads call this function taking turns n times. I had implemented this functionality in pthreads with a condition variable but it is too verbose. What I want program to print as follows:
id: 0
id: 1
id: 0
id: 1
id: 0
id: 1
...
In the end, "id: 0" and "id: 1" should be printed n times.
What is the idiomatic way of doing this OpenMP?
| You can check the thread number against your iteration count and implement the handoff with a barrier.
#include <omp.h>
#include <cstdio>
int main()
{
/* note that it is not pragma omp parallel for, just a parallel block */
# pragma omp parallel num_threads(2)
for(int i = 0; i < 10; ++i) {
if((i & 1) == (omp_get_thread_num() & 1))
std::printf("%d: thread %d\n", i, omp_get_thread_num());
# pragma omp barrier
}
}
|
69,918,360 | 69,918,594 | For loops counting past the limit C++ | I have a really strange problem with for loop. I have to make a program that given the sum of three dice it has to find all possible combinations of those three dice that yield that sum. The problem is that for loops are counting past the limit that they have and I don't have any idea why.
for (k1 = 1; k1 <= 6; k1++) //k1 - die 1
{
for (k2 = 1; k2 <= 6; k2++) //k2 - die 2
{
for (k3 = 1; k3 <= 6; k3++) //k3 - die 3
{
if (k1+k2+k3 == z) //z - sum
cout<<k1<<"-"<<k2<<"-"<<k3<<endl;
}
if (k1+k2+k3 == z)
cout<<k1<<"-"<<k2<<"-"<<k3<<endl;
}
if (k1+k2+k3 == z)
cout<<k1<<"-"<<k2<<"-"<<k3<<endl;
}
If I input 16 for the sum, these are the results that I get:
2-7-7
3-6-7
4-5-7
4-6-6
5-4-7
5-5-6
5-6-5
6-3-7
6-4-6
6-5-5
6-6-4
These are valid results for the sum of 16 but I shouldn't have number 7 on dice and the dice shouldn't be able to get to 7 because of how for is made.
I am using c++ 17 in Eclipse with Eclipse CDT.
| This is happening because you have k2,k3 variables which are allocated higher.
As for loop works until it will end loop when k3=7. So, k3 will save it and after loop when you're getting it, you got 7.
You could use one of proposed approaches by Seth Faulfner or Yksisarvinen.
If you want to save values for future using, use Seth Faulfner's code.
If it is not necessary use Yksisarvinen's code.
|
69,918,542 | 69,918,685 | Can std::bit_cast be used to cast from std::span<A> to std::span<B> and access as if there was an array of object B? | #include <array>
#include <bit>
#include <span>
struct A {
unsigned int size;
char* buf;
};
struct B {
unsigned long len;
void* data;
};
int main() {
static_assert(sizeof(A) == sizeof(B));
static_assert(alignof(A) == alignof(B));
std::array<A, 10> arrayOfA;
std::span<A> spanOfA{arrayOfA};
std::span<B> spanOfB = std::bit_cast<std::span<B>>(spanOfA);
// At this point, is using spanOfB standard compliant?
}
I've tried accessing bit_casted span on 3 major compilers and they seem to be working as expected, but is this standard compliant?
| No. While std::span in C++23 will be defined such that it must be trivially copyable, there is no requirement that any particular span<T> has the same layout of span<U>. And even if it did, you'd still be accessing the objects of type A through a glvalue of type B, which violates strict aliasing if A and B aren't allowed to be accessed that way. And in your example, they are not.
|
69,918,587 | 69,919,210 | I am getting the warning for a piece of code, but the c++ book by bjarne stroustrup is saying it should be an error. what is right here? | As per book The C++ Programming Language, 4th Edition -
In C and in older C++ code, you could assign a string literal to a
non-const char*:
void f()
{
char* p = "Plato"; // error, but accepted in pre-C++11-standard code
p[4] = 'e'; // error : assignment to const
}
It would obviously be unsafe to accept that assignment. It was (and
is) a source of subtle errors, so please don’t grumble too much if
some old code fails to compile for this reason.
It suggest that, above code should give error, but I am getting a warning instead.
21:22:38 **** Incremental Build of configuration Debug for project study ****
Info: Internal Builder is used for build
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\study.o" "..\\src\\study.cpp"
..\src\study.cpp: In function 'void f()':
..\src\study.cpp:10:13: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
| The GCC compiler is somewhat permissive by default and allows some extension such as implicitly converting away the constness of a string.
Most likely this extension was added to keep compatibility with C.
To disable those extensions, simply add the --pedantic-errors flag that will make the compiler refuse invalid code.
Live example
|
69,919,338 | 69,920,625 | LibAV FFmpeg C++ av_find_input_format("dshow") returning nullptr | I'm trying to use DirectShow devices with FFmpeg in a C++ program. I'm using DLLs built with vcpkg using the command .\vcpkg install ffmpeg[nvcodec]:x64-windows. The vcpkg log shows Enabled indevs: dshow
av_find_input_format is returning nullptr for me (no "dshow" devices found).
If I query the downloaded FFmpeg executable, I get a list of 14 "dshow" devices.
How can I get FFmpeg to return the list of "dshow" devices? Do I need to manually build FFmpeg using mingw-w64?
extern "C"
{
#include <libavformat/avformat.h>
#include <libavdevice/avdevice.h>
}
int main(int argc, char *argv[])
{
AVFormatContext* inFormatContext = avformat_alloc_context();
AVInputFormat* inFormat = av_find_input_format("dshow");
if (!inFormat || !inFormat->priv_class || !AV_IS_INPUT_DEVICE(inFormat->priv_class->category))
{
return false;
}
AVDeviceInfoList* deviceList;
int deviceCount = avdevice_list_input_sources(inFormat, nullptr, nullptr, &deviceList);
avdevice_free_list_devices(&deviceList);
avformat_free_context(inFormatContext);
return 0;
}
| You have to call avdevice_register_all() before av_find_input_format("dshow").
The following code returns a valid pointer:
avdevice_register_all();
AVInputFormat* inFormat = av_find_input_format("dshow");
I don't know much about the subject, but I guess avdevice_register_all() expands the list of available formats.
|
69,919,768 | 69,923,791 | How to get back to project after adding a header file in Visual Studio | I have added a header file for a project I am working on and I can't figure out how to get out of the header file and back to where I code. Am I just being stupid?
| Take it easy, you only need to copy the header file you want to add to the project file and you can use #include" "to call the header file. In my example, I copied the Header.h file to the project file, and then Use #include"Header.h" in the .cpp file, which can use the content in the header file.
|
69,919,780 | 69,919,949 | Why rebind<U>::other are deprecated in C++17 and removed in C++20? | I know that it deprecated and removed only in std::allocator. And I can implement it on my own allocators. But why it is deprecated?
| rebind was a clunky, pre-C++11 way of taking an allocator type for T and converting it into an allocator type for U. I say "pre-C++11" because C++11 gave us a much more convenient way to do it: template aliases.
allocator_traits template has a member template alias rebind<U> that computes Allocator<U> for the allocator it is a trait for. It can use the rebind member of the allocator if it is available, otherwise, it just yields Allocator<U>.
allocator_traits effectively defines a lot of functionality that std::allocator used to provide. This made a lot of members of std::allocator redundant, so they have been deprecated and removed in favor of the traits-based defaults.
|
69,919,801 | 69,919,936 | Read Input of different data types in one line C++ | The program I'm working on requires a user to input something like i v or r v, where i means insert, r means remove, and v would be an integer to be inserted or removed.
How can I read the input and separate it into two variables, one for the operator (as in i or d) and another for the value?
Example:
cout << "Enter decision";
cin >> decision;
// somehow split the decision into the two variables below.
int value;
char operation;
| If you want to read something into a std::string (which I assume is what decision is), you should use std::getline. Formatted input, like cin >> decision;, will only read one word by default. Any whitespace character will make it stop reading.
if(std::getline(std::cin, decision)) {
// successfully read a line
}
You then need to split the decision into the two variables. One simple solution is to use a std::istringstream. You copy the std::string into a std::istringstream and extract the values from it:
#include <sstream>
// ...
std::istringstream is(decision);
if(is >> operation >> value) {
// success
}
Depending on the rest of the program, another option is to read directly from std::cin into the two variables and skip reading into decision:
if(std::cin >> operation >> value) {
// success
}
|
69,920,357 | 69,920,683 | Eigen vector constructor initialization vs comma initialization | For Eigen vectors of a fixed size (eg Eigen::Vector3d, Eigen::Vector4f) there is the option to initialize the vector using the constructor as follows:
Eigen::Vector3d a(0.0, 1.0, 2.0);
However, Eigen also offers a way to use comma initialization of a general Eigen matrix that can be used in this case:
Eigen::Vector3d b;
b << 0.0, 1.0, 2.0;
Is one of the two methods preferable for speed or some other reasons? Or are they equal?
| One advantage of the first version is that it will fail at compile time if you pass the wrong number of arguments, e.g. because you misstyped Vector2d as Vector3d.
Performance-wise, the compiler is able to optimize both the same. Checked it with GCC.
|
69,921,199 | 69,923,873 | Is it possible to determine how many messages are in a POSIX message queue? | I am working with POSIX running on a RHEL machine. Is there a way to check the number of messages that are remaining in a message queue (System V Preferably)?
The purpose of this is simply a desire to know which queues have the most messages at a given time so that I can make a "managing" thread receive the messages in a Longest-Queue-First manner.
I didn't see anything about this in the man pages (that were C/C++-specific and not tied to IPCs).
Does anyone have an idea of how to do this?
| You said in comments that you are using msgget() to create the message queue. In that case, you can use msgctl() to get the number of messages in the queue, via the returned msqid_ds::msg_qnum struct field.
|
69,921,481 | 69,921,564 | Code to take value from file and print average, max and min does not work | I want to take a large number of different numbers from a file and give back the Average, Max, and Min values to the command line. I came so far, just to loop over the code, not further. I have tried many ways but nothing is working. Can you please guide me?
fstream my_file ("values.txt");
vector<int> nums;
double input;
// int max_value {0};
// int min_value {0};
// double average_value = accumulate(nums.begin(), nums.end(), 0) / nums.size();
while (my_file >> input)
{
nums.push_back(input);
}
for(int num : nums){
cout << num << endl;
}
| Your code looks OK, except for you need to accumulate after you populate your vector:
fstream my_file ("values.txt");
vector<int> nums;
double input;
while (my_file >> input )
{
nums.push_back(input);
}
double average_value = accumulate(nums.begin(), nums.end(), 0) / nums.size();
|
69,921,650 | 69,922,030 | Extraction Operator reaching EOF on istringstream, behavioral change with int/char/string | So I am doing some simple file I/O in c++ and I notice this behaviour, not sure if I am forgetting something about the extraction operator and chars
Note that the file format in Unix.
ifstream infile("test.txt");
string line;
while(getline(infile, line)){
istringstream iss(line);
**<type>** a;
for(...){
iss >> a;
}
if(iss.eof())
cout << "FAIL" << endl;
}
Say that the input file test.txt looks like this and the <type> of a is int
$ is the newline character (:set line)
100 100 100$
100 100 100$
what I notice is that after the first line is read, EOF is set true;
If the input file is like so, and the <type> of a is char:
a b c$
a b c$
Then the Code behaves perfectly as expected.
From what I understand about File I/O and the extraction operator, the leading spaces are ignored, and the carriage lands on the character after the input is taken out of the input stringstream iss. So in both cases, at the end of each stringstream the carriage lands on the newline character, and it shouldn't be an EOF.
Changing the <type> of a to string had similar failure as <type> = int
BTW failbit is not set,
at the end:
good = 0
fail = 0
eof = 1
| getline has extracted and discarded the newline, so line contains 100 100 100, not 100 100 100$, where $ is representing the newline. This means reading all three tokens from the line with a stringstream and the >> operator may reach the EOF and produce the FAIL message.
iss >> a; when a is an int or a string will skip all preceding whitespace and then continue extracting until it reaches a character that can't possibly be part of an int or is whitespace or is the end of the stream. On the third >> from the stream, the end of the stream stops the extraction and the stream's EOF flag is set.
iss >> a; when a is an char will skip all preceding whitespace and then extract exactly one character. In this case the third >> will extract the final character and stop before seeing the end of the stream and without setting the EOF flag.
|
69,921,670 | 69,921,703 | patsubst in GNU make returns nothing | I am trying to have my cpp source files and my object files in separate directories, so I'm trying to use Make's patsubst to replace the paths. After nothing was compiling, I made a phony target to simply print out the relevant variables and I discovered that patsubst was returning nothing. This doesn't make a lot of sense to me, as from what I can tell, targets that don't match the pattern should pass through unchanged, so even if my patterns are malformed I should still be seeing something get returned.
My variables are declared like this:
SRC_DIR := source/
SRC := $(wildcard $(SRC_DIR)*.cpp)
OBJ_DIR := obj/
OBJ := $(PATSUBST $(SRC_DIR)%.cpp, $(OBJ_DIR)%.o, $(SRC))
My phony target that just prints out the above variables looks like this:
.PHONY: print
print:
@echo $(SRC_DIR)
@echo $(SRC)
@echo $(OBJ_DIR)
@echo $(OBJ)
and the result of running make print is this:
user@athena:~/proj$ make print
source/
source/main.cpp source/util.cpp
obj/
user@athena:~/proj$
Other things I've tried
I've tried SRC_DIR and OBJ_DIR having trailing slashes and not having them, I've tried $(SRC:$(SRC_DIR)%.cpp=$(OBJ_DIR)%.o) which did work, and $(OBJ) would have both main.o and util.o, but then my static rule ($(OBJ): $(OBJ_DIR)%.o : $(SRC_DIR)%.cpp) would only trigger for main.cpp, and wouldn't try to compile util.cpp, which I'm considering a completely separate issue?
I hope I'm just doing something dumb and there's a simple fix, but I've been racking my brain and I can't see what would be causing patsubst to just be blank. Any help would be greatly appreciated.
| Like (virtually) all programming languages, makefiles are case-sensitive. $(FOO) is not the same as $(foo), and $(PATSUBST ...) is not the same as $(patsubst ...).
In fact, $(PATSUBST ...) is nothing and expands to the empty string.
|
69,922,029 | 69,922,102 | How can a array provide storage? | In C++ draft The first paragraph is talking about situations where an array provides storage:
If a complete object is created ([expr.new]) in storage associated
with another object e of type “array of N unsigned char” or of type
“array of N std::byte” ([cstddef.syn]), that array provides storage
for the created object if:...
In these cases array is refering to an unsigned char C[1] or to std::array? If is the first case, I can, for example, create an object at the same memory addres of a existing array C and then this array C will provide storage, but only if its type is the cited above? What would happen if it was just a char array and not a unsigned char array?
|
In these cases array is refering to an unsigned char C[1] or to std::array?
"Array" refers to arrays such as T[N].
"Array" doesn't refer to std::array. std::array isn't an array, but rather it is a class template. std::array may contain an array as a member.
array (with formatting that signifies code) refers to std::array.
What would happen if it was just a char array and not a unsigned char array?
Strict interpretation would be that no other type could "provide storage" for another object unless that is specified by another rule.
A loose interpretation would be that other types may provide storage, and the conditions that follow the quoted rule do not apply to them.
|
69,922,229 | 69,949,698 | C++ compiler error MDM2009 Duplicate type found processing metadata file referencing 2 Windows Component Libraries that both reference another library | My solution structure looks like this:
The compiler complains that it finds duplicate types (of every public interface/class) in WCL1.winmd b/c that winmd file already exists in WCL4's bin directory.
One problem is that I know absolutely nothing about C++ and the link offered in the Answer to this question provides a C++ workaround that doesn't help (it's literally like reading a different-but-related language -- i.e. reading German when I only know English).
I also found this which provides another workaround but doesn't tell you where to put it. I added the specified ItemGroupDescription element into every .csproj file as well as the application's PropertySheet.props file to no avail.
I have also done the following:
Moved the code from WCL2 into WCL3 and removed WCL2 from the
solution.
Had the application reference WCL1, WCL3 and WCL4.
Anyone else got any ideas? It would be greatly appreciated....
UPDATE:
Here's a link to a small solution that reproduces the compile errors.
It seems that it comes from the Microsoft.Windows.CppWinRT NuGet package referenced by the C++ Application. That package auto-generates C++ header files from the .winmd files generated by the component projects referenced by the Application.
| Well....it's not perfect but this is how I got around the problem...Add the following line to each ProjectReference in each Component .csproj file:
I'm not sure what the intention of this particular Xml element was, but by setting Private=false, the compiler doesn't copy the InterfaceDefinitionComponent.winmd file into the other Components' bin directory which prevents the C++ compiler from seeing duplicate .winmd files and blowing up because it's trying to generate multiple identical C++ header files for the same Type.
|
69,922,431 | 69,922,469 | Copy temporary buffer to out buffer | In C++, how do I copy a temporary buffer (buffer) to out buffer (outBuffer) using strncpy?
void writeSensorStatus(SensorStatus& data, char* outBuffer[256])
{
// create temporary buffer
char buffer[256];
const size_t capacity = JSON_OBJECT_SIZE(3);
StaticJsonDocument<capacity> doc;
serializeJson(data, buffer);
strncpy(outBuffer, buffer, sizeof(outBuffer)); // Problem is here
}
I get the following error, on the lien trying to copy: cannot convert 'char**' to 'char*'
What I'm trying to do here is to retrieve the new values added to buffer outside the method. (Like a return)
| void writeSensorStatus(SensorStatus& data, char* outBuffer[256])
When char* outBuffer[256] is passed as a function parameter, it decays to a pointer to a pointer to char, not a string.
Change this to:
void writeSensorStatus(SensorStatus& data, char* outBuffer)
But this will affect sizeof(outBuffer), so you can use what @paddy suggests, pass by reference:
void writeSensorStatus(SensorStatus& data, char (&outBuffer)[256])
|
69,922,638 | 69,922,709 | Conversion from `const char[]` to non-scalar type requested | I'm trying to make a class that wraps a pointer around another type. With all of the extraneous bits removed, it looks like this:
template<typename T>
class field {
std::unique_ptr<T> t_;
public:
field() : t_(nullptr) {}
field(const T &t) : t_(std::make_unique<T>(t)) {}
field<T> &operator=(const T &t) {
t_.reset(new T(t));
return *this;
}
};
I can declare them by explicitly calling their constructors, but not with =, like so:
int main() {
field<std::string> strA("Hello");
field<std::string> strB = "Hello";
return 0;
}
I get the error
-snip-/StringImplicit/main.cpp: In function ‘int main()’:
-snip-/StringImplicit/main.cpp:21:31: error: conversion from ‘const char [6]’ to non-scalar type ‘field<std::__cxx11::basic_string<char> >’ requested
21 | field<std::string> strB = "Hello";
| ^~~~~~~
Where am I going wrong? I can't seem to use field<std::string>s in class constructors with raw strings without this conversion either, it throws the same error.
Edit: The end goal is something like discordpp::ApplicationCommandOption option{.type = 3, .name = "message", .description = "The message to echo", .required = true}; where all of those parameters are differently-typed fields.
| The problem is that two class-type conversions are required:
const char[6] to std::string
std::string to field<std::string>.
There is a rule that implicit conversion can have at most one class-type conversion (the official term is "user-defined" conversion although this includes class types that are part of the standard library).
To fix it you can either use your suggested fix; or manually specify one of the conversions, e.g:
auto strB = field<std::string>("Hello");
field<std::string> strC = std::string("Hello");
field<std::string> strD = "Hello"s;
or you could add a constructor for const char[].
SFINAE version of char array constructor (there will be better ways in C++20 I'm sure):
template<size_t N, typename = std::enable_if_t<std::is_same_v<T, std::string>>>
field(char const (&t)[N])
: t_(std::make_unique<T>(t)) {}
|
69,922,718 | 69,922,787 | How to get a field object using its name in proto3 | I am migrating schemas from proto2 to proto3 syntax. I want to eliminate extensions as they are not supported. Is it possible to get an object using a field name in proto3, similar to what MutableExtension does in proto2.
For example,
Schema in proto2 syntax
message Foo {
message Bar {
unint32 a = 1;
}
extend Foo {
Bar b = 1;
}
}
C++
Foo::Bar b_val = foo.MutableExtension(Foo::b);
Now in proto3, I could do this:
syntax="proto3";
message Foo {
message Bar {
unint32 a = 1;
}
Bar b = 1;
}
C++ code:
Foo::Bar b_val = foo.mutable_b();
However, I want to use the name Foo::b to get a Foo::Bar object. Is there a way to do this?
| It's not clear why you need this but what you are asking for is kinda feasible.
Foo::b is a garden variety member function, which means that &Foo::b is a regular pointer-to-member-function.
So you can use it as such using the regular c++ syntax for these entities:
auto b_ref = &Foo::b;
Foo::Bar b_val = (foo.*b_ref)();
|
69,923,184 | 69,924,659 | C++ Overloading the plus operator to add an element to an object | Constructor for object
Set<T>::Set() {
buckets = new forward_list<T>[9];
numBuck = 9;
numElem = 0;
maxLoad = 9;
}
Overloading of plus operator
Set<T>::operator+(T elem){
Set<T> res;
return res;
}
I don't quite know where to begin with this. This overloaded operator add its parameter elem to a copy of *this and return the result.
ex:
Set<char>setA;
Set<char>setB;
setA.Add('a')
setA.Add('b')
setA.Add('c')
// setA contains {'a','b','c'}
setB = setA + 'd'
// setB should now contain {'a','b','c','d'}
Any guidance?
edit: Clarified operator overload functionality
| You can just make a copy function in the set, and use the Add function inside the overload. Demo code:
Set<T>::operator+(T elem)
{
Set<T> result;
result.Copy(*this);
result.Add(elem);
return result;
}
NOTE: Or you can follow @jxh's answer and use the default copy constructor. I would make a Copy function just to be explicit. :)
|
69,923,609 | 69,923,677 | Please help me to know what is happening in this code | string kthDistinct(vector<string>& arr, int k) {
unordered_map<string, int> m;
for (auto &s : arr)
++m[s];
//Frome here
for (auto &s : arr)
if (m[s] == 1 && --k == 0)
return s;
return "";
//to here
}
Especially in this part
for (auto &s : arr)
if (m[s] == 1 && --k == 0)
return s;
| That block of code is a bit on the dense side. If we rewrite the same logic in a more verbose manner, we get:
for (auto &s : arr) {
if (m[s] == 1) {
k -= 1;
if (k == 0) {
return s;
}
}
}
return string{""};
Since m contains the number of time a string appears within arr, we can interpret this as:
"Return the kth string of arr that appears only once within arr, otherwise, return the empty string."
|
69,924,241 | 69,924,289 | Move a std::map vs move all the elements of a std::map | std::map<int, Obj> mp;
// insert elements into mp
// case 1
std::map<int, Obj> mp2;
mp2 = std::move(mp);
// case 2
std::map<int, Obj> mp3;
std::move(std::begin(mp), std::end(mp), std::inserter(mp3, std::end(mp3));
I am confused by the two cases. Are they exactly the same?
| No, they are not the same.
Case 1 moves the content of the whole map at once. The map's internal pointer(s) are "moved" to mp2 - none of the pairs in the map are affected.
Case 2 moves the individual pair's in the map, one by one. Note that map Key s are const so they can't be moved but will instead be copied. mp will still contain as many elements as before - but with values in an indeterminable state.
|
69,924,357 | 69,924,519 | assigning an unsigned value to integer data type | I wrote code:
int a = -1U;
cout << a;
Why the output is -1 not 2^w-1?
As in the case of:
long long a = -1U;
cout << a;
The output comes out as
4294967295
| -1U is the negation of 1U. As an unsigned cannot have a negative value the result is incremented by (UINT_MAX + 1). Result UINT_MAX is 4294967295 on OP's machine.
In both of OP's cases, code is initializing a signed integer variable with 4294967295u.
int a = -1U;
Why the output is -1 not 2^w-1?
2w - 1 (w being the bit width 32) is outside the range of int a so a cannot have that value.
Assigning an out-of-range value to an int results in implementation defined behavior. On OP's machine, assigning 4294967295 to an int "wrapped" to -1.
long long a = -1U;
long long a = -1U; is like long long a = 4294967295; (see above), so a has the value of 4294967295, well within the long long range.
|
69,924,835 | 69,924,894 | Finding the size of datatypes in C ++ | I tried to write a program like this
#include<iostream>
using namespace std;
int main(){
int a ;//declaration
a = 12 ;//initialization
cout<<"size of int"<<size of (a)<<endl;
return 0;
}
and the output came like this
datatypes.cpp: In function 'int main()':
datatypes.cpp:8:26: error: 'size' was not declared in this scope; did you mean 'size_t'?
8 | cout<<"size of int"<<size of (a)<<endl;
| ^~~~
| size_t
[Done] exited with code=1 in 17.278 seconds
How to solve it ?
| There is no size of () function/operator in C++, there is only sizeof. C++ doesn't allow names to have spaces.
Note: sizeof is an operator, not a function.
You should change this to:
#include<iostream>
// using namespace std; is bad
int main(){
int a;
a = 12;
// sizeof is an operator, so you can do sizeof a.
// the parentheses aren't actually needed
// use newline character instead of std::endl
std::cout <<"size of int" << sizeof (a) << '\n';
return 0;
}
|
69,925,214 | 69,952,288 | I cannot display the linked list in c++ | I have a problem, I have created a new node.
And then I created a new node, to insert at beginning and show its display.
And then I created another node to insert it at the end but I cannot display it in the display function.
Can anyone tell me what's the issue here?
The display literally doesn't show up for the final linked list.
Here is the code :
#include<iostream>
using namespace std;
void createlinklist();
void insertatfirst();
void insertatend();
void display();
struct node {
int data;
node * link;
};
node * start = NULL;
node * location = NULL;
void createlinklist() {
node * temp = new node;
cout << "Enter data in first node";
cin >> temp -> data;
temp -> link = NULL;
start = temp;
location = temp;
}
void insertatfirst() {
node * temp = new node;
cout << "Enter data for new node at the beginning ";
cin >> temp -> data;
temp -> link = NULL;
start = temp;
temp -> link = location;
location = start;
cout << "Linked first after inserting data at is ";
while (location != NULL) {
cout << location -> data;
location = location -> link;
}
location = temp;
}
void insertatend() {
node * temp = new node;
cout << "Enter data for new node at the end ";
cin >> temp -> data;
temp -> link = NULL;
location = start;
while (location != NULL) {
location = location -> link;
}
location -> link = temp;
location = temp;
}
void display() {
location = start;
while (location != NULL) {
cout << "The final linked list after ending at last node is ";
cout << location -> data;
location = location -> link;
}
}
int main() {
createlinklist();
insertatfirst();
insertatend();
display();
}
| Your code is producing segmentation fault, look at these lines of code:
while (location != NULL) {
location = location -> link;
}
location -> link = temp;
location = temp;
you are running the loop until location is null and then assigning null -> link = temp (as location is already null) this is what is causing a segmentation fault.
Change
while (location != NULL)
to
while (location -> link != NULL)
Everything should work fine after this.
|
69,925,454 | 69,931,862 | Bespoke C++ Windows app crashing and producing an empty dmp file | We have an in-house c++ app that we are running via task scheduler. We are attempting to trace an issue with the app which causes a crash, a windows event and we would usually look for the .dmp file to enable us to track the issue in visual studio.
However, these windows dump files [appname. dmp] is zero bytes.
Is there anyone out there that knows the potential causes of the .dmp file being empty, please?
Sample event log below in case it helps.
Many thanks for any help and thoughts :)
Andy P
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
<Provider Name="Application Error" />
<EventID Qualifiers="0">1000</EventID>
<Level>2</Level>
<Task>100</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2021-11-09T15:48:04.642807400Z" />
<EventRecordID>5214</EventRecordID>
<Channel>Application</Channel>
<Computer>redacted>
<Security />
</System>
- <EventData>
<Data>redacted.exe</Data>
<Data>1.0.0.1</Data>
<Data>60816c15</Data>
<Data>KERNELBASE.dll</Data>
<Data>10.0.17763.2183</Data>
<Data>12a65345</Data>
<Data>e06d7363</Data>
<Data>001235e2</Data>
<Data>fa0</Data>
<Data>01d7d57fa38520cb</Data>
<Data>K:\redacted\redacted.exe</Data>
<Data>C:\WINDOWS\System32\KERNELBASE.dll</Data>
<Data>03eae790-81b8-4040-aab4-6068440c4db0</Data>
<Data />
<Data />
</EventData>
</Event>
| MSDN notes one very important restriction: writing a minidump from inside a just-crashed process is not reliable. It's not clear from your question whether you're using a separate process to write the dumps ("redacted.exe"?), so this is definitely a possible cause.
|
69,925,923 | 69,956,878 | How to write a custom exception class derived from std::invalid_argument? | How should I write an efficient exception class to show the error that can be prevented by fixing the source code mistakes before run-time?
This is the reason I chose std::invalid_argument.
My exception class(not working, obviously):
class Foo_Exception : public std::invalid_argument
{
private:
std::string Exception_Msg;
public:
explicit Foo_Exception( const std::string& what_arg );
virtual const char* what( ) const throw( );
};
explicit Foo_Exception::Foo_Exception( const std::string& what_arg ) // how should I write this function???
{
Exception_Msg.reserve( 130000 );
Exception_Msg = "A string literal to be appended, ";
Exception_Msg += std::to_string( /* a constexpr int */ );
Exception_Msg += /* a char from a const unordered_set<char> */;
}
const char* Foo_Exception::what( ) const throw( )
{
return Exception_Msg.c_str( );
}
An if block that throws Foo_Exception:
void setCharacter( const char& c )
{
if ( /* an invalid character (c) is passed to setCharacter */ )
{
try
{
const Foo_Exception foo_exc;
throw foo_exc;
}
catch( const Foo_Exception& e )
{
std::cerr << e.what( );
return;
}
}
/*
rest of the code
*/
}
int main( )
{
setCharacter( '-' ); // dash is not acceptable!
return 0;
}
As you can see, I need to concatenate Exception_Msg with a few substrings in order to form the completed message. These substrings are not only string literals but also constexpr ints and chars from a static std::unordered_set<char>. That's why I used std::string because it has the string::operator+= which is easy to work with. And needless to say, my goal is to reduce heap allocations down to only 1.
Another very important question is that where should I place the handler( the try-catch )? Inside the main() wrapping the setCharacter() or keep it inside setCharacter?
Please make a good and standard custom exception class similar to the above. Or write your own. Thanks in advance.
| I solved this problem based on the feedback that I received from others through comments and answers. So I decided to leave my own answer/solution here for future readers.
Below can be seen what I came up with after much thought and research. This solution is fairly simple and readable.
Here is the exception class interface:
Foo_Exception.h
#include <exception>
class Foo_Exception : public std::invalid_argument
{
public:
explicit Foo_Exception( const std::string& what_arg );
};
And here is its implementation:
Foo_Exception.cpp
#include "Foo_Exception.h"
Foo_Exception::Foo_Exception( const std::string& what_arg )
: std::invalid_argument( what_arg )
{
}
A function that throws Foo_Exception:
Bar.cpp
#include "Bar.h"
#include "Foo_Exception.h"
void setCharacter( const char& c )
{
if ( /* an invalid character (c) is passed to setCharacter */ )
{
std::string exceptionMsg;
exceptionMsg.reserve( 130000 );
exceptionMsg = "A string literal to be appended, ";
exceptionMsg += std::to_string( /* a constexpr int */ );
exceptionMsg += /* a char from a const unordered_set<char> */;
throw Foo_Exception( exceptionMsg );
}
/*
rest of the code
*/
}
How to handle the exception:
main.cpp
#include <iostream>
#include "Bar.h"
#include "Foo_Exception.h"
int main( )
{
try
{
setCharacter( '-' ); // The dash character is not valid! Throws Foo_Exception.
}
catch ( const Foo_Exception& e )
{
std::cerr << e.what( ) << '\n';
}
return 0;
}
Summary of the Changes:
Notice how there's no need for a what() function since the compiler generates it implicitly because Foo_Exception inherits from std::invalid_argument.
Also, the process of creating the exception message was moved from the Foo_Exception's ctor to the body of the function setCharacter which actually throws the aforementioned exception. This way, the Foo_Exception's ctor is not responsible for creating the message. Instead, it is created in the body of the function that throws and is then passed to the ctor of Foo_Exception to initialize the new exception object.
The data member std::string Exception_Msg was also removed from Foo_Exception as it wasn't needed anymore.
Finally, the try-catch block was moved to main() so that it now wraps around setCharacter() and catches a Foo_Exception object that it might throw.
Final word:
Any suggestions to further improve my answer is highly appreciated.
Thanks a ton for all the feedback.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.