I think that the default overload of == for valarray is not very convenient. By default x==y (for two valarrays x and y) returns a valarray<bool>, with true on the ith entry if x[i]==y[i]. Rather, I need a single bool, which tells me if both valarray<double> contain the same elements or not. I know I can do this with a cycle, but having to do the cycle every time is not convenient. What's the best workaround here? Is there a way for me to define my own overload of == (and also !=, <, and so on)?
lundi 29 juin 2015
C++ fstream is writing hex instead of string?
I'm trying to download a file using URLDownloadToFile() which is working so far, however I'm having trouble with the callback function and writing the callback output wszStatusText to a file.
Here is the function that's giving the problem:
HRESULT DownloadStatus::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR wszStatusText)
{
fstream myfile;
myfile.open("file.txt", ios::app);
// this prints hex e.g. StatusText: 00435F78
myfile << " StatusText: " << wszStatusText;
myfile.close();
// this prints the string properly e.g. text/plain
MessageBox(NULL, wszStatusText, L"test", MB_OK);
return S_OK;
}
The thing is that MessageBox() is showing the data properly...
How to declare unique_ptr of vector?
I am trying to declare a global vector of MyClass using unique_ptr. My compiler is 4.8.4.
glo.h
extern std::unique_ptr<std::vector<MyClass>> gl_vec;
glo.cpp
std::unique_ptr<std::vector<MyClass>> gl_vec;
And in the file where I initialize and use it for the first time in a different *.cpp file:
#include "glo.h"
// within function
{
gl_vec = std::unique_ptr<std::vector<MyClass>> ();
cout << "gl_vec size = " << (*gl_vec).size() << endl; // crashes here
}
Things keep crashing when I use the pointer. Anyone see what I'm doing wrong?
Qt QDir::current()
I had some code like this:
void MainWindow::saveData()
{
QDir oldDir=QDir::current();//this should return the main executable directory.Since there is no other place in my hole code where i temper with QDir.
QDir sess("Sessions");
if(!oldDir.exists("Sessions"))//if "Sessions" Dir doesn't exist
oldDir.mkdir("Sessions");//create it.
QDir::setCurrent(sess.absolutePath());
//some virtual code inside current Dir, which i didn't implement yet.
QDir::setCurrent(oldDir.absolutePath());//restore old dir
}
When i run my app firstly the code works perfectly.but in the second run, the first call to "QDir::current();" returns the "Sessions" Dir and not the main executable Dir as it should be restored in the first run.actually i did manage to overcome this by adding one line at the biginning of the code, the following :
QDir::setCurrent(QCoreApplication::applicationDirPath());
Still i want to know why the first code didn't work.already checked for the documentation of the functions and found nothing.
gmtime_r((time_t*)&title->start_time, &start_time);
I'm trying to compile on Microsoft visual studio 2013 on C++ a program written for linux ( is a mix of C and C++ (#include .h) and I'm going to convert all in C++ to not be more confused !)
the statement:
gmtime_r((time_t*)&title->start_time, &start_time);
return errors: Error 11 error C3861: 'gmtime_r': identifier not found IntelliSense: identifier "gmtime_r" is undefined
please help
Passing a reference-to-function as a universal reference
I'm struggling to understand what exactly happens when passing a reference-to-function to a function as a universal reference (what type is being deduced). Let's suppose we have a function foo that takes a param as a universal reference:
template<typename T>
void foo(T&& param)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
And then let's do the following:
void(&f)(int) = someFunction;
foo(f);
The result will be:
void foo(T&&) [with T = void (&)int]
This is perfectly understandable: we are passing lvalue to our function foo, so the deduced type is void(&)int, and the type of the param will be "void(&& &)int" which under reference collapsing rules becomes void(&)int. Param will be just an lvalue reference to a function.
But when I do the following:
void(&f)(int) = someFunction;
foo(std::move(f));
foo will print:
void foo(T&&) [with T = void (&)int]
which is exactly the same as before! What is happening here? Why the result is the same as when passing lvalue? I would expect that since we are passing rvalue to foo, the deduced type should be T = void(int), and param should become void(&&)int. This always happen with all other "normal" types (like classes, primitive types, etc.) Why is it different when dealing with function references?
Refresh a Combobox in C++?
I have a function that detects camera ports in 3D slicer, however it seems to only run once. When I unplug/plug in a camera, the number of ports should update in a combobox (designed in Qt), but nothing changes.
The function I'm using detects when the camera port is clicked:
void qSlicerTrackingModuleWidget::onCameraPortClicked(){
Q_D(qSlicerTrackingModuleWidget);
// Clear current entries
d->CameraPortComboBox->clear();
int n = 0;
// Loop over camera ports until last one is found. Add all available ports to combo box and exit.
while(1){
cv::VideoCapture cap = cv::VideoCapture(n);
if(!cap.isOpened()){
return;
}
QString portNum = QString::fromStdString(std::to_string(n++));
d->CameraPortComboBox->addItem(portNum);
qSlicerCoreApplication::processEvents();
}
}
The setup function runs last and assigns the GUI to the actual function.
connect( d->CameraPortComboBox, SIGNAL(clicked()), this, SLOT(onCameraPortClicked()));
I need it to refresh and try to detect the cameras every time the combobox is clicked on, but because of the interface setup I am not sure if it is possible. I don't think constantly refreshing the program is a good option, so I'm out of ideas. Is there any way to do this?
What is the use for buckets interface in std::unordered_map?
I've been watching this video from CppCon 2014 and discovered that there is an interface to access buckets underneath std::unordered_map. Now I have a couple of questions:
- Are there any reasonable examples of the usage of this interface?
- Why did the committee decide to define this interface, why typical STL container interface wasn't enough?
What reasons are there for having comparisons be only of the form <= and >= (and not including =< and =>)?
In many languages, such as Java and C/C++, comparisons are always done of the form <= and >=. For example, here is a working sample program:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Get inputs
int input1 = s.nextInt();
int input2 = s.nextInt();
// compare them
if (input1 >= input2) {
System.out.println("Input 1 is greater than or equal to input 2");
} else {
System.out.println("Input 1 is less than input 2");
}
}
}
And this compiles and runs correctly. However, if I change the one comparison line to be:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Get inputs
int input1 = s.nextInt();
int input2 = s.nextInt();
// compare them
if (input1 => input2) { // ------Changed this line------
System.out.println("Input 1 is greater than or equal to input 2");
} else {
System.out.println("Input 1 is less than input 2");
}
}
}
It produces a compiler error here, as it does in many other languages.
This is most certainly an error generated from the language's grammar. But why would the grammar forbid such a comparison? From a programmer's perspective, it should not matter on which side of the equal sign the comparison operator is used.
Because both of the comparisons that have the operator on the left side of the equals, it makes sense that the syntax parsing is done linearly (either left-to-right, or vice versa). But why would the order matter?
boost.asio: Accept IPv4 and IPv6 together
Short and simple question: I am new to boost.asio and I was wondering if it is possible to create a tcp::acceptor listening for both, IPv4 and IPv6 connections together. The tutorials on boost's homepage show something like this:
_acceptor = new tcp::acceptor(_ioService, tcp::endpoint(tcp::v4(), 3456));
where the endpoint is always specified with a specific protocol. Is it not possible to listen for IPv4 and IPv6 on the same port at the same time?
Is it possible to set a class object reference as a default parameter in c++ without const?
For example, this:
Class Point{
double x, y;
public:
Point();
bool testequal(const Point& p1, Point& p2 = Point()) const;
}
doesn't work. It gives me an error:
error: could not convert 'Point()' from Point to Point&
This works if I use it as,
bool testequal(const Point& p1, const Point& p2 = Point()) const;
or
bool testequal(const Point& p1, Point p2 = Point()) const;
But instead I want to use object p2 as a reference value whose data can be changed inside the implementation.
Edit:
Here is the complete program. Yes, it's trivial - I'd prefer it if you wouldn't assess the need for this code, but instead comment on whether it's possible to implement.
If not, could you please state why, and tell me what the right way to do it is. Is overloading the only option?
#ifndef __POINT_H__
#define __POINT_H__
Class Point{
double x, y;
public:
Point();
Point(double xx, double yy);
bool testequal(const Point& p1, Point& p2 = Point()) const;
// this declaration fails. alternative is to use const Point& p2 or Point p2.
// but it is vital that the default parameter should store some value in
// it which can be accessed at the function call location without returning it.
}
#include "Point.h"
Point::Point(): x(0), y(0) {}
Point::Point(double xx, double yy): x(xx), y(yy) {}
bool Point::testequal(const Point& p1, Point& p2){
if (this->x == p1.x && this->y == p1.y){
p2.x = this->x;
p2.y = this->y;
return true;
}
else
return false;
}
WIN32 Garbage from Reading COM Port
I am attempting to read a message that was sent on one COM port and received on another. The two ports are connected via two USB to Serial converters. When I attempt to read the transmitted message I get this:
Tx Baud rate: 9600 Rx Baud rate: 9600 Attempting to read... Hello, is ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠á☼ Done...
Press any key to continue . . .
The message should read "Hello, is there anybody out there!?"
we is the code I have written:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <Windows.h>
typedef struct COMDevice {
HANDLE deviceHandle;
DWORD actualBytesReadOrWritten;
int deviceStatus;
std::string message;
DCB controlSettings;
} COMDevice;
int main(int argc, char *argv[]) {
// create new device
COMDevice *comWriter = new COMDevice;
COMDevice *comReader = new COMDevice;
// setup
comWriter->deviceHandle = NULL;
comWriter->actualBytesReadOrWritten = 0;
comWriter->deviceStatus = 0;
comWriter->message = "Hello, is there anybody out there!?";
comReader->deviceHandle = NULL;
comReader->actualBytesReadOrWritten = 0;
comReader->deviceStatus = 0;
comReader->message = "";
// open COM1 for writing
comWriter->deviceHandle = CreateFile(TEXT("COM5"), GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0);
if(comWriter->deviceHandle == INVALID_HANDLE_VALUE) {
std::cout << "Error occurred opening port for writing...\n";
return (int)GetLastError();
}
// open COM4 for reading
comReader->deviceHandle = CreateFile(TEXT("COM4"), GENERIC_READ, 0, 0, OPEN_ALWAYS, 0, 0);
if(comReader->deviceHandle == INVALID_HANDLE_VALUE) {
std::cout << "Error occurred opening port for reading...\n";
return (int)GetLastError();
}
// check baud rates
if(GetCommState(comWriter->deviceHandle, &comWriter->controlSettings) == 0 ||
GetCommState(comReader->deviceHandle, &comReader->controlSettings) == 0) {
std::cout << "Error occurred getting the comm state...\n";
return (int)GetLastError();
}
else {
std::cout << "Tx Baud rate: " << comWriter->controlSettings.BaudRate << std::endl;
std::cout << "Rx Baud rate: " << comReader->controlSettings.BaudRate << std::endl;
}
// write message to serial port
comWriter->deviceStatus = WriteFile(comWriter->deviceHandle, comWriter->message.c_str(),
comWriter->message.length(), &comWriter->actualBytesReadOrWritten, NULL);
if(comWriter->deviceStatus == FALSE) {
std::cout << "Error occurred writing to port..\n";
return (int)GetLastError();
}
// wait a few
int i = 0, count = 4000;
while(i < count) { i++; }
// read
std::cout << "Attempting to read...\n";
char buffer[1024];
comReader->deviceStatus = ReadFile(comReader->deviceHandle, buffer, 1023,
&comReader->actualBytesReadOrWritten, NULL);
if(comReader->deviceStatus == FALSE) {
return (int)GetLastError();
}
std::cout << buffer << std::endl;
// close handles
(void)FlushFileBuffers(comReader->deviceHandle);
(void)CloseHandle(comWriter->deviceHandle);
(void)CloseHandle(comReader->deviceHandle);
// clean up...
delete comWriter;
delete comReader;
std::cout << "Done...\n";
return 0;
}
I also use the DCB structure to check the baud rates at both ends...they match. Is there something else I may be missing?
Too many libboost_*.lib
I have downloaded boost 1.58.0 (precompiled, x86, VC 12.0) from http://ift.tt/1eGdNQa and installed to C:\local\boost_1_58_0 (I also tried compiled the source code using msvc-12.0 by myself and get the same result.
The problem: I see too many libboost*.lib of the same library, for example
ls -l libboost_math_* returns:
libboost_math_c99f-vc120-mt-1_58.lib
libboost_math_c99f-vc120-mt-gd-1_58.lib
libboost_math_c99f-vc120-mt-s-1_58.lib
libboost_math_c99f-vc120-mt-sgd-1_58.lib
libboost_math_c99f-vc120-s-1_58.lib
libboost_math_c99f-vc120-sgd-1_58.lib
libboost_math_c99l-vc120-mt-1_58.lib
libboost_math_c99l-vc120-mt-gd-1_58.lib
libboost_math_c99l-vc120-mt-s-1_58.lib
libboost_math_c99l-vc120-mt-sgd-1_58.lib
libboost_math_c99l-vc120-s-1_58.lib
libboost_math_c99l-vc120-sgd-1_58.lib
libboost_math_c99-vc120-mt-1_58.lib
libboost_math_c99-vc120-mt-gd-1_58.lib
libboost_math_c99-vc120-mt-s-1_58.lib
libboost_math_c99-vc120-mt-sgd-1_58.lib
libboost_math_c99-vc120-s-1_58.lib
libboost_math_c99-vc120-sgd-1_58.lib
libboost_math_tr1f-vc120-mt-1_58.lib
libboost_math_tr1f-vc120-mt-gd-1_58.lib
libboost_math_tr1f-vc120-mt-s-1_58.lib
libboost_math_tr1f-vc120-mt-sgd-1_58.lib
libboost_math_tr1f-vc120-s-1_58.lib
libboost_math_tr1f-vc120-sgd-1_58.lib
libboost_math_tr1l-vc120-mt-1_58.lib
libboost_math_tr1l-vc120-mt-gd-1_58.lib
libboost_math_tr1l-vc120-mt-s-1_58.lib
libboost_math_tr1l-vc120-mt-sgd-1_58.lib
libboost_math_tr1l-vc120-s-1_58.lib
libboost_math_tr1l-vc120-sgd-1_58.lib
libboost_math_tr1-vc120-mt-1_58.lib
libboost_math_tr1-vc120-mt-gd-1_58.lib
libboost_math_tr1-vc120-mt-s-1_58.lib
libboost_math_tr1-vc120-mt-sgd-1_58.lib
libboost_math_tr1-vc120-s-1_58.lib
libboost_math_tr1-vc120-sgd-1_58.lib
My questions: 1. Why are there so many lib files for one library? (36 files for libboost_math, 4 libboost_atomic, 6 libboost_iostreams and so on) 2. Why are there no single libboost_math.lib, libboost_atomic, ... files? 3. If I want to use boost_math, which library should I choose?
Storing large data arrays on the stack
I was watching a video that said: on Windows the size of the stack allocated in virtual memory, per process, is 1mb. I wasn't sure if it was correct, but anyway ...
So I was thinking; What happens if you declare a local variable within a function with a size that exceeds 1MB? Let's say and array of 1 byte char's whos size is around 2MB:
char oops[2000000];
There isn't enough space on the stack (if only 1mb is allocated for the stack) to reserve the required memory for the char array. What happens? Would this raise some memory exception?
And if infact an exception would be raised, the way around this would to be to declare the variable on the heap with malloc (deleting it at the end of the function)?
I would test, except I'm not at a computer.
SDL textures no longer rendering after restructuring code
I have been following the tutorials found here and I decided to deviate a bit before moving on.
I made a basic texture wrapper with which rendering textures worked fine. I then made a GameObject Class that stores a texture, a SDL_rect and, a dimension/location for the SDL_rect. I also tried to implement the standard update/draw loop with function pointers. So after setting all of this up, the textures that previously rendered perfectly fine (which I am testing with again) no longer work under this extra wrapper
From my main.cpp:
//the Texture that we will be applying an image on
Texture TextureOne("PNGTest.png");
Texture TextureTwo("Test2.png");
Texture TextureThree("Test3.png");
GameObject Background(TextureTwo);
GameObject Viewport(TextureOne);
GameObject TextBoxBackground(TextureThree);
first I declare my objects:
Background.Dimensions.x = SCREEN_WIDITH / 2;
Background.Dimensions.y = SCREEN_HEIGHT / 2;
Background.Location.x = SCREEN_WIDITH / 2;
Viewport.Dimensions.x = SCREEN_WIDITH / 2;
Viewport.Dimensions.y = SCREEN_HEIGHT / 2;
TextBoxBackground.Dimensions.x = SCREEN_WIDITH;
TextBoxBackground.Dimensions.y = SCREEN_HEIGHT / 2;
TextBoxBackground.Location.y = SCREEN_HEIGHT / 2;
//clear screen
SDL_RenderClear(Renderer);
//for all objects in the object list
for(unsigned i = 0; i < ObjectList.size(); i++)
{
//update the object
ObjectList[i]->Update(*ObjectList[i]);
//then draw the updated object
ObjectList[i]->Draw(*ObjectList[i]);
}
//upadte screen
SDL_RenderPresent(Renderer);
Then I set up the various dimensions and locations and finally call the objects update and draw
Here is the game object constructor being used:
GameObject::GameObject(Texture TargetTexture)
{
Dimensions.x = 1;
Dimensions.y = 1;
ObjectStorage.x = Location.x;
ObjectStorage.y = Location.y;
ObjectStorage.w = Dimensions.x;
ObjectStorage.h = Dimensions.y;
Update = DefaultUpdate;
Draw = DefaultDraw;
ObjectTexture = TargetTexture;
ObjectList.push_back(this);
}
here is the update function:
float DefaultUpdate(GameObject& Self)
{
float CurrentTime = SDL_GetTicks();
Self.ObjectStorage.w = Self.Dimensions.x;
Self.ObjectStorage.h = Self.Dimensions.y;
Self.ObjectStorage.x = Self.Location.x;
Self.ObjectStorage.y = Self.Location.y;
if(CurrentTime > LastTime)
{
DeltaTime = (CurrentTime - LastTime) / 1000;
LastTime = CurrentTime;
}
return DeltaTime;
}
and lastly the draw function:
void DefaultDraw(GameObject& Self)
{
SDL_RenderSetViewport(Renderer, &Self.ObjectStorage);
SDL_RenderCopy(Renderer, Self.ObjectTexture.GetCurrentTexture(),
NULL, NULL);
}
I have a sneaking suspicion that the issue is in the draw function, in that the SDL_Viewport/SDL_RenderCopy lose meaning after going out of scope, or that I should be updating the renderer with in the draw function, but I cannot seem to get those to work, are there any suggestions or should I just give up on this architecture entirely?
I dont understand how this array of pointers is working
I dont understand why I have to increment de variable contador before I do this
palabras[contador]=auxiliar;
palabras is an array of char pointers that I declared like this:
char *palabras[13];
Which I think is the proper way to do it. This array of pointers would store words that have a max size of 12. I created contador as a global variable and initialized to 0. But if I don't put contador++; before using palabras[contador]=auxiliar the program will crash, for some reason I can't write in the palabras[0] array.
void leerArchivo()
{
ifstream archivo("palabras.txt", ios::in);
char linea[13];
char *auxiliar;
if(archivo.fail())
{
cerr<<"Error al abrir el archivo palabras.txt"<<endl;
getch();
}else
{
while(!archivo.eof())
{
archivo.getline(linea, sizeof(linea));
contador++; //???
auxiliar=linea; //copy the first address of the array linea
palabras[contador]=auxiliar;
cout<<" "<<palabraSize(palabras[contador])<<" "; //????
cout<<palabras[contador]<<endl;
}
archivo.close();
}
}
Parsing hex values with Boost Spirit
I have been playing around with parsing with Boost Spirit and was wondering if anyone could help me get this to work. I have a simple parser that takes a file containing a pair of entries on each line. Something similar to the following:
Foo 04B
Bar 1CE
Bam 456
My code below currently parses this out and places each pair into a std::map and it seems to work correctly. What I really want to do is parse out the second string on each line and convert it to an integer. I have looked at int_parser and how you can specify the base but have been unable to get a similar setup to compile.
namespace qi = boost::spirit::qi;
std::map results;
void insert(std::pair p) {
results[p.first] = p.second;
}
template
bool parse_numbers(Iterator first, Iterator last) {
using qi::char_;
using qi::parse;
qi::rule<Iterator, std::pair<std::string, std::string>()> assignment;
assignment = +(~char_(' ')) >> +(char_);
bool r = parse(
first,
last,
assignment[&insert]);
if (first != last)
return false;
return r;
}
int main(int argc, char* argv[]) { std::ifstream ifs; std::string str; ifs.open (argv[1], std::ifstream::in);
while (getline(ifs, str)) {
if (!parse_numbers(str.begin(), str.end())) {
std::cout << "Parsing failed\n";
}
}
return 0;
}
What I would really like if to parse it out directly as a std::pair<std::string, int>. Any help is appreciated.
wstring to wchar_t conversion
I am using Namedpipes communication(C++) to transfer data between two processes. For the sake of comfort, I am using wstring to transfer the data and everything is fine at the transfer end. I am not able to receive the total data on the receiving end. The following is the transfer end code.
wstringstream send_data;
send_data << "10" << " " << "20" << " " << "30" << " " << "40" << " " << "50" << " " << "60" << "\0" ;
DWORD numBytesWritten = 0;
result = WriteFile(
pipe, // handle to our outbound pipe
send_data.str().c_str(), // data to send
send_data.str().size(), // length of data to send (bytes)
&numBytesWritten, // will store actual amount of data sent
NULL // not using overlapped IO
);
The following is the receiving end code.
wchar_t buffer[128];
DWORD numBytesRead = 0;
BOOL result = ReadFile(
pipe,
buffer, // the data from the pipe will be put here
127 * sizeof(wchar_t), // number of bytes allocated
&numBytesRead, // this will store number of bytes actually read
NULL // not using overlapped IO
);
if (result) {
buffer[numBytesRead / sizeof(wchar_t)] = '\0'; // null terminate the string
wcout << "Number of bytes read: " << numBytesRead << endl;
wcout << "Message: " << buffer << endl;
}
The result in buffer contains only 10 20 30 Can someone please explain me why the data is truncated.
VTK: Rotate actor programmatically while vtkRenderWindowInteractor is active
I'm trying to rotate a vtkActor using vtkActor::RotateZ and then calling vtkRenderWindow::Render. It works fine (it rotates the actor) but I can't move, resize, or even focus the window.
I suspected this was caused due to something not catching operating system events, so I added a vtkRenderWindowInteractor to the mix. Now I can move, resize and focus the window, but the actor is not rotating anymore.
I've isolated the code in the snippet below, comment line 43 to see both effects:
renderWindowInteractor->Start();
I'm compiling VTK 6.2 with mingw-w64 (GCC 4.9.1), running in Windows 8.1. I've uploaded the code in this repo with a small CMake setup so you can test it easily.
Thanks for your help!
constexpr float planeWidth = 200.0f;
constexpr float planeHeight = 100.0f;
int main()
{
auto renderer = vtkRenderer::New();
// Create render window
auto renWin = vtkRenderWindow::New();
renWin->AddRenderer(renderer);
renWin->SetSize(600,600);
// Create a plane
auto texturedPlane = vtkActor::New();
auto plane = vtkPlaneSource::New();
plane->SetOrigin(0, planeHeight, 0);
plane->SetPoint1(planeWidth, planeHeight, 0);
plane->SetPoint2(0, 0, 0);
auto planeMapper = vtkPolyDataMapper::New();
planeMapper->SetInputConnection(plane->GetOutputPort());
texturedPlane->SetMapper(planeMapper);
texturedPlane->SetOrigin(planeWidth / 2, planeHeight, 0);
renderer->AddActor(texturedPlane);
renderer->ResetCamera();
// Create a RenderWindowInteractor
auto renderWindowInteractor = vtkRenderWindowInteractor::New();
renderWindowInteractor->SetRenderWindow(renWin);
renderWindowInteractor->Start(); // <-- Comment this line!
// Render
float rot = 0.0f;
while(true)
{
texturedPlane->SetOrientation(0,0,0);
texturedPlane->RotateZ(rot++);
renWin->Render();
}
}
inserting elements with duplicate keys gives same result std::map and std::multimap
I am writing a program that implements a uni-directional graph using std::map or std::multimap. I have to search for the key and then copy the vector values corresponding to that key into a new location in the map. Specifically, I am copying elements corresponding to 'find_key' into location pointed by 'mykey'. I find that both map and multimap give me the same result (no duplicate keys). How can I fix this using multimap? mymap is a map, mymultimap is a multimap. mymap[find_key] contains the vector values that I am trying to copy. I expected to be able to copy them (while retaining the original values in the multimap) using multimap. But it does not work. This is what I have so far:
for (vector<string>::const_iterator itr =mymap.find(mykey)->second.begin(); itr!=mymap.find(mykey)->second.end();++itr){
string find_key;
stringstream sso(*itr);
if (! (sso >> find_key))
{
cout<< "ERROR failed to convert value"<<endl;
}
auto& mapit= mymap.find(find_key);
if (mapit == mymap.end()) {
std::cout << "key not found" << std::endl;
} else {
mymap.insert(pair<string, vector<string>>(mykey,mymap[find_key]));
mymultimap.insert(pair<string, vector<string>>(mykey,mymap [find_key]));
}}}